在ConfigureServices方法中添加:
services.AddAuthentication(options => { options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme; }) .AddCookie() .AddOpenIdConnect(options => { options.Authority = Configuration["Authentication:Authority"]; options.ClientId = Configuration["Authentication:ClientId"]; options.ClientSecret = Configuration["Authentication:ClientSecret"]; options.ResponseType = OpenIdConnectResponseType.IdToken; options.CallbackPath = "/signin-oidc"; options.SignedOutCallbackPath = "/signout-callback-oidc"; options.UsePkce = false; options.SaveTokens = true; options.GetClaimsFromUserInfoEndpoint = true; options.TokenValidationParameters = new TokenValidationParameters { NameClaimType = "name", RoleClaimType = "role" }; });
在Configure方法中添加:
app.UseAuthentication();
然后在控制器中使用以下代码:
if (User.Identity.IsAuthenticated) { string idToken = await HttpContext.GetTokenAsync("id_token"); // 使用id token }
这将从缓存中获取id_token以供后续使用。