a121984376  

一 Cookie认证

1  services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie();

2  app.UseAuthentication();

3 Microsoft.AspNetCore.Authorization.AuthorizeAttribute

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认证

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

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

posted on 2018-11-26 13:37  冰之玄岩,小小Programmer  阅读(208)  评论(0编辑  收藏  举报