如果OnTokenValidated
用户不存在您的数据库,您可以抛出特定异常。然后OnRemoteFailure
事件将用户重定向到该特定异常的特定操作方法
options.Events = new OpenIdConnectEvents()
{
OnTokenValidated = async context =>
{
// get email claim
var emailClaim = context.Principal.Claims.SingleOrDefault(x => x.Type == ClaimTypes.Email);
UserEntity cu = null;
using (var accountService = context.HttpContext.RequestServices.GetService<IAccountService>())
{
cu = await accountService.Authorize(emailClaim.Value);
}
if (cu == null)
{
throw new UnauthorizedAccessException(string.Format("Could not find user for login '{0}' ", emailClaim.Value));
}
var newIdentity = new ClaimsIdentity(context.Principal.Identity.AuthenticationType);
// keep the id_token for logout
newIdentity.AddClaim(new Claim("id_token", context.ProtocolMessage.IdToken));
// add email claim
newIdentity.AddClaim(emailClaim);
// add email value as name claim
newIdentity.AddClaim(new Claim(ClaimTypes.Name, emailClaim.Value));
// add other claims here like roles
context.Properties.IsPersistent = true;
context.Properties.ExpiresUtc = DateTime.UtcNow.AddHours(3);
// overwrite existing authentication ticket
context.Principal = new ClaimsPrincipal(newIdentity);
},
OnRedirectToIdentityProviderForSignOut = async context =>
{
var idTokenHint = context.HttpContext?.User?.FindFirst("id_token");
if (idTokenHint != null)
context.ProtocolMessage.IdTokenHint = idTokenHint.Value;
await Task.FromResult(0);
},
OnRemoteFailure = async context =>
{
if (context.Failure is UnauthorizedAccessException)
{
context.Response.Redirect("/Account/UnAuthorized");
}
else
{
context.Response.Redirect("/Account/Error");
}
context.HandleResponse();
await Task.FromResult(0);
}
};
账户控制器.cs
public class AccountController : Controller
{
[AllowAnonymous]
public IActionResult UnAuthorized()
{
HttpContext.Session.Clear();
await Microsoft.AspNetCore.Authentication.AuthenticationHttpContextExtensions.SignOutAsync(HttpContext, CookieAuthenticationDefaults.AuthenticationScheme);
await Microsoft.AspNetCore.Authentication.AuthenticationHttpContextExtensions.SignOutAsync(HttpContext, OpenIdConnectDefaults.AuthenticationScheme);
}
}