基於令牌的認證
我們知道WEB網站的身份驗證一般通過session或者cookie完成的,登錄成功后客戶端發送的任何請求都帶上cookie,服務端根據客戶端發送來的cookie來識別用戶。
WEB API使用這樣的方法不是很適合,於是就有了基於令牌的認證,使用令牌認證有幾個好處:可擴展性、松散耦合、移動終端調用比較簡單等等,別人都用上了,你還有理由不用嗎?
下面我們花個20分鍾的時間來實現一個簡單的WEB API token認證:
Step 1:安裝所需的NuGet包:
打開NuGet包管理器控制台,然后輸入如下指令:
Install-Package Microsoft.AspNet.WebApi.Owin -Version 5.1.2 Install-Package Microsoft.Owin.Host.SystemWeb -Version 2.1.0 Install-Package Microsoft.AspNet.Identity.Owin -Version 2.0.1
Install-Package Microsoft.Owin.Cors -Version 2.1.0
Install-Package EntityFramework -Version 6.0.0
Step 2 在項目根目錄下添加Owin“Startup”類

1 using System; 2 using System.Web.Http; 3 4 using Owin; 5 using Microsoft.Owin; 6 using Microsoft.Owin.Security.OAuth; 7 using SqlSugar.WebApi; 8 9 [assembly: OwinStartup(typeof(WebApi.Startup))] 10 namespace WebApi 11 { 12 public class Startup 13 { 14 public void Configuration(IAppBuilder app) 15 { 16 HttpConfiguration config = new HttpConfiguration(); 17 ConfigureOAuth(app); 18 19 WebApiConfig.Register(config); 20 app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll); 21 app.UseWebApi(config); 22 } 23 24 public void ConfigureOAuth(IAppBuilder app) 25 { 26 OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions() 27 { 28 AllowInsecureHttp = true, 29 TokenEndpointPath = new PathString("/token"), 30 AccessTokenExpireTimeSpan = TimeSpan.FromDays(1), 31 Provider = new SimpleAuthorizationServerProvider() 32 }; 33 app.UseOAuthAuthorizationServer(OAuthServerOptions); 34 app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()); 35 } 36 } 37 }
Step 3:在項目根目錄下添加驗證類 SimpleAuthorizationServerProvider,為了簡單用戶的驗證部分我們省略掉;

1 using System.Threading.Tasks; 2 using System.Security.Claims; 3 using Microsoft.Owin.Security.OAuth; 4 5 namespace WebApi 6 { 7 /// <summary> 8 /// Token驗證 9 /// </summary> 10 public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider 11 { 12 public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context) 13 { 14 await Task.Factory.StartNew(() => context.Validated()); 15 } 16 17 public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) 18 { 19 await Task.Factory.StartNew(() => context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" })); 20 /* 21 * 對用戶名、密碼進行數據校驗 22 using (AuthRepository _repo = new AuthRepository()) 23 { 24 IdentityUser user = await _repo.FindUser(context.UserName, context.Password); 25 26 if (user == null) 27 { 28 context.SetError("invalid_grant", "The user name or password is incorrect."); 29 return; 30 } 31 }*/ 32 33 var identity = new ClaimsIdentity(context.Options.AuthenticationType); 34 identity.AddClaim(new Claim("sub", context.UserName)); 35 identity.AddClaim(new Claim("role", "user")); 36 37 context.Validated(identity); 38 39 } 40 } 41 }
Step 4:讓CORS起作用
在ASP.NET Web API中啟用OAuth的Access Token驗證非常簡單,只需在相應的Controller或Action加上[Authorize]標記

1 [Authorize] 2 [HttpGet, Route("product/getList")] 3 public List<Entity.Sys_User> GetProductList() 4 { 5 throw new NotImplementedException(); 6 }
Step 5 : 請求 Token
獲取token, POST http://localhost:23477/token
參數BODY x-www-form-urlencoded 格式:
grant_type=password
username=admin
password=123456
返回狀態200 結果為
Step 5 調用api
只要在http請求頭中加上Authorization:bearer Token就可以成功訪問API就成功了:
GET http://localhost:58192/api/testapi/testapi
Authorization : bearer T5jF97t5n-rBkWcwpiVDAlhzXtOvV7Jw2NnN1Aldc--xtDrvWtqLAN9hxJN3Fy7piIqNWeLMNm2IKVOqmmC0X5_s8MwQ6zufUDbvF4Bg5OHoHTKHX6NmZGNrU4mjpCuPLtSbT5bh_gFOZHoIXXIKmqD3Wu1MyyKKNhj9XPEIkd9bl4E9AZ1wAt4dyUxmPVA_VKuN7UvYJ97TkO04XyGqmXGtfVWKfM75mNVYNhySWTg
結果為: