簡體   English   中英

使用Web API承載令牌基礎身份驗證生成令牌時如何設置一些用戶數據

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

當令牌在當時以自己的條件流動時生成時,我想獲取登錄用戶的一些數據。

我已經完成訪問令牌生成

這是我的啟動課程:

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

    }
}

郵差 在此處輸入圖片說明 我的預期輸出如下: 在此處輸入圖片說明 在哪里設置用戶生成令牌所需的用戶數據。 如何實現呢?

您正在向令牌添加聲明,因此要訪問它們,您需要對令牌進行解碼。 但是,如果您希望多余的數據在令牌之外(例如您繪制的圖像),則可以將它們作為不同的屬性添加到登錄響應對象中:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM