以前在web端的身份認(rèn)證都是基于Cookie | Session的身份認(rèn)證, 在沒有更多的終端出現(xiàn)之前,這樣做也沒有什么問題,但在Web API時代,你所需要面對的就不止是瀏覽器了,還有各種客戶端,這樣就有了一個問題,這些客戶端是不知道cookie是什么鬼的。 (cookie其實是瀏覽器搞出來的小貓膩,用來保持會話的,但HTTP本身是無狀態(tài)的, 各種客戶端能提供的無非也就是HTTP操作的API)
而基于Token的身份認(rèn)證就是應(yīng)對這種變化而生的,它更開放,安全性也更高。
基于Token的身份認(rèn)證有很多種實現(xiàn)方式,但我們這里只使用微軟提供的API。
接下來的例子將帶領(lǐng)大家完成一個使用微軟JwtSecurityTokenHandler完成一個基于beare token的身份認(rèn)證。
注意:這種文章屬于Step by step教程,跟著做才不至于看暈,下載完整代碼分析代碼結(jié)構(gòu)才有意義。
前期準(zhǔn)備
推薦使用VS2015 Update3作為你的IDE,下載地址://www.survivalescaperooms.com/softjc/446184.html
你需要安裝.NET Core的運行環(huán)境以及開發(fā)工具,這里提供VS版://www.survivalescaperooms.com/softs/472362.html
創(chuàng)建項目
在VS中新建項目,項目類型選擇ASP.NET Core Web Application(.NET Core), 輸入項目名稱為CSTokenBaseAuth
Coding
創(chuàng)建一些輔助類
在項目根目錄下創(chuàng)建一個文件夾Auth,并添加RSAKeyHelper.cs以及TokenAuthOption.cs兩個文件
在RSAKeyHelper.cs中
using System.Security.Cryptography;namespace CSTokenBaseAuth.Auth{ public class RSAKeyHelper { public static RSAParameters GenerateKey() { using (var key = new RSACryptoServiceProvider(2048)) { return key.ExportParameters(true); } } }}在TokenAuthOption.cs中
using System;using Microsoft.IdentityModel.Tokens;namespace CSTokenBaseAuth.Auth{ public class TokenAuthOption { public static string Audience { get; } = "ExampleAudience"; public static string Issuer { get; } = "ExampleIssuer"; public static RsaSecurityKey Key { get; } = new RsaSecurityKey(RSAKeyHelper.GenerateKey()); public static SigningCredentials SigningCredentials { get; } = new SigningCredentials(Key, SecurityAlgorithms.RsaSha256Signature); public static TimeSpan ExpiresSpan { get; } = TimeSpan.FromMinutes(20); }}Startup.cs
在ConfigureServices中添加如下代碼:
services.AddAuthorization(auth =>{ auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder() .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme) .RequireAuthenticatedUser().Build());});完整的代碼應(yīng)該是這樣
public void ConfigureServices(IServiceCollection services){ // Add framework services. services.AddApplicationInsightsTelemetry(Configuration); // 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()); }); services.AddMvc();}
新聞熱點
疑難解答
圖片精選