Token Based Authentication in ASP.NET Core
我正在使用ASP.NET核心应用程序。我正在尝试实现基于令牌的身份验证,但无法找出如何为我的案例使用新的安全系统。我列举了一些例子,但它们对我没什么帮助,它们要么使用cookie认证,要么使用外部认证(github、microsoft、twitter)。
我的场景是:AngularJS应用程序应该请求
我找到了一篇关于使用ASP.NET Web API 2、OWIN和Identity实现当前版本的基于令牌的ASP.NET身份验证所需内容的优秀文章。但对于我来说,如何在ASP.NET核心中做同样的事情并不明显。
我的问题是:如何配置ASP.NET核心WebAPI应用程序以使用基于令牌的身份验证?
为.NET核心2更新:
此答案的早期版本使用了RSA;如果生成令牌的同一代码也在验证令牌,则实际上不需要这样做。但是,如果您在分配职责,那么您可能仍然希望使用
创建一些稍后将要使用的常量;以下是我所做的:
1 2 | const string TokenAudience ="Myself"; const string TokenIssuer ="MyProject"; |
把这个加到你的初创公司.cs的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | 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; }); |
号
我看到过其他答案会更改其他设置,如
设置身份验证。您应该在任何需要您的
1 | app.UseAuthentication(); |
请注意,这不会导致您的令牌与
您可以指定一个
1 2 3 4 5 6 | services.AddAuthorization(auth => { auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder() .AddAuthenticationTypes(JwtBearerDefaults.AuthenticationType) .RequireAuthenticatedUser().Build()); }); |
。
接下来是棘手的部分:构建令牌。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | 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); } } |
然后,在需要令牌的控制器中,如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 | [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); } |
。
这里,我假设你已经有了校长。如果您使用的是身份,那么可以使用
要测试它:获取一个令牌,将它放到jwt.io的表单中。我上面提供的说明还允许您使用配置中的秘密来验证签名!
如果您在HTML页面上的部分视图中结合.NET 4.5中的纯承载身份验证来呈现此内容,那么现在可以使用
工作从马特dekrey的精彩回答,我已经创建了一个基于令牌的认证协会工作的例子,对ASP.NET的核心工作(1.0.1)。你可以找到完整的代码库(替代在这个分支的1.0.0-rc1在GitHub,beta8,beta7),但在信中,重要的步骤是:
生成密钥为您的应用程序
在我的例子,我的随机密钥生成的每一次发射的应用程序,你需要一个地方产生和提供它的商店和它的应用程序。本文件的知识海洋(I’M生成随机密钥和你可以从一.json文件导入信息。在AS内的kspearrin red"的评论,似乎在数据保护API管理的理想候选键"正确",但我不曾出,而如果这是可能的。请提交请求,如果你拉工作!
startup.cs - configureservices
在这里,我们需要为我们的私人密钥A的负载和一个令牌符号。所以,我们将使用验证令牌是他们周围。我们储存的关键变量在类层次
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | // 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()); }); |
因此,我们已经建立了授权的政策是让美国在端点和使用
startup.cs配置
在这里,我们需要配置的jwtbearerauthentication:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | 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加载。我们已经注册的一tokenauthoptions实例在启动,所以我们需要一个构造函数将在tokencontroller:
1 2 3 4 5 6 7 8 9 10 | [Route("api/[controller]")] public class TokenController : Controller { private readonly TokenAuthOptions tokenOptions; public TokenController(TokenAuthOptions tokenOptions) { this.tokenOptions = tokenOptions; } ... |
那么你就需要在你的程序生成的登录令牌的端点,在我的例子我的用户名和密码以验证A和那些使用if语句,但关键的事情你需要做的是创建或负载基于身份和索赔令牌生成的那个:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | 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); } |
这应该是它。只是添加到任何方法或类
您可以查看OpenID Connect示例,这些示例演示了如何处理不同的身份验证机制,包括JWT令牌:
https://github.com/aspnet-contrib/aspnet.security.openidconnect.samples
如果您查看cordova后端项目,那么API的配置如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | // Create a new branch where the registered middleware will be executed only for non API calls. app.UseWhen(context => !context.Request.Path.StartsWithSegments(new PathString("/api")), branch => { // Insert a new cookies middleware in the pipeline to store // the user identity returned by the external identity provider. branch.UseCookieAuthentication(new CookieAuthenticationOptions { AutomaticAuthenticate = true, AutomaticChallenge = true, AuthenticationScheme ="ServerCookie", CookieName = CookieAuthenticationDefaults.CookiePrefix +"ServerCookie", ExpireTimeSpan = TimeSpan.FromMinutes(5), LoginPath = new PathString("/signin"), LogoutPath = new PathString("/signout") }); branch.UseGoogleAuthentication(new GoogleOptions { ClientId ="560027070069-37ldt4kfuohhu3m495hk2j4pjp92d382.apps.googleusercontent.com", ClientSecret ="n2Q-GEw9RQjzcRbU3qhfTj8f" }); branch.UseTwitterAuthentication(new TwitterOptions { ConsumerKey ="6XaCTaLbMqfj6ww3zvZ5g", ConsumerSecret ="Il2eFzGIrYhz6BWjYhVXBPQSfZuS4xoHpSSyD9PI" }); }); |
/providers/authorizationprovider.cs和该项目的ressourcecontroller中的逻辑也值得一看;)。
或者,您也可以使用以下代码来验证令牌(还有一个代码片段使其与信号器一起工作):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | // Add a new middleware validating access tokens. app.UseOAuthValidation(options => { // Automatic authentication must be enabled // for SignalR to receive the access token. options.AutomaticAuthenticate = true; options.Events = new OAuthValidationEvents { // Note: for SignalR connections, the default Authorization header does not work, // because the WebSockets JS API doesn't allow setting custom parameters. // To work around this limitation, the access token is retrieved from the query string. OnRetrieveToken = context => { // Note: when the token is missing from the query string, // context.Token is null and the JWT bearer middleware will // automatically try to retrieve it from the Authorization header. context.Token = context.Request.Query["access_token"]; return Task.FromResult(0); } }; }); |
号
对于颁发令牌,您可以使用OpenID Connect服务器包,如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | // Add a new middleware issuing access tokens. app.UseOpenIdConnectServer(options => { options.Provider = new AuthenticationProvider(); // Enable the authorization, logout, token and userinfo endpoints. //options.AuthorizationEndpointPath ="/connect/authorize"; //options.LogoutEndpointPath ="/connect/logout"; options.TokenEndpointPath ="/connect/token"; //options.UserinfoEndpointPath ="/connect/userinfo"; // Note: if you don't explicitly register a signing key, one is automatically generated and // persisted on the disk. If the key cannot be persisted, an exception is thrown. // // On production, using a X.509 certificate stored in the machine store is recommended. // You can generate a self-signed certificate using Pluralsight's self-cert utility: // https://s3.amazonaws.com/pluralsight-free/keith-brown/samples/SelfCert.zip // // options.SigningCredentials.AddCertificate("7D2A741FE34CC2C7369237A5F2078988E17A6A75"); // // Alternatively, you can also store the certificate as an embedded .pfx resource // directly in this assembly or in a file published alongside this project: // // options.SigningCredentials.AddCertificate( // assembly: typeof(Startup).GetTypeInfo().Assembly, // resource:"Nancy.Server.Certificate.pfx", // password:"Owin.Security.OpenIdConnect.Server"); // Note: see AuthorizationController.cs for more // information concerning ApplicationCanDisplayErrors. options.ApplicationCanDisplayErrors = true // in dev only ...; options.AllowInsecureHttp = true // in dev only...; }); |
编辑:我已经使用Aurelia前端框架和ASP.NET核心实现了一个基于令牌的身份验证实现的单页应用程序。还有一个信号R持久连接。但是,我没有进行任何DB实现。代码如下:https://github.com/alexandere-spieser/aureliaaspnetcoreauth
希望这有帮助,
最好的,
亚历克斯
有一个看它的openiddict a New Project(在时间写作)让它易于配置和创建的令牌的令牌在ASP.NET刷新智威汤逊5。在验证的令牌是由其他软件处理。
如果你使用一个
1 2 3 4 | services.AddIdentity<ApplicationUser, ApplicationRole>() .AddEntityFrameworkStores<ApplicationDbContext>() .AddDefaultTokenProviders() .AddOpenIddictCore<Application>(config => config.UseEntityFramework()); |
在
1 2 3 4 5 6 7 8 | app.UseOpenIddictCore(builder => { // tell openiddict you're wanting to use jwt tokens builder.Options.UseJwtTokens(); // NOTE: for dev consumption only! for live, this is not encouraged! builder.Options.AllowInsecureHttp = true; builder.Options.ApplicationCanDisplayErrors = true; }); |
你在
1 2 3 4 5 6 7 8 9 | // use jwt bearer authentication app.UseJwtBearerAuthentication(options => { options.AutomaticAuthenticate = true; options.AutomaticChallenge = true; options.RequireHttpsMetadata = false; options.Audience ="http://localhost:58292/"; options.Authority ="http://localhost:58292/"; }); |
有一个或两个其他的小东西,如您需要任何dbcontext从openiddictcontext。
你可以看到一个完整长度的解释在这个博客帖子:http://ASP.NET capesean.co.za /博客/收入/ 5智威汤逊
a功能演示是可用在:http:////capesean github.com openiddict试验