简体   繁体   English

使用Web API承载令牌基础身份验证生成令牌时如何设置一些用户数据

[英]How to set some user data when token generate using web api bearer token base authentication

When token generate with flowing my own condition at that time I want to fetch some data of login user. 当令牌在当时以自己的条件流动时生成时,我想获取登录用户的一些数据。

I'm already done access token generate 我已经完成访问令牌生成

Here is my Startup class: 这是我的启动课程:

 public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=316888
        app.UseCors(CorsOptions.AllowAll);
        var myProvider = new MyAuthorizationServerProvider();
        OAuthAuthorizationServerOptions options = new OAuthAuthorizationServerOptions
        {
            AllowInsecureHttp = true,
            TokenEndpointPath = new PathString("/token"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
            Provider = myProvider
        };
        app.UseOAuthAuthorizationServer(options);
        app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
        HttpConfiguration config = new HttpConfiguration();
        WebApiConfig.Register(config);
    }


}

MyAuthorizationServerProvider class MyAuthorizationServerProvider类

public class MyAuthorizationServerProvider : OAuthAuthorizationServerProvider
{
    private readonly ReviewDbContext db;
    public MyAuthorizationServerProvider()
    {
        db = new ReviewDbContext();
    }
    public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
    {
        context.Validated();
    }
    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        var user = db.Reviewers.Where(x => x.Name == context.UserName && x.Password == context.Password).FirstOrDefault();
        var admin = db.Admins.Where(x => x.Name == context.UserName && x.Password == context.Password).FirstOrDefault();
        var identity = new ClaimsIdentity(context.Options.AuthenticationType);
        if (admin != null && user == null)
        {
            identity.AddClaim(new Claim(ClaimTypes.Role, "admin"));
            identity.AddClaim(new Claim("UserName", admin.Name));
            identity.AddClaim(new Claim(ClaimTypes.Name, "Admin Ahasanul Banna"));
            context.Validated(identity);
        }
        else if (user != null)
        {
            identity.AddClaim(new Claim(ClaimTypes.Role, "user"));
            identity.AddClaim(new Claim("UserName", user.Name));
            identity.AddClaim(new Claim(ClaimTypes.Name, "User Ahasanul Banna"));
            context.Validated(identity);
        }
        else
        {
            context.SetError("Invalid_grant", "Provided username & password is incorrect");
            return;
        }
    }
}

AuthorizeAttribute class AuthorizeAttribute类

public class AuthorizeAttribute :System.Web.Http.AuthorizeAttribute
{
    protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
    {
        if (!HttpContext.Current.User.Identity.IsAuthenticated)
        {
            base.HandleUnauthorizedRequest(actionContext);
        }
        else
        {
            actionContext.Response = new HttpResponseMessage(HttpStatusCode.Forbidden);
        }

    }
}

Postman 邮差 在此处输入图片说明 My expected output like as: 我的预期输出如下: 在此处输入图片说明 Where I set user data which I want with user generate token. 在哪里设置用户生成令牌所需的用户数据。 How to achieve this? 如何实现呢?

You are adding claims to your token so in order to access them you need to decode the token. 您正在向令牌添加声明,因此要访问它们,您需要对令牌进行解码。 However, if you want your extra data to be outside the token (like the image you have painted), you can add them as different properties to the login response object: 但是,如果您希望多余的数据在令牌之外(例如您绘制的图像),则可以将它们作为不同的属性添加到登录响应对象中:

                  var props = new AuthenticationProperties(new Dictionary<string, string>
                    {
                        {
                            "UserName", "AA"
                        },
                        {
                             "UserId" , "1"
                        }
                    });
                    var ticket = new AuthenticationTicket(identity, props);
                    context.Validated(ticket);

Also, you need to add the following method to MyAuthorizationServerProvider : 另外,您需要将以下方法添加到MyAuthorizationServerProvider

 public override Task TokenEndpoint(OAuthTokenEndpointContext context)
    {
        foreach (KeyValuePair<string, string> property in context.Properties.Dictionary)
        {
            context.AdditionalResponseParameters.Add(property.Key, property.Value);
        }
        return Task.FromResult<object>(null);
    }

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

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