2017-02-17 79 views
1

在我的基於web api的項目中。我正在使用基於令牌的身份驗證。如何以編程方式獲取訪問令牌?

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); 

     } 


    } 

如果用戶憑據有效,則返回如下回應: -

{"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"} 

我試圖重寫此方法如下

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

但是,這給我建立自己的錯誤。

我的要求是,如果用戶是有效的響應應該是一個JSON字符串如下。

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

用戶憑證無效。

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

我不想通過在響應主體的令牌,但在頭添加令牌 &其有效性詳細的後續請求。

+0

@jps,可以請你在此分享您的輸入? –

回答

0

你試過myabe把回報

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

所以像:

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

如何將access_token值添加到標題? –

+0

AuthenticationProperties properties = CreateProperties(user.UserName); AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity,properties); ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,OAuthDefaults.AuthenticationType); context.Validated(ticket); context.Request.Context.Authentication.SignIn(oAuthIdentity); –

+0

如果你不介意,你可以請編輯帖子並添加此片段? –