【问题标题】:Authentication in Laravel API with sanctum使用 sanctum 在 Laravel API 中进行身份验证
【发布时间】:2023-03-29 03:07:01
【问题描述】:

我一直在使用 POSTMAN 和浏览器访问我的登录端点,但我总是遇到“未经授权”错误。我已经在 config 文件夹中添加了 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>

【问题讨论】:

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


    【解决方案1】:

    你错过了 url 中的 api。 api/sanctum/csrf-cookie

    【讨论】:

      【解决方案2】:

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

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

      });

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

      【讨论】:

        猜你喜欢
        • 2021-12-23
        • 1970-01-01
        • 2023-03-10
        • 2020-09-22
        • 2013-01-05
        • 2016-05-18
        • 2020-09-09
        • 2022-12-04
        • 2021-02-08
        相关资源
        最近更新 更多