Passport Laravel Rest API Auth With Normal Design

落爺英雄遲暮 提交于 2019-12-07 11:48:00

问题


I have Completely assigned the Passport REST API and i get token and tested on PostMan

and it retrieve the data with this Auth

this is normal js html with laravel blade view (NOT VUE.JS)

<script>
$.ajax({
  method: 'POST',
  dataType: 'json',
  url: "**********/api/User/GetPost",
  headers: {
      'Authorization':'Bearer Tokenblablabla',
      'Content-Type':'application/json'
  },
  data: null,
  success: function(data){
  console.log('succes: '+data);
  }

});

this is the controller function

    public function GetPosts(Request $request){
         $data3="Test"
         return response()->json([
            'Success'=> true,
            'Message'=>'8',
            'Data' => $data3,
         ], 200);
    }

this is api.php // this will return a json with posts details

Route::group(['middleware'=>'auth:api'],function(){
      Route::post('/GetPosts','Wall\PostsController@GetPosts');
});

this is web.php

Route::get('/GetPost', function () {
     return view('getpostview');
})->middleware('auth:api');

i get confused i cannot send Auth beside i cannt retrieve the json from API iam 3 days STUCK in this problem what iam need to connect the normal laravel blade to another laravel passport REST API


回答1:


The Blade templates generated by Laravel for authentication can works with Laravel Passport, JWT, etc.

The thing that you need to do is configure Passport properly.

Do not forget to modify the driver specified in the API config/auth.php file:

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    'api' => [
        'driver' => 'passport',
        'provider' => 'users',
    ],
],

Also, to retrieve a json response add this header in your requests:

'Accept' : 'application/json'

So your request should be like this:

$response = $client->request('GET', 'some-url/api/getPosts', [
    'headers' => [
        'Accept' => 'application/json',
        'Authorization' => 'Bearer '.$accessToken,
    ],
]);

Side note

I encourage you to read this presentation, "Teaching a Dog to REST", to create a clean, intuitive and easy to learn API properly using HTTP verbs and good practices.



来源:https://stackoverflow.com/questions/48975428/passport-laravel-rest-api-auth-with-normal-design

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!