详解ASP.NET Core Token认证(3)

大部分代码都很官方,JwtSecurityToken 类生成jwt,JwtSecurityTokenHandler将jwt编码,你可以在claims中添加任何chaims。验证用户身份只是简单的验证,实际情况肯定不是这样的,你可以集成 identity framework或者其他的,对于这个实例只是简单的硬编码:

private Task<ClaimsIdentity> GetIdentity(string username, string password) { // DON'T do this in production, obviously! if (username == "TEST" && password == "TEST123") { return Task.FromResult(new ClaimsIdentity(new System.Security.Principal.GenericIdentity(username, "Token"), new Claim[] { })); } // Credentials are invalid, or account doesn't exist return Task.FromResult<ClaimsIdentity>(null); }

添加一个将DateTime生成timestamp的方法:

public static long ToUnixEpochDate(DateTime date) => (long)Math.Round((date.ToUniversalTime() - new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero)).TotalSeconds);

现在,你可以将这个中间件添加到startup.cs中了:

using System.Text; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Microsoft.IdentityModel.Tokens; namespace SimpleTokenProvider { public partial class Startup { public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .AddJsonFile("appsettings.json", optional: true); Configuration = builder.Build(); } public IConfigurationRoot Configuration { get; set; } public void ConfigureServices(IServiceCollection services) { services.AddMvc(); } // The secret key every token will be signed with. // In production, you should store this securely in environment variables // or a key management tool. Don't hardcode this into your application! private static readonly string secretKey = "mysupersecret_secretkey!123"; public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(LogLevel.Debug); loggerFactory.AddDebug(); app.UseStaticFiles(); // Add JWT generation endpoint: var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secretKey)); var options = new TokenProviderOptions { Audience = "ExampleAudience", Issuer = "ExampleIssuer", SigningCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256), }; app.UseMiddleware<TokenProviderMiddleware>(Options.Create(options)); app.UseMvc(); } } }

测试一下,推荐使用chrome 的postman:

POST /token Content-Type: application/x-www-form-urlencoded username=TEST&password=TEST123

结果:
OK

Content-Type: application/json
 
{
  "access_token": "eyJhb...",
  "expires_in": 300
}

你可以使用jwt工具查看生成的jwt内容。如果开发的是移动应用或者单页应用,你可以在后续请求的header中存储jwt,如果你需要在cookies中存储的话,你需要对代码修改一下,需要将返回的jwt字符串添加到cookie中。
测试下:

其他方案

下面是比较成熟的项目,可以在实际项目中使用:

AspNet.Security.OpenIdConnect.Server – ASP.NET 4.x的验证中间件。

OpenIddict – 在identity上添加OpenId验证。

IdentityServer4 – .NET Core认证中间件(现在测试版本)。

下面的文章可以让你更加的了解认证:

Overview of Token Authentication Features

How Token Authentication Works in Stormpath

Use JWTs the Right Way!

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wjywxs.html