2016-09-19 36 views
0

我是新來的ASP.NET身份驗證,現在玩認證方法。我想爲用戶名/密碼認證實施不記名令牌,並且我希望外部用戶通過Google和其他OAuth2提供商登錄。在WebAPI2 OWIN中如何結合承載令牌和OAuth2?

我無法同時實現這兩種方法。我在這樣一個選項豐富的OWIN配置中做錯了。

這裏是我SecurityConfig類:

public class SecurityConfig 
{ 
    public static void Configure(IAppBuilder app) 
    { 
     ConfigureTokenAuthentication(app); 
     ConfigureExternalAuthentication(app); 
    } 

    private static void ConfigureTokenAuthentication(IAppBuilder app) 
    { 
     string PublicClientId = "self"; 
     Func<UserManager<User>> UserManagerFactory =() => new UserManager<User>(new UserStore<User>(new TicketsContext())); 
     var oAuthOptions = new OAuthAuthorizationServerOptions 
     { 
      TokenEndpointPath = new PathString("/token"), 
      Provider = new ApplicationOAuthProvider(PublicClientId, UserManagerFactory), 
      AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"), 
      AccessTokenExpireTimeSpan = TimeSpan.FromDays(14), 
      AllowInsecureHttp = false 
     }; 

     // Enable the application to use bearer tokens to authenticate users 
     app.UseOAuthBearerTokens(oAuthOptions); 
    } 

    private static void ConfigureExternalAuthentication(IAppBuilder app) 
    { 
     // Use a cookie to temporarily store information about a user logging in with a third party login provider 
     app.UseCookieAuthentication(new CookieAuthenticationOptions 
     { 
      AuthenticationType = DefaultAuthenticationTypes.ExternalCookie, 
      LoginPath = new PathString("/api/Account/ExternalLogin") 
     }); 

     app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); 

     // Configure Google authentication 
     app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions 
     { 
      ClientId = "my client id here", 
      ClientSecret = "my client secret here" 
     });   
    } 
} 

,這裏是外部登錄方法:

// GET api/Account/ExternalLogin 
[HttpGet] 
[AllowAnonymous] 
[Route("api/Account/ExternalLogin")] 
public IHttpActionResult ExternalLogin(string provider) 
{ 
    return new ChallengeResult(provider, "/api/home", this.Request); 
} 

當我使這兩種方法,只是承載令牌正常工作,努力做外部登錄答案我「錯誤:invalid_request」,並沒有進入控制器方法。

也許這個問題?

AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"), 

試圖解決這個已經2天了。

回答

0

UseGoogleAuthentication實現的OAuth2流不適用於WebApi場景,它依賴於用戶交互。無記名令牌是WebApis的正確方法。要獲得代表像Google這樣的外部身份提供商的無記名令牌,您需要使用IdentityServer3這樣的中間身份驗證服務器。見https://github.com/IdentityServer/IdentityServer3