登錄后,我有 jwt 令牌并且可以登錄。但是當我使用 jwt 令牌在 fetch 函式中呼叫其他 api 時,我的 api 呼叫未經授權。我不能呼叫 api。
NET 6 API
程式.cs
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.SaveToken = true;
options.RequireHttpsMetadata = false;
options.TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuer = true,
ValidateAudience = true,
ValidAudience = builder.Configuration["JWT:ValidAudience"],
ValidIssuer = builder.Configuration["JWT:ValidIssuer"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["JWT:SecretKey"]))
};
});
登錄控制器.cs
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.UTF8.GetBytes(_configuration["JWT:SecretKey"]);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new Claim[]
{
new Claim(SessionConstant.UserName, user.UserName!),
new Claim(ClaimTypes.Role, userRole)
}),
Issuer = _configuration["JWT:ValidIssuer"],
Audience = _configuration["JWT:ValidAudience"],
Expires = DateTime.Now.AddMinutes(20),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
var tokenString = tokenHandler.WriteToken(token);
用戶控制器.cs
[Authorize(Roles = RoleConstant.Developer)]
[HttpGet("GetUsers")]
public async Task<JsonResult> GetUsers(User user)
Sveltekit
index.svelte
// get = fetch with 'get' method.
let result = await get(`api/User/GetUsers?id=${id}`, accesstoken);
實用程式.ts
export async function get(endpoint, token) {
let headers = {};
if (token)
{
headers = {
'Authorization': `JWT ${token}`
};
}
return await fetch(`${baseApiUrl}/${endpoint}`, {
method: 'GET',
headers
}).then(r => r.json())
.then(x => x);
}
我有 jwt 令牌。在 jwt 令牌中,它顯示我的角色是與 NET Api 的 [Authorize(Roles = RoleConstant.Developer)] 匹配的開發人員。但我仍然無法呼叫 GetUsers,它回傳“未授權”。我也在“授權”標頭中嘗試了“Bearer ${token}”,但沒有成功。
我在代碼中遺漏了什么?
uj5u.com熱心網友回復:
你應該使用這個;
headers = new Headers({ 'Authorization': 'Bearer ' token, 'Content-Type': 'application/json' });
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/457623.html
