2017-02-17 2 views
1

Dans mon projet basé sur l'API Web. J'utilise l'authentification basée sur Token.comment obtenir le jeton d'accès par programme?

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) 
    { 
     var allowedOrigin = context.OwinContext.Get<string>("as:clientAllowedOrigin"); 

     if (allowedOrigin == null) 
     { 
      allowedOrigin = "*"; 
     } 

     context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin }); 

     /* db based authenication*/ 
     var user = ValidateUser(context.UserName.Trim(), context.Password.Trim()); 
     if (user != null) 
     { 
      /* db based authenication*/ 
      var identity = new ClaimsIdentity(context.Options.AuthenticationType); 
      identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName)); 
      identity.AddClaim(new Claim(ClaimTypes.Role, "user")); 
      identity.AddClaim(new Claim("sub", context.UserName)); 

      var props = new AuthenticationProperties(new Dictionary<string, string> 
      { 
       { 
        "Status", "Success" 
       }, 
       { 
        "StatusCode", "200" 
       }, 
       { 
        "data", context.UserName.Trim() 
       }, 
       { 
        "message", "User valid" 
       } 
      }); 

      var ticket = new AuthenticationTicket(identity, props); 
      //add token to header 
      context.OwinContext.Response.Headers.Add("Authorization", new []{"Bearer " + ticket}); 
      context.Validated(ticket); 
     } 
     else 
     { 
      context.Rejected(); 
      //_reponse = _util.Create(0, HttpStatusCode.Forbidden, message: "User Invaid.", data: null); 

     } 


    } 

Si les informations d'identification de l'utilisateur sont valides, il renvoie la réponse ci-dessous: -

{"access_token":"-cmhkjwPvXieXEvs_TUsIHiMVdMAR4VxcvUK6XucNv3yx9PNVc4S8XtDdjEjc3cI8bU9EWhoXUI4g8I0qhcAh8WlgZKKJIXMZUhuJtUanUsOds_t-k0OoISIzb6zrk0XutfvCBkg7RMxrXBHWRO59PEJijDJd4JVmU-ekNeSalnVlC-k6CD4cOfRESBanDwSJJ9BU1PxIDqGGXHJtfIrlyruGn2ZuzqFstyCyfgdbJDekydj_RNnbO7lNAi0Xzw7bNItkBDNZ0yceWAFFzyKGAvm54Hemz7oEMcV0U0rlmE0LXM8O9D6GB8nT8rI9KOSjFKAoNOXgwB-L9nowmgqahRkc8DDwlsTUseM5tf-POBhcuMwBVatejtUJjfybqlt","token_type":"bearer","expires_in":1799,"Status":"Success","StatusCode":"200","data":"[email protected]","message":"User valid"} 

J'ai essayé de remplacer cette méthode comme ci-dessous

public override async Task<ResponseTO> GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) 
{ 
} 

Mais donnez-moi construire une erreur.

Mon exigence est que si l'utilisateur est valide, la réponse devrait être une chaîne JSON comme ci-dessous.

{ 
    "Status", "Success", 
    "message": "User is valid", 
    "data" context.userName 
} 

Les informations d'identification de l'utilisateur ne sont pas valides.

{ 
    "Status", "Error", 
    "message": "User Invalid", 
    "data" context.userName 
} 

Je ne veux pas passer le jeton dans le corps de la réponse, mais ajoutez le jeton & ses détails de validité dans l'en-tête pour les demandes ultérieures.

+0

@jps, pouvez-vous s'il vous plaît partager vos entrées sur ce ?? –

Répondre

0

Avez-vous essayé de mettre MyaBe retour

Task.FromResult<ResponseTO>(new ResponseTO{ //your properties filled });

donc quelque chose comme:

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) 
     { 
      var allowedOrigin = context.OwinContext.Get<string>("as:clientAllowedOrigin"); 

      if (allowedOrigin == null) 
      { 
       allowedOrigin = "*"; 
      } 

      context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin }); 

      /* db based authenication*/ 
      var user = ValidateUser(context.UserName.Trim(), context.Password.Trim()); 
      if (user != null) 
      { 
       /* db based authenication*/ 
       var identity = new ClaimsIdentity(context.Options.AuthenticationType); 
       identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName)); 
       identity.AddClaim(new Claim(ClaimTypes.Role, "user")); 
       identity.AddClaim(new Claim("sub", context.UserName)); 

       var props = new AuthenticationProperties(new Dictionary<string, string> 
       { 
        { 
         "Status", "Success" 
        }, 
        { 
         "StatusCode", "200" 
        }, 
        { 
         "data", context.UserName.Trim() 
        }, 
        { 
         "message", "User valid" 
        } 
       }); 

       var ticket = new AuthenticationTicket(identity, props); 
       //add token to header 

       context.Validated(ticket); 
// TRY THIS 
      context.Request.Context.Authentication.SignIn(identity); 
      } 
      else 
      { 
       context.Rejected(); 
       //_reponse = _util.Create(0, HttpStatusCode.Forbidden, message: "User Invaid.", data: null); 

      } 

//RETURN YOUR DTO 
    context.Response.WriteAsync(JsonConvert.SerializeObject(new Responseto{ // propeties here}, new JsonSerializerSettings { Formatting = Formatting.Indented })); 
     } 
+0

comment ajouter la valeur access_token à l'en-tête? –

+0

Propriétés AuthenticationProperties = CreateProperties (user.UserName); AuthenticationTicket ticket = nouveau AuthenticationTicket (oAuthIdentity, propriétés); ClaimsIdentity oAuthIdentity = wait utilisateur.GenerateUserIdentityAsync (userManager, OAuthDefaults.AuthenticationType); context.Validated (ticket); context.Request.Context.Authentication.SignIn (oAuthIdentity); –

+0

Si cela ne vous dérange pas, pouvez-vous s'il vous plaît modifier le poste et ajouter cet extrait ?? –