我一直在使用 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>