基於令牌的認證api
咱們知道WEB網站的身份驗證通常經過session或者cookie完成的,登陸成功後客戶端發送的任何請求都帶上cookie,服務端根據客戶端發送來的cookie來識別用戶。緩存
WEB API使用這樣的方法不是很適合,因而就有了基於令牌的認證,使用令牌認證有幾個好處:可擴展性、鬆散耦合、移動終端調用比較簡單等等。cookie
Step 1:安裝所需的NuGet包:session
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
Step 2 在項目下添加「Startup.Auth」類app
默認會在App_Start文件夾裏async
using System; using System.Collections.Generic; using System.Linq; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using Microsoft.Owin; using Microsoft.Owin.Security.Cookies; using Microsoft.Owin.Security.Google; using Microsoft.Owin.Security.OAuth; using Owin; using System.Web.Http; namespace SJOA { public partial class Startup { public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; } public static string PublicClientId { get; private set; } public void Configuration(IAppBuilder app) { HttpConfiguration config = new HttpConfiguration(); ConfigureOAuth(app); WebApiConfig.Register(config); app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll); app.UseWebApi(config); } public void ConfigureOAuth(IAppBuilder app) { OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions() { AllowInsecureHttp = true, TokenEndpointPath = new PathString("/token"), AccessTokenExpireTimeSpan = TimeSpan.FromDays(1), Provider = new SimpleAuthorizationServerProvider() }; app.UseOAuthAuthorizationServer(OAuthServerOptions); app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()); } } }
Step 3:在項目下添加驗證類 SimpleAuthorizationServerProvideride
using System.Threading.Tasks; using System.Security.Claims; using Microsoft.Owin.Security.OAuth; using Microsoft.Owin.Security; using SJOA.Entity.Models.Tables; using SJOA.Core.BLL; namespace SJOA { /// <summary> /// Token驗證 /// </summary> public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider { public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context) { await Task.Factory.StartNew(() => context.Validated()); } public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { await Task.Factory.StartNew(() => context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" })); try { var userName = context.UserName; var password = context.Password; UserBLL bll = new UserBLL();
//驗證用戶名,密碼 Users user =await Task.Factory.StartNew(() => bll.Query(userName, password)); if (user == null) { context.SetError("invalid_grant", "用戶名或密碼錯誤"); return; } else { var oAuthIdentity = new ClaimsIdentity(context.Options.AuthenticationType); oAuthIdentity.AddClaim(new Claim("sub", context.UserName)); oAuthIdentity.AddClaim(new Claim("role", "user")); oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, user.UserName)); oAuthIdentity.AddClaim(new Claim(ClaimTypes.UserData, user.UserID.ToString())); var authenticationProperties = new AuthenticationProperties(); var ticket = new AuthenticationTicket(oAuthIdentity, authenticationProperties); context.Validated(ticket); } } catch (System.Exception ex) { throw; } } } }
Step 4:讓CORS起做用網站
在ASP.NET Web API中啓用OAuth的Access Token驗證很是簡單,只需在相應的Controller或Action加上[Authorize]標記ui
Step 5:獲取Tokenurl
獲取token, POST請求本地http://localhost:23477/token
請求頭 Content-Type:application/x-www-form-urlencoded
參數BODY格式:
grant_type=password
username=admin
password=123456
token請求到之後,能夠緩存在客戶端,而後客戶端再拿着token請求其它接口
Step 6:請求接口
只要在http請求頭中加上Authorization:bearer Token就能夠成功請求接口了
GET http://localhost:49209/api/sys/Dept/GetALLDept
Authorization : bearer T5jF97t5n-rBkWcwpiVDAlhzXtOvV7Jw2NnN1Aldc--xtDrvWtqLAN9hxJN3Fy7piIqNWeLMNm2IKVOqmmC0X5_s8MwQ6zufUDbvF4Bg5OHoHTKHX6NmZGNrU4mjpCuPLtSbT5bh_gFOZHoIXXIKmqD3Wu1MyyKKNhj9XPEIkd9bl4E9AZ1wAt4dyUxmPVA_VKuN7UvYJ97TkO04XyGqmXGtfVWKfM75mNVYNhySWTg
至此,項目的Token驗證就完成了