从Matt Dekrey's fabulous answer 开始,我创建了一个基于令牌的身份验证的完整工作示例,针对 ASP.NET Core (1.0.1)。您可以找到完整的代码in this repository on GitHub(1.0.0-rc1、beta8、beta7 的替代分支),但简而言之,重要的步骤是:
为您的应用程序生成密钥
在我的示例中,每次应用启动时我都会生成一个随机密钥,您需要生成一个并将其存储在某处并将其提供给您的应用程序。 See this file for how I'm generating a random key and how you might import it from a .json file。正如@kspearrin 在 cmets 中所建议的那样,Data Protection API 似乎是“正确”管理密钥的理想人选,但我还没有弄清楚这是否可能。如果你解决了,请提交一个拉取请求!
Startup.cs - 配置服务
在这里,我们需要为要签名的令牌加载一个私钥,我们还将使用它来验证令牌的出现。我们将密钥存储在类级变量key 中,我们将在下面的配置方法中重复使用该变量。 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)
}
});
TokenController
在令牌控制器中,您需要有一种方法来使用在 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 错误,则需要注册自定义异常处理程序 as I have in my example here。