2017-08-07 220 views
1

我在我的MVC 5應用程序中實現了OAuth2身份驗證,所以我可以在我的Android應用程序中使用它。但我不確定這是怎麼回事,因爲我以前從未使用Oauth2或任何令牌認證。如何在OAuth2中從MVC5獲取客戶端ID和客戶端密鑰?

到目前爲止,我實施了MVC如下因素代碼:

OwinContextExtensions.cs

public static class OwinContextExtensions 
{ 
    public static string GetUserId(this IOwinContext ctx) 
    { 
     var result = "-1"; 
     var claim = ctx.Authentication.User.Claims.FirstOrDefault(c => c.Type == "UserID"); 
     if (claim != null) 
     { 
      result = claim.Value; 
     } 
     return result; 
    } 
} 

Startup.Auth.cs

public partial class Startup 
{ 
    public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; } 

    static Startup() 
    { 
     OAuthOptions = new OAuthAuthorizationServerOptions 
     { 
      TokenEndpointPath = new PathString("/token"), 
      Provider = new OAuthAppProvider(), 
      AccessTokenExpireTimeSpan = TimeSpan.FromDays(2), 
      AllowInsecureHttp = true 
     }; 
    } 

    public void ConfigureAuth(IAppBuilder app) 
    { 
     app.UseOAuthBearerTokens(OAuthOptions); 
    } 
} 

OAuthAppProvider.cs

public class OAuthAppProvider : OAuthAuthorizationServerProvider 
{ 
    private ProtokolEntities db = new ProtokolEntities(); 
    public IFormsAuthenticationService FormsService { get; set; } 
    public IMembershipService MembershipService { get; set; } 


    public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) 
    { 
     if (MembershipService == null) { MembershipService = new AccountMembershipService(); } 

     return Task.Factory.StartNew(() => 
     { 
      var username = context.UserName; 
      var password = context.Password; 


      var userID = db.aspnet_Users.Where(x => x.UserName == username).SingleOrDefault().UserId.ToString(); 

      if (MembershipService.ValidateUser(username, password)) 
      { 
       var claims = new List<Claim>() 
       { 
        new Claim(ClaimTypes.Name, username), 
        new Claim("UserID", userID) 
       }; 

       ClaimsIdentity oAutIdentity = new ClaimsIdentity(claims, Startup.OAuthOptions.AuthenticationType); 
       context.Validated(new AuthenticationTicket(oAutIdentity, new AuthenticationProperties() { })); 
      } 
      else 
      { 
       context.SetError("invalid_grant", "Error"); 
      } 
     }); 
    } 

    public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context) 
    { 
     if (context.ClientId == null) 
     { 
      context.Validated(); 
     } 
     return Task.FromResult<object>(null); 
    } 
} 

啓動.cs.cs

[assembly: OwinStartup(typeof(PageOffice.Startup))] 
namespace PageOffice 
{ 

    public partial class Startup 
    { 
     public void Configuration(IAppBuilder app) 
     { 
      app.MapSignalR(); 

      ConfigureAuth(app); 
     } 
    } 
} 

當我打開郵差和http://localhost:1076/token使用POST方法,我打開身體 - >生和寫入

grant_type =密碼&密碼=輸入mypassword &用戶名=名爲myUsername

後我得到這個結果:

{ 
    "access_token": "QmmWSh4OZPfC8uv-jyzFzZx1KP05T8b09QlPP3Cy-_Zr9qvWtzWpxNTXOhc4U387N6VHNCnIPklgTEk8CISMyXlcsWAz7MxlRN8qI_Ajg8gjEphHUS1SrO0uDRG2XRqtX1gvTVupym_1xtsdjlwj2VXoc6ySvR0ihb2YjuXnSd4CNgKKaMBQLb1w8P1XB13jc4Pc5tump4-Y4dYn3A5hpvtc9fqpgVAUjZFdiJ_HXMiIpgmqdIFim0Ty8oRZolzpm3RSMPRV6ZIpZBqHG1A2kcdWN-52ZkHuL4_7U743vW0", 
    "token_type": "bearer", 
    "expires_in": 172799 
} 

如何找到此「客戶端ID」和「客戶端密鑰」paremeters? 另外我真的不明白我怎麼會在android中使用這個access_token,請教關於this教程的解釋是否足夠了?

感謝您的閱讀和抱歉這麼多的代碼:)

回答

0

有大約OAuth2 for native applications的RFC。它建議使用授權碼授權流程,但沒有客戶端密碼,因爲您無法在應用程序二進制文件中保密。

您現在正在使用的資源所有者密碼憑據流(請參閱OAuth2 RFC)應僅在資源所有者完全信任應用程序的情況下使用,因爲應用程序必須知道其密碼。

當您在OAuth2提供商處註冊您的應用程序(客戶端)時,您將獲得或指定客戶端ID和密碼。

您鏈接的教程似乎在討論OAuth版本1,而不是2.

+0

謝謝,我現在正處於正確的道路上。我現在發送了一個錯誤的鏈接。我認爲這個教程會有所幫助。 –

+0

@Jan Halasa, 正如你所說的客戶端和祕密可以在應用程序reg.assume期間獲得我的客戶端是一個手機,那麼我需要在我的代碼中核實客戶端ID和祕密?或者需要存儲在SQL中,並與難編碼的值進行比較? – Jayendran