基於asp.net MVC 的服務器和客戶端的交互(二)之獲取Oauth 2.0認證權限


基本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 = true
10                 //ApplicationCanDisplayErrors = false
11             });
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);
        }

  接下來就是可以使用客戶端通過賬號密碼對客戶端進行調用,在一隨筆中詳細介紹。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM