Asp.net 4.8 MVC 5.2.3.0
After a user is authenticated through Okta and goes back to my application, I will do some check against my database, if say I found the user is not active, I will log him out. How do I do this?
I tried to do this in Startup.cs on OpenIdConnectEvents named SecurityTokenValidated. Like this:
notification.OwinContext.Authentication.SignOut(
CookieAuthenticationDefaults.AuthenticationType,
OktaDefaults.MvcAuthenticationType);
But sometimes it works and sometimes it doesn’t.
Can someone tell me how to achieve this?
Also I have trouble getting ApplicationUserManager. I did as follows. Although it works, it is awkward.
ApplicationUserManager applicationUserManager = notification.OwinContext.Get<ApplicationUserManager>("AspNet.Identity.Owin:CAVMWidget.Web.Controllers.Conf.ApplicationUserManager, CAVMWidget.Web.Controllers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null");
code:
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseOktaMvc(new OktaMvcOptions()
{
OktaDomain = ConfigurationManager.AppSettings["okta:OktaDomain"],
// ...
OpenIdConnectEvents = new OpenIdConnectAuthenticationNotifications
{
SecurityTokenValidated = SecurityTokenValidatedHandler
}
});
}
private async Task SecurityTokenValidatedHandler(SecurityTokenValidatedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> notification)
{
bool isAdmin = false;
// ...
string email = notification.AuthenticationTicket.Identity.Claims.FirstOrDefault(c => c.Type == "email").Value;
ApplicationUserManager applicationUserManager = notification.OwinContext.Get<ApplicationUserManager>("AspNet.Identity.Owin:CAVMWidget.Web.Controllers.Conf.ApplicationUserManager, CAVMWidget.Web.Controllers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null");
Data.Models.User user = await applicationUserManager.FindByEmailAsync(email);
if (isAdmin)
{
if (!user.Roles.Any())
{
notification.OwinContext.Authentication.SignOut(
CookieAuthenticationDefaults.AuthenticationType,
OktaDefaults.MvcAuthenticationType);
}
}
else
{
CollateralProfile profile = user.Profiles.FirstOrDefault();
if (profile == null || !profile.IsActive)
{
notification.OwinContext.Authentication.SignOut(
CookieAuthenticationDefaults.AuthenticationType,
OktaDefaults.MvcAuthenticationType);
}
}
}
}