簡體   English   中英

如何使用Bearer Token在Owin上按會話存儲每個用戶的其他數據

[英]How to store additional data per user like session on Owin using Bearer Token

客戶端登錄后,我需要在控制器上存儲第三方軟件調用的令牌,因此我嘗試將其保存在用戶聲明中:

public class BaseController : ApiController
{
    private const string Token = "thirdyparty.token";
    private string Token
    {
        set
        {
            // Here I want to store a token in any way (Session, Cache, etc)
            var claimsIdentity = (ClaimsIdentity)User.Identity;
            var claims = claimsIdentity.Claims;
            var tokenClaim = claims.FirstOrDefault(x => x.Type == Token);

            if (Token != null)
            {
                claimsIdentity.RemoveClaim(tokenClaim);
            }
            claimsIdentity.AddClaim(new Claim(Token, value));
        }
        get
        {
            // Here I want to get the token
            var claimsIdentity = (ClaimsIdentity)User.Identity;
            var claims = claimsIdentity.Claims;
            var tokenClaim = claims.FirstOrDefault(x => x.Type == Token);

            return tokenClaim?.Value;
        }
    }
}

這沒有用,每次提出新請求時,我的新索賠都消失了。 那么,如何為每個用戶存儲一些其他信息?

問題在於聲明是承載令牌的一部分。

因此,即使將聲明添加到當前標識中,下一個請求也將具有舊的聲明值,因為它們是隨新請求一起發送的令牌的一部分。

因此,如果添加索賠,則還需要生成一個新令牌並將其返回給客戶。

生成新令牌的一種方法是將在Startup.cs類中使用的OAuthAuthorizationServerOptions存儲為靜態變量,然后在需要時使用它

public class Startup
{
    public static OAuthAuthorizationServerOptions OAuthServerOptions { get; private set; }
    public void Configuration(IAppBuilder app)
    {
        ConfigureOAuth(app);
        //....add the rest
    }

    public void ConfigureOAuth(IAppBuilder app)
    {
        OAuthServerOptions = new OAuthAuthorizationServerOptions()
        {
            AllowInsecureHttp = true,
            TokenEndpointPath = new PathString("/token"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
            Provider = new AuthProvider() //Your derived OAuthAuthorizationServerProvider
        };

        // Token Generation
        app.UseOAuthAuthorizationServer(OAuthServerOptions);
        app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
    }
}

然后生成一個新令牌

var claimsIdentity = ... //The claim identity after you have added the new claims
    var newToken = Startup.OAuthServerOptions.AccessTokenFormat.Protect(new AuthenticationTicket(claimsIdentity, new AuthenticationProperties()));

暫無
暫無

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

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