Majeed
345
1
Laravel

How to add Bearer Access Token to a request header from Controller in Laravel

Posted 1 year ago by Majeed

I'm working on Laravel Passport to make a API Authentication system. After successful login i'm getting an access_token and for every request i need to add the Bearer access_token in request header. I want to add this Bearer access_token in request header from my controller.

Here, Is my Controller

class PassportController extends Controller
{

   public $successStatus = 200;

    public function login()
    { 
        if(Auth::attempt(['email' => request('email'), 'password' => request('password')])){ 
            $user = Auth::user(); 
            $success['token'] =  $user->createToken('MyApp')-> accessToken; 
            return response()->json(['success' => $success], $this-> successStatus); 
        } 
        else{ 
            return response()->json(['error'=>'Unauthorised'], 401); 
        } 
    }

    public function register(Request $request) 
    { 
        $validator = Validator::make($request->all(), [ 
            'name' => 'required', 
            'email' => 'required|email', 
            'password' => 'required', 
            'c_password' => 'required|same:password', 
        ]);
        if ($validator->fails()) { 
                    return response()->json(['error'=>$validator->errors()], 401);            
                }
        // $input = $request->all(); 
        //         $input['password'] = bcrypt($input['password']); 
        //         $user = User::create($input); 
                $user=new User();
                $user->name=$request->name;
                $user->email=$request->email;
                $user->password=bcrypt($request->password);
                $user->save();
                $success['token'] =  $user->createToken('MyApp')-> accessToken; 
                $success['name'] =  $user->name;
        return response()->json(['success'=>$success], $this-> successStatus); 
    }

    public function details(Request $request) 
    { 
        $user = Auth::user(); 
        
       //  'headers' => [
       //  'Accept' => 'application/json',
       //  'Authorization' => 'Bearer '.$accessToken,
       // ],
        $token=$request->post('/oauth/token', [
            'content-type' => 'application/json',
            'Accept' => 'application/json',
            'Authorization' => 'Bearer '.'mahgf1234567890',
        ]);
        //$token=$request->header('Authorization');


        return response()->json(['success' => $user,'token' => $token], $this-> successStatus); 
    } 

    
}

Please sign in or create an account to participate in this conversation.