这是身份验证方案:
services.AddAuthentication(option =>
{
option.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
option.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
option.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.SaveToken = true;
options.RequireHttpsMetadata = false;
options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters()
{
ValidateIssuer = true,
ValidateAudience = true,
ValidIssuer = Configuration["JWT:ValidAudience"],
ValidAudience = Configuration["JWT:ValidIssuer"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JWT:Secret"]))
};
});
这是我的管道:
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors(); //custom
app.UseAuthentication(); //CUSTOM
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
如果我删除Authorize
控制器顶部的属性,则请求会成功发送,但如果添加它则不起作用。
[Route("api/[controller]")]
[ApiController]
[Authorize]//(Roles = UserRoles.Admin)]
public class ValuesController : ControllerBase
{
// GET: api/<ValuesController>
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
如果我删除该Authorize
属性,此代码将起作用。即使没有任何角色,它也不起作用。
这是我的appSettings.json
:
"JWT": {
"ValidAudience": "User",
"ValidIssuer": "https://localhost:44336",
"Secret": "ThisIsMySecretKEYadadasdasd939239" // MUST BE 16 CHARACTERS
}
这是登录代码:
public async Task<TokenModel> SignIn(SignInModel model)
{
var user = await _context.FindByNameAsync(model.UserName);
if (user != null && await _context.CheckPasswordAsync(user, model.Password)) //Rocko@135
{
var authClaims = new List<Claim>
{
new Claim(ClaimTypes.Name, user.UserName),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
};
var userRoles = await _context.GetRolesAsync(user);
foreach (var userRole in userRoles)
{
authClaims.Add(new Claim(ClaimTypes.Role, userRole));
}
var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JWT:Secret"]));
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: _configuration["JWT:ValidIssuer"],
audience: _configuration["JWT:ValidAudience"],
expires: DateTime.Now.AddDays(2),
claims: authClaims,
signingCredentials: credentials);
return new TokenModel
{
Token = new JwtSecurityTokenHandler().WriteToken(token),
Expiration = token.ValidTo,
Username = user.UserName
};
}
else
{
return new TokenModel
{
Token = null,
Expiration = null,
Username = string.Empty
};
}
}
这是我的智威汤逊
https://jwt.io/#debugger-io?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoiUm9ja28iLCJqdGkiOiI0NTQ2MjhkMy1jMGM1LTQ1MTUtODQ0My1kMDQ4Y2ZhNzM1NWYiLCJodHRwOi8vc2NoZW1hcy5taWNyb3NvZnQuY29tL3dzLzIwMDgvMDYvaWRlbnRpdHkvY2xhaW1zL3JvbGUiOiJBZG1pbiIsImV4cCI6MTcxMTA1NDkzNSwiaXNzIjoiaHR0cHM6Ly9sb2NhbGhvc3Q6NDQzMzYiLCJhdWQiOiJVc2VyIn0.FQBlJENwQWzuvQ1NwzRBaTuk7I3h2YBPxhWo1vT7PUw