简体   繁体   English

如何以编程方式获取访问令牌?

[英]how to get the access token programatically?

In my web api based project. 在我的基于web api的项目中。 I am using Token based authentication. 我正在使用基于令牌的身份验证。

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

        }


    }

If user credentials are valid, it returns the response as below:- 如果用户凭据有效,则返回响应如下: -

{"access_token":"-cmhkjwPvXieXEvs_TUsIHiMVdMAR4VxcvUK6XucNv3yx9PNVc4S8XtDdjEjc3cI8bU9EWhoXUI4g8I0qhcAh8WlgZKKJIXMZUhuJtUanUsOds_t-k0OoISIzb6zrk0XutfvCBkg7RMxrXBHWRO59PEJijDJd4JVmU-ekNeSalnVlC-k6CD4cOfRESBanDwSJJ9BU1PxIDqGGXHJtfIrlyruGn2ZuzqFstyCyfgdbJDekydj_RNnbO7lNAi0Xzw7bNItkBDNZ0yceWAFFzyKGAvm54Hemz7oEMcV0U0rlmE0LXM8O9D6GB8nT8rI9KOSjFKAoNOXgwB-L9nowmgqahRkc8DDwlsTUseM5tf-POBhcuMwBVatejtUJjfybqlt","token_type":"bearer","expires_in":1799,"Status":"Success","StatusCode":"200","data":"admin@website.com","message":"User valid"}

I tried to override this method as below 我试图覆盖这个方法,如下所示

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

But this give me build error. 但是这给了我构建错误。

My requirement is if user is valid the response should be a JSON string as below. 我的要求是,如果用户有效,响应应该是JSON字符串,如下所示。

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

Is user credentials are invalid. 用户凭据是否无效。

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

I don't want to pass the token in the response body but add the token & its validity detail in the header for the subsequent requests. 我不想在响应正文中传递令牌,而是在后续请求的标头中添加令牌及其有效性详细信息。

Have you tried myabe to put return 你有没有尝试过回复

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

so something like: 像这样的东西:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM