.Net Core 3.1更新:
David Fowler(ASP .NET
Core团队的架构师)汇集了一组非常简单的任务应用程序,其中包括演示JWT的简单应用程序。我很快将把他的更新和简单化的风格纳入本文。
为.Net Core 2更新:
此答案的先前版本使用RSA;如果生成令牌的相同代码也正在验证令牌,则实际上是没有必要的。但是,如果您要分配职责,则可能仍想使用的实例来执行此操作
Microsoft.IdentityModel.Tokens.RsaSecurityKey。
创建一些常量,稍后我们将使用它;这是我所做的:
const string TokenAudience = "Myself";
const string TokenIssuer = “MyProject”;
将此添加到您的Startup.cs的中
ConfigureServices
。稍后我们将使用依赖项注入来访问这些设置。我假设您authenticationConfiguration
是一个ConfigurationSection
或Configuration
对象,以便可以为调试和生产使用不同的配置。确保您安全地存储密钥!它可以是任何字符串。var keySecret = authenticationConfiguration["JwtSigningKey"];
var symmetricKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(keySecret));
services.AddTransient(_ => new JwtSignInHandler(symmetricKey));
services.AddAuthentication(options =>
{
// This causes the default authentication scheme to be JWT.
// Without this, the Authorization header is not checked and
// you’ll get no results. However, this also means that if
// you’re already using cookies in your app, they won’t be
// checked by default.
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.TokenValidationParameters.ValidateIssuerSigningKey = true;
options.TokenValidationParameters.IssuerSigningKey = symmetricKey;
options.TokenValidationParameters.ValidAudience = JwtSignInHandler.TokenAudience;
options.TokenValidationParameters.ValidIssuer = JwtSignInHandler.TokenIssuer;
});
我已经看到其他答案会更改其他设置,例如
ClockSkew;设置了默认值,使其可以在时钟不完全同步的分布式环境中工作。这些是您唯一需要更改的设置。
- 设置身份验证。在需要您的
User
信息的任何中间件之前,您应该有此行app.UseMvc()
。app.UseAuthentication();
请注意,这不会导致您的令牌与
SignInManager或其他任何东西一起发出。您将需要提供自己的输出JWT的机制-参见下文。
您可能需要指定一个
AuthorizationPolicy
。这将允许您使用来指定仅允许Bearer令牌作为身份验证的控制器和操作[Authorize("Bearer")]。services.AddAuthorization(auth =>
{
auth.AddPolicy(“Bearer”, new AuthorizationPolicyBuilder()
.AddAuthenticationTypes(JwtBearerDefaults.AuthenticationType)
.RequireAuthenticatedUser().Build());
});这是棘手的部分:构建令牌。
class JwtSignInHandler
{
public const string TokenAudience = “Myself”;
public const string TokenIssuer = “MyProject”;
private readonly SymmetricSecurityKey key;public JwtSignInHandler(SymmetricSecurityKey symmetricKey){ this.key = symmetricKey;}public string BuildJwt(ClaimsPrincipal principal){ var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var token = new JwtSecurityToken( issuer: TokenIssuer, audience: TokenAudience, claims: principal.Claims, expires: DateTime.Now.AddMinutes(20), signingCredentials: creds ); return new JwtSecurityTokenHandler().WriteToken(token);}}
然后,在需要令牌的控制器中,如下所示:
[HttpPost]public string AnonymousSignIn([FromServices] JwtSignInHandler tokenFactory){ var principal = new System.Security.Claims.ClaimsPrincipal(new[] { new System.Security.Claims.ClaimsIdentity(new[] { new System.Security.Claims.Claim(System.Security.Claims.ClaimTypes.Name, "Demo User") }) }); return tokenFactory.BuildJwt(principal);}在这里,我假设您已经有一个校长。如果您使用的是Identity,则可以使用
IUserClaimsPrincipalFactory<>将转换
User为
ClaimsPrincipal。
要测试它 :获得令牌,将其放入jwt.io的表单中。我上面提供的说明还允许您使用配置中的密码来验证签名!
如果要在HTML页面的部分视图中呈现此视图,并与.Net 4.5中的仅承载身份验证结合使用,则现在可以使用进行
ViewComponent
相同的操作。它与上面的“控制器操作”代码基本相同。



