After login, I have jwt token and can login. But when I called other api in fetch function with jwt token, my api call got unauthorized. I cannot call api.
NET 6 Api
Program.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"]))
};
});
LoginController.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);
UserController.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);
utils.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);
}
I have jwt token. Inside the jwt token, it shows my role is developer which matches with NET Api's [Authorize(Roles = RoleConstant.Developer)]. But I still cannot call GetUsers and it returns 'Unauthorization'. I tried 'Bearer ${token}' in 'Authorization' header too and it didn't work.
Anything I miss in code?
CodePudding user response:
You should use this;
headers = new Headers({ 'Authorization': 'Bearer ' token, 'Content-Type': 'application/json' });