Asp.net identity keep user login - asp.net-mvc

I have to keep user login for 15 hours but its logout after about 20 minutes of inactivity.
My code in startup.auth.cs is
public void ConfigureAuth(IAppBuilder app)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
ExpireTimeSpan = TimeSpan.FromHours(15),
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
SlidingExpiration = true,
Provider = new CookieAuthenticationProvider
{
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
validateInterval: TimeSpan.FromMinutes(0),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
}
}
}
Why user is logged out after about 20 minutes of inactivity?

As you say, you want to keep session active then put this following key in web.config.
maybe your application session get expired in 20 minutes(it is default value )
<sessionState timeout="900" cookieless="AutoDetect">

Related

Updating Claims Value without logging out and back in

I set Claim value after register user.
await _userManager.AddClaimAsync(user.Id,new Claim("DeActive", "1"));
user only visit special pages. after fill a form i remove this Claim, The user can now access all pages.
await _userManager.RemoveClaimAsync(CurrentUser.UserId, new Claim("DeActive", "1"));
But the problem is that the user has to log in again to clear the Claim.
How to update Claims value without logout?
Yes, your claim will update, after you remove/add it.
The issue is HOW LONG does it take... in your startupAuth.cs you have setting that needs to be modified my guess is you used the default its ~30 mins, change that to
TimeSpan.FromMinutes(30) to TimeSpan.FromMilliseconds(75)
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/HiddenLogin"),
Provider = new CookieAuthenticationProvider
{
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
validateInterval: TimeSpan.FromMinutes(30), // change this as above
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
}
});

Mixing ASP.net Identity and Azure AD authentication

We use ASP.Net Identity for our DB backed login currently and need to add support for Azure AD SSO.
I appreciate once logged in I will need to link the SSO user to a user in our system to assign the relevant Claims and Roles but am struggling to get the 2 authentication methods working side by side and app.UseCookieAuthentication seems to be at the root of my problems.
Currently we have:
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Login/Index"),
ReturnUrlParameter = "url",
Provider = new CookieAuthenticationProvider
{
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, IdentityUser>(
validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
},
ExpireTimeSpan = TimeSpan.FromMinutes(double.Parse(ConfigurationManager.AppSettings["AuthenticationTimeout"])),
SlidingExpiration = true
});
With this in I suspect the cookie returned by the SSO isn't getting processed correctly as the Request.IsAuthenticated is always false.
If I change it to:
app.UseCookieAuthentication(new CookieAuthenticationOptions());
Then the SSO works and returns me an authenticated request but obviously breaks the Identity login.
For info my OpenId setup is as follows, for now just trying to get it to work with our work AD but eventually will need to expand to multi tenant:
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
ClientId = clientId,
Authority = authority,
RedirectUri = redirectUri,
PostLogoutRedirectUri = redirectUri,
Scope = OpenIdConnectScope.OpenIdProfile,
ResponseType = OpenIdConnectResponseType.IdToken,
TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuer = false
},
Notifications = new OpenIdConnectAuthenticationNotifications
{
AuthenticationFailed = OnAuthenticationFailed
}
}
);
Any help or pointers appreciated.
try using the
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
before
app.UseOpenIdConnectAuthentication

Is it possible to change HttpContext.Current.User.Identity.Name after change username

I'm working on a ASP MVC application. And want to change username without making user logout. I am using Identity Provider version 1.0.11. My code looks like:
var updtUser = UserManager.FindById(model.UserId);
updtUser.UserName = model.PrivateEMail;
var res = await UserManager.UpdateAsync(updtUser);
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
updtUser.UserName,
DateTime.Now,
DateTime.Now,
false,
"someData",
FormsAuthentication.FormsCookiePath);
string encTicket = FormsAuthentication.Encrypt(ticket);
Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));
return RedirectToAction("RedirectToDashbord", "Dashboard", new { area = "CRM"});
But after this manipulations HttpContext.Current.User.Identity.Name is not changed. Any help would be great
You should enable immediate revocation of cookies (+):
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
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.FromSeconds(0),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
}
});

Owin, WebApi, and UseCookieAuthentication

I've configured OWIN in my ASP.NET MVC application using cookie authentication, but when I attempt to access an ApiController with an Authorize attribute on it, authorization fails and I can't figure out why. Stepping into the IsAuthorized method of the Authorize attribute, I can see that none of the identity properties that are present when accessing an MVC controller are present, so it certainly appears (at least to the authorize attribute) that the user is not authenticated.
The app is configured as follows:
public void ConfigureAuth(IAppBuilder app)
{
app.CreatePerOwinContext(MyAuthContext.Create);
app.CreatePerOwinContext<MyUserManager>(MyUserManager.Create);
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
{
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<MyUserManager, MyUser>(
validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
}
});
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
var httpConfig = new HttpConfiguration();
WebApiConfig.Register(httpConfig);
app.UseWebApi(httpConfig);
}
Do I absolutely have to use bearer tokens for WebAPI or is there just something I'm missing.

Request.IsAuthenticated when using Identity with Owin for MVC and WebAPI

I have a ASP.Net WebAPI 2.1 that I have just transitioned across to using Identity 2.0 using bearer tokens. This works fine. Now I am attempting to pull in some MVC code to create a set of login and user management pages. My issue is that I can't seem to get Request.IsAuthenticated to work from my Razor views when I set the WebApi HttpConfigurationto SuppressDefaultHostAuthentication.
Below is my code, and I'm out of ideas as to how I can get this to work for both scenarios :(
Here's my Startup.cs which sets up the Identity OWIN module, and the WebAPI:
public class Startup
{
public void Configure(IAppBuilder app)
{
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
PublicClientId = "self";
OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/token"),
Provider = new ApplicationOAuthProvider(PublicClientId),
AuthorizeEndpointPath = new PathString("/api/account/externalLogin"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(14)
};
app.UseOAuthBearerTokens(OAuthOptions);
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
Provider = new CookieAuthenticationProvider
{
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager, DefaultAuthenticationTypes.ApplicationCookie))
}
});
var httpConfiguration = new HttpConfiguration();
// Disable this line to allow Request.IsAuthenticated to work
// But by doing this, it allows the 'redirect' to kick in on unauthenticated API requests, which returns a HTML page for a webapi call, rather than the JSON 'unauthenticated' response
httpConfiguration.SuppressDefaultHostAuthentication();
httpConfiguration.Filters.Add(new HostAuthenticationFilter(DefaultAuthenticationTypes.ApplicationCookie));
httpConfiguration.MapHttpAttributeRoutes();
app.UseWebApi(httpConfiguration);
}
}
Here's my Global.asax.cs, which sets up the MVC side of things (AFAIK OWIN doesn't support any form of app.UseMvc()):
public class WebApiApplication : HttpApplication
{
protected void Application_Start()
{
// pretty much the defaults here for everything, just renamed
AreaRegistration.RegisterAllAreas();
MvcConfig.ConfigureFilters(GlobalFilters.Filters);
MvcConfig.ConfigureRoutes(RouteTable.Routes);
MvcConfig.ConfigureBundles(BundleTable.Bundles);
}
}
Now in my Razor views, I would like to use Request.IsAuthenticated, as used in the Identity samples, but this fails when the httpConfiguration.SuppressDefaultHostAuthentication is enabled. I understand the goal of this extension is to remove the current identity after the Identity middleware has run -- so that the WebAPI authentication filter can do as it pleases. But I am hoping that on the MVC side of things, that the suppression wouldn't occur.
Example Razor view:
#if (Request.IsAuthenticated) // false when using httpConfiguration.SuppressDefaultHostAuthentication
{
<div>User.Identity.Email</div>
}
Can anyone help me? Is this even possible?
Thanks!
Looks like it's all about the ordering of the app builder. If I place the Identity bearer configuration before the WebAPI, then my WebAPI requests still utilize the Identity OWIN module. By placing the Cookie configuration after the WebAPI configuration, the Cookie Identity resolution occurs after the WebAPI identity removal, and before the MVC execution.
Unsure if this is the 'correct' way to go about doing it, but it seems to solve all of the test cases I have open.
public class Startup
{
public void Configure(IAppBuilder app)
{
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
PublicClientId = "self";
OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/token"),
Provider = new ApplicationOAuthProvider(PublicClientId),
AuthorizeEndpointPath = new PathString("/api/account/externalLogin"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(14)
};
app.UseOAuthBearerTokens(OAuthOptions);
var httpConfiguration = new HttpConfiguration();
httpConfiguration.SuppressDefaultHostAuthentication();
httpConfiguration.Filters.Add(new HostAuthenticationFilter(DefaultAuthenticationTypes.ApplicationCookie));
httpConfiguration.MapHttpAttributeRoutes();
app.UseWebApi(httpConfiguration);
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
Provider = new CookieAuthenticationProvider
{
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager, DefaultAuthenticationTypes.ApplicationCookie))
}
});
}
}
EDIT
The above works, but it seems to be better to utilize the app.MapWhen() functionality to do this.
public class Startup
{
public void Configure(IAppBuilder app)
{
// setup auth for all requests
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
PublicClientId = "self";
OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/token"),
Provider = new ApplicationOAuthProvider(PublicClientId),
AuthorizeEndpointPath = new PathString("/api/account/externalLogin"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(14)
};
app.UseOAuthBearerTokens(OAuthOptions);
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
Provider = new CookieAuthenticationProvider
{
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager, DefaultAuthenticationTypes.ApplicationCookie))
}
});
// setup webapi for only /api requests
app.MapWhen(
context => context.Request.Uri.PathAndQuery.StartsWith("/api"),
newApp => {
var httpConfiguration = new HttpConfiguration();
httpConfiguration.SuppressDefaultHostAuthentication();
httpConfiguration.Filters.Add(new HostAuthenticationFilter(DefaultAuthenticationTypes.ApplicationCookie));
httpConfiguration.MapHttpAttributeRoutes();
app.UseWebApi(httpConfiguration);
}
}
}

Resources