Answers for "laravel 7 api authentication"

PHP
3

laravel token authentication

# Database Preparation
// add api_token to users table
Schema::table('users', function ($table) {
    $table->string('api_token', 80)->after('password')
                        ->unique()
                        ->nullable()
                        ->default(null);
});

// Create token for existing users, code can also be added to registerController
    $token = Str::random(60);
    $user = User::find(1);
    $user->api_token = hash('sha256', $token); // <- This will be used in client access
    $user->save();



//config/auth.php
    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'api' => [
            'driver' => 'token', // <- Add this entry
            'provider' => 'users',
            'hash' => false,
        ],
    ],

          
          
//routes/api.php
    // Add "middleware('auth:api')" as below        
	Route::middleware('auth:api')->get('/user', function (Request $request) {
        return $request->user();
    });          



//client access example (in Vue js)

axios.get('http://example.com/api/user', 
          {
  headers: { 
    'Accept': 'application/json', 
    'Authorization': 'Bearer '+ 'user-api-token'
  }
}
         )
  .then(function (response) {
  // handle success
  console.log(response);
})
  .catch(function (error) {
  // handle error
  console.log(error);
})
Posted by: Guest on October-09-2020
0

Laravel api login

public function login(Request $request){
        $fields = $request->validate([

         'email'=>'required|string|email',
         'password'=>'required|string'   
        ]);

        //Check email

        $user= User::where('email', $fields['email'])->first();

        //Check Password
        if(!$user || !Hash::check($fields['password'], $user->password) ){
            return response([
                'message'=>'Invalid Credentials'
            ], 401);
        }

        $token = $user->createToken('myapptoken')->plainTextToken;

        $response= [
            'user' => $user,
            'token'=> $token
        ];

        return response($response, 201);
    }
Posted by: Guest on August-02-2021
-1

how auth with api in laravel

$data = $request->all();
Auth::attempt(['email'=>$data['email'] , 'password'=>$data['password']])
Posted by: Guest on June-18-2021

Code answers related to "laravel 7 api authentication"

Browse Popular Code Answers by Language