2017-02-17 5 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); 

     } 


    } 

ユーザーの資格情報が有効であれば以下のように、それは応答を返します - 私は

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

以下のようにこのメソッドをオーバーライドしようとしたが、これはエラーを構築する私を与える

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

私の要件は、ユーザーが有効な場合、応答は以下のような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

headerにaccess_tokenの値を追加するにはどうすればよいですか? –

+0

AuthenticationPropertiesプロパティ= CreateProperties(user.UserName);認証チケットの新しい認証チケット(oAuthIdentity、properties); context.Request.Context.Authentication.SignIn(oAuthIdentity); –

+0

あなたが気にしない場合は、投稿を編集してこのスニペットを追加できますか? –

関連する問題