我使用laravel 9和vue js 3组成API,当我想获得登录用户数据/认证用户时,我总是得到错误401,我试图找到一种方法并使用所有的方式,从配置设置等,我希望任何人都能帮助我,因为这是我第一次使用laravel sanctum
这是我的vue登录代码,我试图获得登录用户数据,但我总是得到401未经授权
const onSubmit = async () => {
isLoggingIn.value = true;
try {
await axios.get("http://localhost:8000/sanctum/csrf-cookie");
const { data } = await repository.login(credentials);
if (data) {
localStorage.setItem("access_token", data.access_token);
localStorage.setItem("user", JSON.stringify(data.user));
let response = await axios.get("http://localhost:8000/api/auth/profile");
console.log(response.data);
router.replace({ name: "restos" });
}
} catch (e) {
console.error(e);
}
isLoggingIn.value = false;
};
这是我的axios代码
const client = axios.create({
withCredentials: true,
baseURL: import.meta.env.VUE_APP_API_URL || "http://localhost:8000",
headers: {
"Content-Type": "application/json",
"X-Requested-With": "XMLHttpRequest",
},
});
my API routes
Route::post('/auth/login', [AuthenticationController::class, 'login'])->name('login');
Route::middleware('auth:sanctum')->group(function() {
Route::get('/auth/profile', [AuthenticationController::class, 'profile'])->name('auth.profile');
});
我Kernel.php
'api' => [
LaravelSanctumHttpMiddlewareEnsureFrontendRequestsAreStateful::class,
'throttle:api',
IlluminateRoutingMiddlewareSubstituteBindings::class,
],
我cors.php
'supports_credentials' => true,
然后是。env
SESSION_DRIVER=cookie
SESSION_LIFETIME=120
SESSION_DOMAIN=localhost
我想获得数据用户登录/认证用户,但总是得到401未经授权,非常感谢你的帮助,我很困惑这个
这是我上周的项目,也许能帮到你。
添加到User Model:
use IlluminateFoundationAuthUser as Authenticatable;
class User extends Authenticatable
{
use HasFactory,HasApiTokens;
protected $guarded = []; // like $fillable=[all]
}
路线:
Route::controller(UserController::class)->group(function(){
Route::post('/auth/signin','signin');
Route::post('/auth/signup','signup');
});
控制器:
class UserController extends Controller
{
public function signin(Request $request){
$credentials = $request->validate([
'email' => ['required', 'email'],
'password' => ['required'],
]);
$user = User::whereEmail($credentials['email'])->first();
if(Auth::attempt($credentials)){
return response()->json([
'message' => 'login success',
// send token to front-end
'token' => $user->createToken("API TOKEN")->plainTextToken
], 200);
}
return response()->json([
'message' => 'wrong email or password'
], 500);
}
public function signup(Request $request){
$request = $request->validate([
'email' => 'required | email | string',
'password' => 'required'
]);
User::create([
'email' => $request['email'],
'password' => bcrypt($request['password'])
]);
return response()->json([
'message' => 'registration success',
], 201);
}
}
,最后:
在我的首选项中,我创建了一个文件夹库并创建了axiosClient.js,其中包含:
import axios from 'axios';
export const axiosClient = axios.create({
withCredentials:true,
baseURL:'http://localhost:8000'
})
export const setTokenCSRF = (token) => axios.defaults.headers.common = `Bearer ${token}`
并在您的前端导入axiosClient.js,并使用setTokenCSRF函数从后端使用令牌csrf设置头axios,并在每个请求中自动使用此令牌。
这个令牌保存在数据库的personal_access_token表中。
和使用应该了解CSRF令牌的工作原理。对不起,我的英语不好。