Laravel API中使用Sanctum进行身份验证

时间:2020-06-30 15:35:10

标签: php laravel laravel-7 laravel-sanctum laravel-api

我一直在使用POSTMAN和浏览器来访问登录端点,但是我总是遇到“未授权”错误。我在配置文件夹中添加了Sanctum和Cors所需的配置。

这是我的代码

public function login(Request $request) {
     try {
        $request->validate([
            'email' => 'required|string|email',
            'password' => 'required',
        ]);
        if ($this->hasTooManyLoginAttempts($request)){
        //Fire the lockout event.
        $this->fireLockoutEvent($request);
        return response()->json([
            'message' => 'Account Locked, too many attempts, try again in 2 minutes'
        ], 429);
    }
        $credentials = request(['email', 'password']);
        if(!Auth::attempt($credentials)) {
          $this->incrementLoginAttempts($request);
            return response()->json([
                'message' => 'Unauthorized'
            ], 401);
          }
        $user = $request->user();
        //$tokenResult = $user->createToken('Personal Access Token');
        $tokenResult = $user->createToken('authToken')->plainTextToken;
        $token = $tokenResult;
        if ($request->remember_me)
            $token->expires_at = Carbon::now()->addWeeks(1);
        $token->save();
        return response()->json([
            'access_token' => $tokenResult,
            'token_type' => 'Bearer',
            'expires_at' => Carbon::parse($tokenResult->expires_at)->toDateTimeString()
        ], 201);
      }
      catch (Exception $error) {
         return response()->json([
          'status_code' => 500,
          'message' => 'Error in Login',
          'error' => $error,
        ]);
      }
    }

这是我的vuejs文件,我从此处单击登录端点,并且我的API已版本化。

<template>
  <div class="row justify-content-center">
      <div class="form-column col-md-8">
                      <div class="form-group row">
                             <label for="ft-placeholder" class="ft-placeholder">
                                <input id="email" type="email" placeholder=" " required autocomplete="off" v-model="container.email" autofocus>
                                <span class="label">Email Address</span>
                                <span class="focus-placeholder"></span>
                               </label>
                              </div>
                      <div class="form-group row">
                             <label for="ft-placeholder" class="ft-placeholder">
                              <input id="password" type="password" placeholder=" " required autocomplete="new-password" v-model="container.password">
                               <span class="label">Password</span>
                               <span class="focus-placeholder"></span>
                              </label>
                              
                             </div>
                      <div class="form-group row n-b-padded">
                              <button @click="initiate" class="btn">
                                  Sign in
                              </button>
                          </div>
              
          </div>
</template>

<script>

    export default {
    name: "login",
    data() {
      return {
       container:{
       email:null,
       password:null
       }
       loading: false,
       errors: null
    };
  },
    methods: {
      
      initiate() {
        this.errors = {};
        this.loading = true;
        axios.get('/sanctum/csrf-cookie').then(response => {
        axios.post('api/v1/auth/login', this.container).then(response => {
        this.loading = false;
        this.container = {}; //Clear input container.
        
       }).catch(error => {
       this.loading = false;
      
       });
     });
      }
      }
    }
</script>

2 个答案:

答案 0 :(得分:0)

您是否在路由中添加了圣殿中间件。

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();

});

https://laravel.com/docs/7.x/verification

答案 1 :(得分:0)

您错过了网址中的api。 api / sanctum / csrf-cookie