一 Cookie认证
1 services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie();
2 app.UseAuthentication();
3 Microsoft.AspNetCore.Authorization.AuthorizeAttribute
4
var claims = new List<Claim>()
{
new Claim (ClaimTypes.Role,"admin"),
new Claim (ClaimTypes.Name,account),
};
var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
this.HttpContext.SignInAsync(new ClaimsPrincipal(identity));
二 Jwt认证
1
services.AddAuthentication(option =>
{
option.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
option.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(o =>
{
o.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
{
ValidIssuer = settings.Issurer,
ValidAudience = settings.Audience,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(settings.SecretKey)),
};
});
2 app.UseAuthentication();
3 Microsoft.AspNetCore.Authorization.AuthorizeAttribute
4
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name,"yan"),
new Claim (ClaimTypes.Role,"admin"),
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("SecretKey"));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken("Issurer", "Audience", claims, DateTime.Now, DateTime.Now.AddMinutes(30), creds);
return Ok(new
{
token = new JwtSecurityTokenHandler().WriteToken(token),
});
}
5 header中添加 Authorization : bearer 获得的token