如何使用web api bearer token base authentication生成令牌时设置一些用户数据

问题描述 投票:0回答:1

当令牌生成时,我想要获取登录用户的一些数据。

我已经完成了访问令牌生成

这是我的Startup类:

 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类

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类

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

    }
}

Postmanenter image description here我的预期输出如:enter image description here我用用户生成令牌设置我想要的用户数据。怎么做到这一点?

c# asp.net-web-api2 bearer-token
1个回答
1
投票

您正在向令牌添加声明,因此为了访问它们,您需要解码令牌。但是,如果您希望额外数据位于令牌之外(如您绘制的图像),则可以将它们作为不同的属性添加到登录响应对象:

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

此外,您需要将以下方法添加到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);
    }
© www.soinside.com 2019 - 2024. All rights reserved.