【发布时间】:2020-01-08 21:45:54
【问题描述】:
各位专家,我最近对 OAuth 以及 JWT 的工作原理进行了很多探索。本质上应该有一个发出令牌的AuthServer,并且应该有一个ServiceAPI(应用服务器)将令牌用于客户端!! .我也知道令牌由 3 部分组成,标头、有效负载和签名...
现在,如果我想构建一个 API,它既可以进行身份验证又可以发出 JWT 令牌,然后再提供服务。这听起来像是带有令牌的基本身份验证!!
我也不确定我编写的代码是否反映了这个概念(令牌发行者与 ServiceAPI 相同)。我正在按照this 文章构建一个 .net core 2.1 Web API。
在 Startup.cs 中
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
//Authentication
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.Authority = "https://localhost:44387/";
options.Audience = "JWT:Issuer";
options.TokenValidationParameters.ValidateLifetime = true;
options.TokenValidationParameters.ClockSkew = TimeSpan.FromMinutes(5);
options.RequireHttpsMetadata = false;
});
services.AddAuthorization(options =>
{
options.AddPolicy("GuidelineReader", p => {
p.RequireClaim("[url]", "GuidelineReader");
});
});
}
我还添加了一个 LoginController 来生成令牌并返回它...
[AllowAnonymous]
[HttpPost]
public IActionResult Login([FromBody]Application login)
{
IActionResult response = Unauthorized();
var user = AuthenticateUser(login);
if (user != null)
{
var tokenString = GenerateJSONWebToken(user);
response = Ok(new { token = tokenString });
}
return response;
}
private string GenerateJSONWebToken(Application appInfo)
{
var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(_config["Jwt:Issuer"],
_config["Jwt:Issuer"],
null,
expires: DateTime.Now.AddMinutes(120),
signingCredentials: credentials);
return new JwtSecurityTokenHandler().WriteToken(token);
}
下面有什么区别
- options.Authority
- options.Audience(我认为是发送https请求的应用程序)
- options.Issuer
【问题讨论】:
标签: oauth-2.0 asp.net-core-mvc jwt asp.net-core-webapi asp.net-core-2.1