小编典典

ASP.NET Core中基于令牌的身份验证(刷新)

c#

我正在使用ASP.NET
Core应用程序。我正在尝试实现基于令牌的身份验证,但无法弄清楚如何使用新的安全系统

我的情况: 客户端请求令牌。我的服务器应授权用户并返回access_token,客户端将在随后的请求中使用它。

这是有关实现我真正需要的两篇很棒的文章:

问题是-在ASP.NET Core中如何做同样的事情对我来说并不明显。

我的问题是: 如何配置ASP.NET Core Web
Api应用程序以与基于令牌的身份验证一起使用?我应该朝哪个方向前进?您是否撰写了有关最新版本的文章,或者知道在哪里可以找到这些文章?

谢谢!


阅读 874

收藏
2020-05-19

共1个答案

小编典典

根据Matt
Dekrey的出色回答
,我创建了一个完全有效的基于令牌的身份验证示例,它针对ASP.NET
Core(1.0.1)。你可以找到完整的代码在这个仓库在GitHub上(替代分支1.0.0-RC1beta8β7的),但在短暂的,重要的步骤是:

为您的应用生成密钥

在我的示例中,每次应用启动时,我都会生成一个随机密钥,您需要生成一个并将其存储在某个位置,然后将其提供给您的应用。有关如何生成随机密钥以及如何从.json文件导入它的信息,请参见此文件。正如@kspearrin在评论中所建议的那样,Data
Protection API
似乎是“正确”管理密钥的理想候选者,但是我还没有解决这个问题。如果解决了,请提交拉取请求!

Startup.cs-ConfigureServices

在这里,我们需要为签名的令牌加载一个私钥,当令牌出现时,我们还将用它来验证令牌。我们将密钥存储在类级别的变量中key,该变量将在下面的Configure方法中重复使用。TokenAuthOptions是一个简单的类,其中包含我们在TokenController中创建我们的密钥所需的签名身份,受众和发行者。

// Replace this with some sort of loading from config / file.
RSAParameters keyParams = RSAKeyUtils.GetRandomKey();

// Create the key, and a set of token options to record signing credentials 
// using that key, along with the other parameters we will need in the 
// token controlller.
key = new RsaSecurityKey(keyParams);
tokenOptions = new TokenAuthOptions()
{
    Audience = TokenAudience,
    Issuer = TokenIssuer,
    SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.Sha256Digest)
};

// Save the token options into an instance so they're accessible to the 
// controller.
services.AddSingleton<TokenAuthOptions>(tokenOptions);

// Enable the use of an [Authorize("Bearer")] attribute on methods and
// classes to protect.
services.AddAuthorization(auth =>
{
    auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
        .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme‌​)
        .RequireAuthenticatedUser().Build());
});

我们还设置了授权策略,以允许我们[Authorize("Bearer")]在希望保护的端点和类上使用。

Startup.cs-配置

在这里,我们需要配置JwtBearerAuthentication:

app.UseJwtBearerAuthentication(new JwtBearerOptions {
    TokenValidationParameters = new TokenValidationParameters {
        IssuerSigningKey = key,
        ValidAudience = tokenOptions.Audience,
        ValidIssuer = tokenOptions.Issuer,

        // When receiving a token, check that it is still valid.
        ValidateLifetime = true,

        // This defines the maximum allowable clock skew - i.e.
        // provides a tolerance on the token expiry time 
        // when validating the lifetime. As we're creating the tokens 
        // locally and validating them on the same machines which 
        // should have synchronised time, this can be set to zero. 
        // Where external tokens are used, some leeway here could be 
        // useful.
        ClockSkew = TimeSpan.FromMinutes(0)
    }
});

令牌控制器

在令牌控制器中,您需要一种方法来使用Startup.cs中加载的密钥生成签名密钥。我们已经在Startup中注册了TokenAuthOptions实例,因此我们需要将其注入TokenController的构造函数中:

[Route("api/[controller]")]
public class TokenController : Controller
{
    private readonly TokenAuthOptions tokenOptions;

    public TokenController(TokenAuthOptions tokenOptions)
    {
        this.tokenOptions = tokenOptions;
    }
...

然后,您需要在处理程序中为登录端点生成令牌,在我的示例中,我使用用户名和密码,并使用if语句验证用户名和密码,但是您需要做的关键是创建或加载声明身份并为此生成令牌:

public class AuthRequest
{
    public string username { get; set; }
    public string password { get; set; }
}

/// <summary>
/// Request a new token for a given username/password pair.
/// </summary>
/// <param name="req"></param>
/// <returns></returns>
[HttpPost]
public dynamic Post([FromBody] AuthRequest req)
{
    // Obviously, at this point you need to validate the username and password against whatever system you wish.
    if ((req.username == "TEST" && req.password == "TEST") || (req.username == "TEST2" && req.password == "TEST"))
    {
        DateTime? expires = DateTime.UtcNow.AddMinutes(2);
        var token = GetToken(req.username, expires);
        return new { authenticated = true, entityId = 1, token = token, tokenExpires = expires };
    }
    return new { authenticated = false };
}

private string GetToken(string user, DateTime? expires)
{
    var handler = new JwtSecurityTokenHandler();

    // Here, you should create or look up an identity for the user which is being authenticated.
    // For now, just creating a simple generic identity.
    ClaimsIdentity identity = new ClaimsIdentity(new GenericIdentity(user, "TokenAuth"), new[] { new Claim("EntityID", "1", ClaimValueTypes.Integer) });

    var securityToken = handler.CreateToken(new Microsoft.IdentityModel.Tokens.SecurityTokenDescriptor() {
        Issuer = tokenOptions.Issuer,
        Audience = tokenOptions.Audience,
        SigningCredentials = tokenOptions.SigningCredentials,
        Subject = identity,
        Expires = expires
    });
    return handler.WriteToken(securityToken);
}

就是这样。只需将其添加[Authorize("Bearer")]到要保护的任何方法或类中,如果在没有令牌的情况下尝试访问它,将会收到错误消息。如果要返回401错误而不是500错误,则需要注册一个自定义异常处理程序,如我在此处的示例所示

2020-05-19