2017-02-17 4 views
1

내 웹 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) 
{ 
} 

다음과 같이이 메소드를 오버라이드 (override)하지만이 날 오류를 구축 제공하기 위해 노력했다.

내 요구 사항은 사용자가 유효한 경우 응답이 아래의 JSON 문자열이어야합니다.

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

사용자 자격 증명이 유효하지 않습니다.

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

나는 응답 본문에 토큰을 전달하지만, 이후의 요청 헤더에 토큰 & 유효성 세부 정보를 추가하지 않습니다.

+0

@jps, 당신이 당신의 입력을 공유하시기 바랍니다 수 있습니다에게? –

답변

0

당신은

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

그래서 같은 수익 넣어 myabe를 시도 :

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 속성 = CreateProperties (user.UserName); AuthenticationTicket 티켓 = 새로운 AuthenticationTicket (oAuthIdentity, 속성), ClaimsIdentity oAuthIdentity = user.GenerateUserIdentityAsync (userManager, OAuthDefaults.AuthenticationType); context.Validated (티켓); context.Request.Context.Authentication.SignIn (oAuthIdentity); –

+0

괜찮 으면 게시글을 편집하고이 스 니펫을 추가 해주시겠습니까 ?? –