標籤:
基本Web API的ASP.NET的Oauth2認證
- 增加Token額外欄位
- 增加Scope授權欄位
- 持久化Token
- 設計Token的時間間隔
- 重新整理Token後失效老的Token
- 自訂驗證【重啟IIS池Token失效,驗證許可權】
Oauth2 認證的流程
用戶端發送口令(grant_type,client_id,client_secret)到服務端請求,認證返回access token ,然後用戶端跟據獲得的access token,根據Access Token獲得許可權去訪問Web API.
配置與準備:此處我們使用 oauth2服務端實現,需要引入Authorize(授權伺服器依賴)和resourceserver(資原始伺服器依賴)。
加了Authorize 標誌之後,進行 API請求測試,如果不通過oauth2認證機制就會出現,請求被拒絕
開始時,當程式開始時,用戶端訪問API,設計進入安全認證狀態
1 public void Configuration(IAppBuilder app)2 {3 4 app.UseCors(CorsOptions.AllowAll);5 ConfigureAuth(app);6 }View Code
1 app.UseOAuthBearerTokens(new OAuthAuthorizationServerOptions 2 { 3 TokenEndpointPath = new PathString("/token"), 4 Provider = new ApplicationOAuthProvider(), 5 //RefreshTokenProvider = new ApplicationRefreshTokenProvider(), 6 AccessTokenExpireTimeSpan = TimeSpan.FromHours(2), 7 AuthenticationMode = AuthenticationMode.Active, 8 //HTTPS is allowed only AllowInsecureHttp = false 9 AllowInsecureHttp = true10 //ApplicationCanDisplayErrors = false11 });View Code
第一步:根據密碼口令獲得Access Token(當密碼和帳號正確時)
/// <summary> /// 驗證客戶[client_id與client_secret驗證] /// </summary> /// <param name="context"></param> /// <returns></returns> public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context) { //http://localhost:48339/token //grant_type=client_credentials&client_id=irving&client_secret=123456 string client_id; string client_secret; context.TryGetFormCredentials(out client_id, out client_secret); if (client_id == "abc" && client_secret == "123456") { context.Validated(client_id); } else { //context.Response.StatusCode = Convert.ToInt32(HttpStatusCode.OK); context.SetError("invalid_client", "client is not valid"); } return base.ValidateClientAuthentication(context); }
/// <summary> /// 用戶端授權[產生access token] /// </summary> /// <param name="context"></param> /// <returns></returns> public override Task GrantClientCredentials(OAuthGrantClientCredentialsContext context) { /* var client = _oauthClientService.GetClient(context.ClientId); oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, client.ClientName)); */ //var oAuthIdentity = new ClaimsIdentity(context.Options.AuthenticationType); //oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, "iphone")); //var ticket = new AuthenticationTicket(oAuthIdentity, new AuthenticationProperties() { AllowRefresh = true }); //context.Validated(ticket); //return base.GrantClientCredentials(context); var oAuthIdentity = new ClaimsIdentity(context.Options.AuthenticationType); oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, "iphone")); //可以加入使用者資訊及其他必要資訊到Token中,以便在api服務中使用(使用中HttpContext.Current.User.Identity即為oAuthIdentity對象,WebApi的Controller中可直接使用User.Identity)。 oAuthIdentity.AddClaim(new Claim("UserID", "irving")); var ticket = new AuthenticationTicket(oAuthIdentity, new AuthenticationProperties()); context.Validated(ticket);//認證通過 return base.GrantClientCredentials(context); }
第二步:重新整理Token
/// <summary> /// 重新整理Token[重新整理refresh_token] /// </summary> /// <param name="context"></param> /// <returns></returns> public override Task GrantRefreshToken(OAuthGrantRefreshTokenContext context) { //enforce client binding of refresh token if (context.Ticket == null || context.Ticket.Identity == null || !context.Ticket.Identity.IsAuthenticated) { context.SetError("invalid_grant", "Refresh token is not valid"); } else { //Additional claim is needed to separate access token updating from authentication //requests in RefreshTokenProvider.CreateAsync() method } return base.GrantRefreshToken(context); }
接下來就是可以使用用戶端通過帳號密碼對用戶端進行調用,在一隨筆中詳細介紹。
基於asp.net MVC 的伺服器和用戶端的互動(二)之擷取Oauth 2.0認證許可權