我需要没有授权属性的创建动作,但我需要在User.Identity.IsAuthenticated中获取价值。
启动:
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultSignInScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.RequireHttpsMetadata = false;
options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = AuthOptions.ISSUER,
ValidateAudience = true,
ValidAudience = AuthOptions.AUDIENCE,
ValidateLifetime = true,
IssuerSigningKey = AuthOptions.GetSymmetricSecurityKey(),
ValidateIssuerSigningKey = true,
};
});
app.UseAuthentication();
令牌:
[HttpPost("/token")]
public async Task Token([FromBody] User user)
{
var username = user.Login;
var password = user.Password;
var identity = await GetIdentityAsync(username, password);
if (identity == null)
{
Response.StatusCode = 400;
await Response.WriteAsync("Invalid username or password.");
return;
}
var now = DateTime.UtcNow;
var jwt = new JwtSecurityToken(
issuer: AuthOptions.ISSUER,
audience: AuthOptions.AUDIENCE,
notBefore: now,
claims: identity.Claims,
expires: now.Add(TimeSpan.FromMinutes(AuthOptions.LIFETIME)),
signingCredentials: new SigningCredentials(AuthOptions.GetSymmetricSecurityKey(),
SecurityAlgorithms.HmacSha256));
var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);
var response = new
{
access_token = encodedJwt,
user = new
{
login = user.Login,
role = identity.FindFirst(ClaimsIdentity.DefaultRoleClaimType).Value
}
};
Response.ContentType = "application/json";
await Response.WriteAsync(JsonConvert.SerializeObject(response,
new JsonSerializerSettings { Formatting = Formatting.Indented }));
}
async Task<ClaimsIdentity> GetIdentityAsync(string userName, string password)
{
var result = await _signInManager.PasswordSignInAsync(userName, password, false, false);
if (result.Succeeded)
{
var user = await _userManager.FindByNameAsync(userName);
if (user != null)
{
var role = (await _userManager.GetRolesAsync(user)).SingleOrDefault();
var claims = new List<Claim>
{
new Claim(ClaimsIdentity.DefaultNameClaimType, user.UserName),
new Claim(ClaimsIdentity.DefaultRoleClaimType, role)
};
return new ClaimsIdentity(claims, "Token", ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType);
}
}
return null;
}
控制器:
[HttpGet]
public IEnumerable<Book> Get()
{
var isAuth = User.Identity.IsAuthenticated;
}
User.Identity.IsAuthenticated始终为false。但是,如果我添加带有参数AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme的Authorize属性,则User.Identity.IsAuthenticated为true。
如何解决此问题?有任何变体吗?
答案 0 :(得分:0)
我在控制器之前添加Authorize with scheme,在我的方法之前添加AllowAnonymous。这可行