存储和访问从我的控制器启动期间获得的值

Store and access value obtained during startup from my controller

我正在使用打开的连接中间件向第三方 oidc 提供商进行身份验证,一切正常,运行 如我所料。在令牌交换期间,我用我的授权码交换了一个成功的访问令牌,但随后我需要存储此不记名令牌以供以后在后续请求中使用。令牌交换是在 asp.net 核心项目中作为我启动 class 的一部分完成的(通过在 OnAuthorizationCodeReceived 方法期间覆盖 OpenIdConnectEvents),我需要存储和访问它我的控制器中的令牌。

由于本身还没有“会话”,从启动时存储此令牌值的最有效(或推荐的方法)是什么 class 并使其在我的控制器中可访问?

我曾尝试使用 IMemoryCache,但尽管在此启动阶段将值放入缓存中,但当我尝试访问我的控制器中的缓存时,它始终是空的。

是否有 better/preferred 方法来持久化启动时的值 class 以供以后在生命周期中使用?

我可以在 HttpContext.Authentication.HttpAuthenticationFeature.Handler.Options 中看到我可以访问 oidc 的所有 OpenIdConnectOptions 属性和设置,但是我无法在任何地方看到我在令牌交换后存储的实际令牌值。

我对 Auth0 和 JWT 使用了类似的方法。我在声明服务器上存储了一些 app_metadata,在我的控制器中为每个请求检索和使用这些值。

Startup.cs 配置

var options = new JwtBearerOptions
        {
            Audience = AppSettings.Auth0ClientID,
            Authority = AppSettings.Auth0Domain
        };

        app.UseJwtBearerAuthentication(options);
        app.UseClaimsTransformation(new ClaimsTransformationOptions
        {
            Transformer = new Auth0ClaimsTransformer()
        });

AdminClaimType

public abstract class AdminClaimType : Enumeration
{
    public static readonly AdminClaimType AccountId = new AccountIdType();
    public static readonly AdminClaimType ClientId = new ClientIdType();
    public static readonly AdminClaimType IsActive = new IsActiveType();

    private AdminClaimType(int value, string displayName) : base(value, displayName)
    {

    }

    public abstract string Auth0Key { get; }
    public abstract string DefaultValue { get; }

    private class AccountIdType : AdminClaimType
    {
        public AccountIdType() : base(1, "AccountId")
        {             
        }

        public override string Auth0Key => "accountId";
        public override string DefaultValue => "0";
    }

    private class ClientIdType : AdminClaimType
    {
        public ClientIdType() : base(2, "ClientId")
        {
        }

        public override string Auth0Key => "clientId";
        public override string DefaultValue => "0";
    }

    private class IsActiveType : AdminClaimType
    {
        public IsActiveType() : base(3, "IsActive")
        {
        }

        public override string Auth0Key => "isActive";
        public override string DefaultValue => "false";
    }
}

Auth0ClaimsTransformer

public class Auth0ClaimsTransformer : IClaimsTransformer
{

    private string _accountId = AdminClaimType.AccountId.DefaultValue;
    private string _clientId = AdminClaimType.ClientId.DefaultValue;
    private string _isActive = AdminClaimType.IsActive.DefaultValue;

    public Task<ClaimsPrincipal> TransformAsync(ClaimsTransformationContext context)
    {
        //TODO: Clean up and simplify AdminClaimTypes Transformer
        foreach (var claim in context.Principal.Claims)
        {
            switch (claim.Type)
            {
                case "accountId":
                    _accountId = claim.Value ?? _accountId;
                    break;
                case "clientId":
                    _clientId = claim.Value ?? _clientId;
                    break;
                case "isActive":
                    _isActive = claim.Value ?? _isActive;
                    break;
            }
        }
        ((ClaimsIdentity)context.Principal.Identity)
            .AddClaims(new Claim[]
            {
                new Claim(AdminClaimType.AccountId.DisplayName, _accountId),
                new Claim(AdminClaimType.ClientId.DisplayName, _clientId), 
                new Claim(AdminClaimType.IsActive.DisplayName, _isActive)
            });

        return Task.FromResult(context.Principal);
    }

BaseAdminController

//[Authorize]
[ServiceFilter(typeof(ApiExceptionFilter))]
[Route("api/admin/[controller]")]
public class BaseAdminController : Controller
{
    private long _accountId;
    private long _clientId;
    private bool _isActive;

    protected long AccountId
    {
        get
        {
            var claim = GetClaim(AdminClaimType.AccountId);
            if (claim == null)
                return 0;

            long.TryParse(claim.Value, out _accountId);
            return _accountId;
        }
    }

    public long ClientId
    {
        get
        {
            var claim = GetClaim(AdminClaimType.ClientId);
            if (claim == null)
                return 0;

            long.TryParse(claim.Value, out _clientId);
            return _clientId;
        }
    }

    public bool IsActive
    {
        get
        {
            var claim = GetClaim(AdminClaimType.IsActive);
            if (claim == null)
                return false;

            bool.TryParse(claim.Value, out _isActive);
            return _isActive;
        }
    }

    public string Auth0UserId
    {
        get
        {
            var claim = User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier);
            return claim == null ? string.Empty : claim.Value;
        }
    }

    private Claim GetClaim(AdminClaimType claim)
    {
        return User.Claims.FirstOrDefault(x => x.Type == claim.DisplayName);
    }
}

现在在继承自 BaseAdminController 的控制器 类 中,我可以访问:

  • 账号
  • 客户编号
  • 有效
  • Auth0UserId
  • 还有什么我想补充的

希望对您有所帮助。

所以我想通了。它可以通过 AuthenticationManager 在 HttpContext 上使用:

var idToken = ((AuthenticateInfo)HttpContext.Authentication.GetAuthenticateInfoAsync("Cookies").Result).Properties.Items[".Token.id_token"];

工作愉快:)