Migrating from FormsAuthentication to Identity. FormsAuthentication.DefaultUrl - asp.net

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.

Related

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

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]",
});
}

Logging out all cookied users

I have an ASP.NET MVC5 app which used to have indefinite timeouts, so users weren't logged out until they actually clicked the 'log out' link. This was changed a few weeks back using the code below in Startup.Auth.cs
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/"),
ExpireTimeSpan = TimeSpan.FromMinutes(29),
SlidingExpiration =true
});
The problem is that there are users who were cookied before the change who still seem to be logged in. Is there a way of logging out these users without deploying a change to the app to store/check for an extra value in the cookie?
Best thing would be to introduce SecurityStamp validation. All your cookies already have a value that you can check against, and you don't really need to do much yourself. Add CookieAuthenticationProvider to your CookieAuthenticationOptions like this:
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/"),
ExpireTimeSpan = TimeSpan.FromMinutes(29),
SlidingExpiration = true,
Provider = new CookieAuthenticationProvider
{
// Enables the application to validate the security stamp when the user logs in.
// This is a security feature which is used when you change a password or add an external login to your account.
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager)),
},
});
This SecurityStampValidator will cause the cookies to regenerate every 30 minutes. You can reduce the validation interval as required, but I don't recommend going too short intervals as it'll increase load on your DB. I usually use 10 minutes.
Unfortunately you'll still have to redeploy this change, but not much code for you to write :-)

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);
},

Make custom request when auth session is expired or user logged out

In one MVC project, I implemented asp.net identity based on cookies. Now I have a requirement to make a request to remote service when auth session is expired or when user logged off.
Is there any natural way to accomplish that? For now I managed to set two delegate properties from CookieAuthenticationProvider like below:
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Login"),
CookieSecure = CookieSecureOption.SameAsRequest,
ExpireTimeSpan = TimeSpan.FromMinutes(expireInMinutes),
CookiePath = cookiePath,
Provider = new CookieAuthenticationProvider
{
OnValidateIdentity = c =>
{
if (c.Properties.ExpiresUtc.HasValue && c.Properties.ExpiresUtc.Value < c.Options.SystemClock.UtcNow)
{
c.RejectIdentity();
c.Request.Context.Authentication.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
return Task.FromResult(0);
}
if (c.Options.SlidingExpiration)
{
// Reissue the auth cookie
}
return Task.FromResult(0);
},
OnResponseSignOut = c =>
{
// Make a custom request
}
}
});
At first glance it looks like it works but I don't like the idea of checking expiry date in here. Problem is that OnResponseSignOut is not called when auth cookie is simply expired but is called only when I explicitly call IAuthenticationManager.SignOut.
Is creating a custom CookieAuthenticationProvider the best option in here, or maybe there is another clean and natural solution for that case?

OWIN Cookies and IP address

When I am testing the samples in VS 2013 out the box, they work fine with localhost or when accessing from localhost - the cookie is generated fine and saved in domain localhost.
I then wanted to do some testing from iPad on Safari, so I enabled IP address access on IISExpress. When I access my test website via IP address 10.0.0.x:port, no cookie is provided.
I have the stock standard line:
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login")
});
How can I "name" my cookie for MS Identity to use so that regardless of the browser domain name "localhost" "IP" or "XXXX" that it will still work?
I am not sure why this did not work initially. I am still playing around with this. But i changed the startup cookie config to (in Startup.Auth.cs):
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = "ABC",
LoginPath = new PathString("/Account/Login"),
CookieName = "ABC"
});
And i then modified the following line in SignIn (IdentityModels.cs)
var identity = manager.CreateIdentity(user, "ABC");
And it started working.

Resources