Dot-Net

OWIN的oAuth中的ValidateClientAuthentication方法和GrantResourceOwnerCredentials方法有什麼區別?

  • January 2, 2018

我是 .NET 中 oauth 和 owin 的初學者。我試圖了解這些方法 ValidateClientAuthentication 方法和 GrantResourceOwnerCredentials 方法。我了解 GrantResourceOwnerCredentials 方法可用於驗證憑據並生成令牌。那麼,ValidateClientAuthentication() 方法的目的是什麼。請指導我。非常感謝。

public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
       {
           return Task.Factory.StartNew(() =>
           {
               var userName = context.UserName;
               var password = context.Password;
               var userService = new UserService(); // our created one
               var user = userService.ValidateUser(userName, password);
               if (user != null)
               {
                   var claims = new List<Claim>()
                   {
                       new Claim(ClaimTypes.Sid, Convert.ToString(user.Id)),
                       new Claim(ClaimTypes.Name, user.Name),
                       new Claim(ClaimTypes.Email, user.Email)
                   };
                   ClaimsIdentity oAuthIdentity = new ClaimsIdentity(claims,Startup.OAuthOptions.AuthenticationType);


                   var properties = CreateProperties(user.Name);
                   var ticket = new AuthenticationTicket(oAuthIdentity, properties);
                   context.Validated(ticket);
               }
               else
               {
                   context.SetError("invalid_grant", "The user name or password is incorrect");
               }
           });
       }
       #endregion

       #region[ValidateClientAuthentication]
       public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
       {
           if (context.ClientId == null)
               context.Validated();

           return Task.FromResult<object>(null);
       }
       #endregion

這與OAuth 2.0 規範中的Client Credentials Flow vs. Resource Owner Password Credentials Flow有關

請記住,客戶端和資源所有者是 OAuth 下的不同實體。客戶端代表資源所有者提出請求。

實際上,當您希望接受實際的使用者名和密碼並發出訪問令牌時,您可能希望使用 GrantResourceOwnerCredentials。

ValidateClientAuthentication 應該用於確保客戶端是它所說的那樣。如果已將客戶端註冊到授權伺服器並需要驗證它是否仍然有效,您可能會這樣做。

我見過的大多數程式碼範例只是呼叫 context.Validated() ,就像您在範例中所做的那樣。我能夠找到一篇部落格文章,其中包含更深入的程式碼範例。在這裡查看:http: //bitoftech.net/2014/10/27/json-web-token-asp-net-web-api-2-jwt-owin-authorization-server/

引用自:https://stackoverflow.com/questions/47974364