Laravel Passport 401 Unauthorized Error using Apac

2020-05-07 07:17发布

问题:

i am trying to connect a generate a laravel user API using vue and laravel passport but i keep getting an authorization error in my headers . This ismy code

<script>
import Hello from './components/Hello'

export default {
  name: 'app',

  components: {
    Hello
  },
  created () {
    const postData = {
      grant_type: 'password',
      client_id: 2,
      client_secret: 'sXdg5nOO4UU2muiHaQnTq4hDQjyj17Kd9AeKuNEx',
      username: 'robertrutenge@gmail.com',
      password: 'password',
      scope: ''

    }
    this.$http.post('http://localhost:8000/oauth/token', postData)

   .then(response => {
     console.log(response)

     const header = {
       'Accept': 'application/json',
       'Authorization': ~'Bearer ' + response.body.access_token
     }
     this.$http.get('http://localhost:8000/api/user', {headers: header})

     .then(response => {
       console.log(response)
     })
   })
  }
}
</script>

I have done a research and most answers suggest modifying apache config file or .htaccess file but that also does not seem to work on my end . Any help will be appreciated :-)

回答1:

this is not problem on in vue.js or larvel. i moved my l Laravel API from Apache to nginx then working fine. i updated my middleware handler like this. then working fine on Apache server

  $origin = $request->server()['HTTP_ORIGIN'];

            if(in_array($origin, $url)){
                header('Access-Control-Allow-Origin: '. $origin);
                header('Access-Control-Allow-Headers: Origin, Content-Type, Accept, Authorization, X-Csrf-Token'); 

            }


回答2:

i think if your vue app and laravel app is combine, then you can use your api without any authorization header you just need to send X-CSRF-TOKEN and send that token with each request no need to send authorization check here

https://laravel.com/docs/5.3/passport#consuming-your-api-with-javascript



回答3:

resolve (2) go to AuthServiceProvider.php

keypoint:set expiration of token

Passport::tokensExpireIn(Carbon::now()->addDays(1));

You must to set token expiration cant be infinite