基於asp.net MVC 的伺服器和用戶端的互動(二)之擷取Oauth 2.0認證許可權

來源:互聯網
上載者:User

標籤:

基本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認證許可權

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.