我已将 AddOpenIdConnect 添加到我的 ASP.NET Core 3.1 Razor 应用程序的 ConfigureServices 方法。 AddOpenIdConnect 用于配置执行 OpenID Connect 协议以从身份提供者获取令牌的处理程序。但我想不将令牌存储在 cookie 中,而是存储在内存或数据库中。 知道如何实现这一目标吗?
我像这样在 starup.cs 中添加了身份验证处理程序
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme =
CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
}).AddCookie()
.AddOpenIdConnect(options =>
{
options.ClientId = Configuration.GetValue<string>("Okta:ClientId");
options.ClientSecret = Configuration.GetValue<string>("Okta:ClientSecret");
options.Authority = $"{Configuration.GetValue<string>
("Okta:Authorization")}";
options.CallbackPath = "/api/callback";
options.SignedOutCallbackPath = "/api/signout-callback";
options.ResponseType = "code";
options.SaveTokens = true;
options.UseTokenLifetime = false;
options.GetClaimsFromUserInfoEndpoint = true;
options.Scope.Add("openid");
options.Scope.Add("profile");
options.Scope.Add("email");
options.Scope.Add("offline_access");
options.TokenValidationParameters = new TokenValidationParameters
{
NameClaimType = "name",
RoleClaimType = "role"
};
options.Events = new OpenIdConnectEvents()
{
OnUserInformationReceived = context =>
{
string rawAccessToken = context.ProtocolMessage.AccessToken;
string rawIdToken = context.ProtocolMessage.IdToken;
string rawRefreshToken = context.ProtocolMessage.RefreshToken;
var handler = new JwtSecurityTokenHandler();
var accessToken = handler.ReadJwtToken(rawAccessToken);
var idToken = handler.ReadJwtToken(rawIdToken);
// do something with the JWTs
var userClaims = new List<Claim>()
{
new Claim("accessToken",rawAccessToken),
new Claim("idToken", rawIdToken)
// new Claim("refreshToken", rawRefreshToken)
};
var userIdentity = new ClaimsIdentity(userClaims, "Okta Identity");
var userPrincipal = new ClaimsPrincipal(new[] { userIdentity });
context.Principal = userPrincipal;
return Task.CompletedTask;
},
};
});
services.AddHttpClient();
services.AddAuthorization();
services.AddControllersWithViews();
知道如何完成这项工作吗?