JWT Same Application是Auth服务器和Application Server

时间:2019-09-06 01:54:38

标签: oauth-2.0 asp.net-core-mvc jwt asp.net-core-webapi asp.net-core-2.1

您好,我最近在OAuth和JWT的工作原理方面进行了很多探讨。本质上,应该有一个发布令牌的 AuthServer ,并且应该有一个将令牌用于客户端 ServiceAPI (应用服务器)! 。我也了解令牌由三部分组成,包括标头,有效载荷和签名...

现在,如果我想构建一个能够同时验证和颁发JWT令牌的API,然后再提供该服务。听起来像带有令牌的基本身份验证!

我也不确定我编写的代码是否反映了这一概念(令牌发行者与ServiceAPI相同)。在this文章之后,我正在构建.net核心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

1 个答案:

答案 0 :(得分:1)

  

options.Authority

Authority是令牌发行认证服务器的地址。在您的情况下,Web API会发出令牌,因此Authority将是Web API的URL。

  

options.Audience(我认为这是发送https请求的应用程序)

Audience表示传入令牌或令牌授予访问权限的资源的预期接收者。在您的方案中,Web api是客户端将使用JWT令牌访问的受保护资源,Web api将验证令牌以检查声明/签名。因此,Web API名称/ URL应为Audience

  

options.Issuer

Issuer标识构造和返回令牌的安全令牌服务(STS)。在您的方案中,Web api会验证用户凭证并返回令牌。因此,Web API名称/ URL为Issuer