2016-11-23 2 views
0

J'essaie d'implémenter l'authentification par jeton contre ma propre base de données. Ma méthode Configurer estAuthentification de jeton contre une base de données personnalisée dans WebAPI

public void ConfigureAuth(IAppBuilder app) 
{ 
     // Configure the db context and user manager to use a single instance per request 
     app.CreatePerOwinContext(ApplicationDbContext.Create); 
     app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create); 

     // Enable the application to use a cookie to store information for the signed in user 
     // and to use a cookie to temporarily store information about a user logging in with a third party login provider 
     app.UseCookieAuthentication(new CookieAuthenticationOptions()); 
     app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); 

     // Configure the application for OAuth based flow 
     PublicClientId = "self"; 
     OAuthOptions = new OAuthAuthorizationServerOptions 
     { 
      TokenEndpointPath = new PathString("/Token"), 
      Provider = new CustomOAuthProvider(), 
      AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"), 
      AccessTokenExpireTimeSpan = TimeSpan.FromDays(14), 
      // In production mode set AllowInsecureHttp = false 
      AllowInsecureHttp = true 
     }; 

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

Comme vous pouvez le voir, j'utilise la classe CustomOAuthProvider, qui remplace méthode GrantResourceOwnerCredentials comme suit

public class CustomOAuthProvider : OAuthAuthorizationServerProvider 
{ 
    public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) 
    { 
     context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] {"*"}); 

     IUsersService userService = DependencyResolver.Current.GetService<IUsersService>(); 
     if (!userService.CheckCredentials(context.UserName, context.Password)) 
     { 
      context.SetError("invalid_grant", "The user name or password is incorrect"); 
      return Task.FromResult<object>(null); 
     } 

     var identity = new ClaimsIdentity("JWT"); 

     identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName)); 
     identity.AddClaim(new Claim("sub", context.UserName)); 
     identity.AddClaim(new Claim(ClaimTypes.Role, "User")); 

     var props = new AuthenticationProperties(new Dictionary<string, string> 
     { 
      { 
       "audience", context.ClientId ?? string.Empty 
      } 
     }); 

     var ticket = new AuthenticationTicket(identity, props); 
     context.Validated(ticket); 
     return Task.FromResult<object>(null); 
    } 
} 

Mais chaque fois que je fais une demande de jeton via Fiddler, je reçois 400 = Bad demande. enter image description here

Qu'est-ce que je fais mal :)

Répondre

0

Toute personne ayant le même problème, il suffit de suivre cet article, il montre comment remplacer la méthode GrantResourceOwnerCredentials pour que tout cela fonctionne:

http://www.hackered.co.uk/articles/asp-net-mvc-creating-an-oauth-password-grant-type-token-endpoint

public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) 
{ 
    var user = userService.GetUser(context.UserName, context.Password); 
    var oAuthIdentity = new ClaimsIdentity(context.Options.AuthenticationType); 
    oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, user.Name)); 
    var ticket = new AuthenticationTicket(oAuthIdentity, new AuthenticationProperties()); 
    context.Validated(ticket); 
    return base.GrantResourceOwnerCredentials(context); 
}