ASP.NET MVC 5 Force all users to logout (using cookie auth) - asp.net

I'm using ASP.NET MVC 5 with cookie-based authentication. I want to make a change in user roles and enforce it right away, but roles don't change until a user logs out and back in.
How can I force all users to logout or to renew their identity cookie?

Turns out this is pretty easy. You can change the cookie name (default is ASP.NET_SessionId, source).
This causes the website to look for a different session cookie name, making the old cookies invalid.
public void ConfigureAuth(IAppBuilder app)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
ExpireTimeSpan = TimeSpan.FromDays(7),
CookieName = "[NewNameHere]",
});
}

Related

ASP.NET OWIN Custom Cookie Authentication

We are running a classic asp web application, and want to it to work together with new developed MVC application. We want to make use of the authentication of the classic asp app in the MVC application.
The idea is when user log into the classic asp app, it will issue kind of auth cookie, the cookie is encrypted in our own method. Cookie will contain use identity.
Client then browse to the MVC app along with this auth cookie. The MVC app will check if the cookie present and validate it. With it is not redirect to the classic asp login page.
So I'm thinking to customize the OWIN cookie authentication to use my own authentication logic. I tried to implement the CookieAuthenicationProvider however I don't know where to put my logic.
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
CookieName = ".classicauth",
CookieSecure = CookieSecureOption.SameAsRequest,
CookieHttpOnly = true,
Provider = new CookieAuthenticationProvider
{
OnValidateIdentity = context => {
//?? where I can extract the cookie and validate it??
context.RejectIdentity();
return Task.FromResult<int>(0);
},
OnApplyRedirect = context => {
context.Response.Redirect("classic_asp_login_url");
}
}
});
The CookieAuthenticationProvider have a OnValidateIdentity, however it seem not the right place to extract cookie and validate it.
Thanks.
Jason.
I haven't tested it my self in that particular context. But CookieManager works for me.
OnValidateIdentity = context => {
var cookie = context.Options.CookieManager.GetRequestCookie(context.OwinContext, context.Options.CookieName);
context.RejectIdentity();
return Task.FromResult<int>(0);
},

ASP.NET Identity 2 execute code after cookie authentication

I'm using ASP.NET Identity 2 authentication via OWIN middlewear. I've created a new project using the template so initially started with the default generated code but have changed it a bit (taken out entity framework and wired in my own existing authentication). This is all working.
What I'd now like to do is execute code after a user logs in via a saved cookie. I've had a look at ConfigureAuth in the Startup.Auth.cs file which I've configured as follows:
public void ConfigureAuth(IAppBuilder app) {
// Configure the user manager and signin manager to use a single instance
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
// Enable the application to use a cookie to store information for the signed in user
// and to use a cookie to temporarily store information about a user logging in with a third party login provider
// Configure the sign in cookie
app.UseCookieAuthentication(new CookieAuthenticationOptions {
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider {
OnResponseSignIn = ctx => {
Log.Trace("On Response Sign In.");
},
OnResponseSignedIn = ctx => {
Log.Trace("On Response Signed In.");
},
OnValidateIdentity = async ctx => {
Log.Trace("On Validate Identity.");
}
}
});
}
From this I can see that OnResponseSignIn and OnResponseSignedIn are hit only during actual logins when the user enters their username and password. They are not hit when the user is authenticated via saved cookie.
OnValidateIdentity is hit regardless of whether the user authenticated via username/password or saved cookie and it's hit for every request they make.
What I'd like is to execute code just once after a login via cookie. Does anyone know how to do this? If not, I guess another option is to put code in OnValidateIdentity but in an if statement that will prevent it being run unless its the first call after the cookie authentication. Can anyone think of how to achieve that? All I can think of is to set a variable in Session after the code is first run and check for it's presence to prevent it being re-run?
It can probably be done by using a session variable as a flag, and only do your thing when it is not set.
OnValidateIdentity = async context => {
if (HttpContext.Current.Session["Refreshed"] == null)
{
/** do your thing **/
...
HttpContext.Current.Session["Refreshed"] = new object();
}
}

Migrating from FormsAuthentication to Identity. FormsAuthentication.DefaultUrl

When migrating from FormsAuthentication to Identity I have some code that have :
return Redirect(FormsAuthentication.DefaultUrl);
In Identity I don't find this configuration (also I don't know why it was on FormsAuthentication in the first place) I'm going to change to
return Redirect("~/");
Is there any Identity configuration for this scenario or is just removed that functionability from identity ?
This is non-existing in Identity.
However when you do Identity configuration, you do stuff like this in Auth.Config.cs
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
// other stuff
}
See the LoginPath property set? that's the redirecting address that is now working the same way as FormsAuthentication.DefaultUrl, only you don't specify it in web.config.

Mixing Owin Asp.Net Identity Cookie Authentication with Owin OpenId Authentication

Does anyone know a good example of mixing Owin Asp.Net Identity Cookie Authentication (local db) with Owin OpenId Authentication (cloud)? Users could then choose to login/register with either creating new user&pass (stored in local database) or via e.g. Office 365 account. But all users will use the claims and roles in the asp.net Identity (local database).
I have done it like this, but I have some weird issues. Here is my ConfigureAuth method in Startup.Auth.cs
public void ConfigureAuth(IAppBuilder app)
{
// Configure the db context and user manager to use a single instance per request
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
//app.Properties["Microsoft.Owin.Security.Constants.DefaultSignInAsAuthenticationType"] = "ExternalCookie";
// Enable the application to use a cookie to store information for the signed in user
// and to use a cookie to temporarily store information about a user logging in with a third party login provider
// Configure the sign in cookie
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
// LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
{
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
}
});
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
ClientId = clientId,
Authority = authority,
PostLogoutRedirectUri = postLogoutRedirectUri
});
}
Logoff method in AccountController
public ActionResult LogOff()
{
//AuthenticationManager.SignOut();
AuthenticationManager.SignOut(
DefaultAuthenticationTypes.ExternalCookie,
DefaultAuthenticationTypes.ApplicationCookie,
OpenIdConnectAuthenticationDefaults.AuthenticationType,
CookieAuthenticationDefaults.AuthenticationType
);
return RedirectToAction("Login", "Account");
}
Here is the issue, I tried to explain on another thread which hasn't got any response yet.
Link for the question

UseGoogleAuthentication force login session expiration?

I'm using ASP.NET MVC 5's external authentication middleware UseGoogleAuthentication/UseExternalSignInCookie with GoogleOAuth2AuthenticationOptions. Is there a way to force a user to have to re-authenticate with Google each time a user visits the site?
Presently, if the user is already logged into Google and they access the site they do not have to re-authenticate with Google. Ideally the cookie assigned would only be good for their current session on the site...
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
var authOptions = new GoogleOAuth2AuthenticationOptions();
authOptions.ClientId = AppSettingsHelper.GoogleClientId;
authOptions.ClientSecret = AppSettingsHelper.GoogleClientSecret;
authOptions.CallbackPath = new PathString("/account/linklogincallback");
foreach (var scope in AppSettingsHelper.GoogleOAuthScope)
{
authOptions.Scope.Add(scope);
}
app.UseGoogleAuthentication(authOptions);
Replace app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); with app.UseCookieAuthentication(..) and specify the ExpireTimeSpan. UseExternalSignInCookie is just a helper for the cookie authentication method that uses certain defaults.
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ExternalCookie,
SlidingExpiration = true,
ExpireTimeSpan = new System.TimeSpan(0, 5, 0),
LoginPath = new PathString("/Account/Login")
});
Notice that we are using DefaultAuthenticationTypes.ExternalCookie here instead of ApplicationCookie

Resources