Logout Redirection to login page in MVC5 - asp.net-mvc-5

Title- Redirection to login after successfull logout
How to automatically redirect to login page after auto logout of the page in mvc5

Since you don't provide any details on your implementation of authentication/authorization, I will assume that you are using MVC5 with individual user accounts and are using OWIN middleware to handle your authentication cookies.
In it's simplest form, put this check if the Request(user) is authenticated in your Home controllers Index method.
public async Task<ActionResult> Index()
{
if (Request.IsAuthenticated)
{
// do something here
return View();
}
return RedirectToAction("Login", "Account");
}
In the Startup class, define your LoginPath as seen here in a standard implementation as assumed above:
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.FromMinutes(30),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
},
SlidingExpiration = true,
// Use this to customize the timeout duration if the default is too short/long
ExpireTimeSpan = TimeSpan.FromDays(14)
});

You need to create the session Timeout attribute.
This
link will help you to implement it.

Related

Kentor/Owin/Azure AD Authentication

I have a web forms app which I am trying to authenticate against Azure AD using SAML 2/Kentor/Owin. I think I have things configured OK, but when my login page issues the following command I am not being redirected to a login page.
HttpContext.Current.GetOwinContext().Authentication.Challenge(new AuthenticationProperties { RedirectUri = "/Login.aspx" });
Here is my startup.cs
private void ConfigureSAML2Authentication(IAppBuilder app) {
var authServicesOptions = new KentorAuthServicesAuthenticationOptions(false)
{
SPOptions = new SPOptions
{
EntityId = new EntityId("https://login.microsoftonline.com/<tenant guid>/saml2")
}
},
AuthenticationType = "KentorAuthServices",
Caption = "ADFS - SAML2p",
};
authServicesOptions.IdentityProviders.Add(new IdentityProvider(
new EntityId("https://sts.windows.net/<tenant guid>/"),
authServicesOptions.SPOptions)
{
MetadataLocation = "https://login.microsoftonline.com/<tenant guid>/federationmetadata/2007-06/federationmetadata.xml",
LoadMetadata = true,
});
app.UseKentorAuthServicesAuthentication(authServicesOptions);
}
As far as I can tell looking at the Network Tools in chrome, no auth request is being sent at all. Is anyone able to tell me why?
The AuthServices middleware is configured as Passive by default, so it will not automatically respond to an authentication challenge unless you specify the provider.
When you issue the challenge you should specify the same AuthenticationType that you used when the middleware was set up. By default this is "KentorAuthServices" but can be changed.
If you change your challenge to include the type, it should trigger the redirect:
HttpContext.Current.GetOwinContext().Authentication.Challenge(new AuthenticationProperties { RedirectUri = "/Login.aspx" }, "KentorAuthServices");

When the user is authenticate after few seconds identity redirect to login page but the session id remains in browser storage

Here the identity class for authentication. it works fine on my localhost but it's behaving strange after deployment on server.I used OWIN for authentication, it works fine for first login, but after few seconds if I refresh the page, it redirects me back to the login page.
public class IdentityConfig
{
public void Configuration(IAppBuilder app)
{
app.CreatePerOwinContext<AppDBContext>(AppDBContext.Create);
app.CreatePerOwinContext<AppUserManager>(AppUserManager.Create);
app.CreatePerOwinContext<AppRoleManager>(AppRoleManager.Create);
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<AppUserManager, AppUser>(
validateInterval: TimeSpan.FromMinutes(15),
regenerateIdentity: (manager, user) => manager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie))
},
CookieName = "MyCookie",
//CookieDomain = "www.example.com",
//CookieHttpOnly = true,
//CookieSecure = CookieSecureOption.Always,
ExpireTimeSpan = TimeSpan.FromMinutes(double.Parse(ConfigurationManager.AppSettings["app:SessionTimeout"])),
SlidingExpiration = true
});
}
}
Here the web.config code of search4best used for session timeout
<add key="owin:AppStartup" value="Search4Best.App_Start.IdentityConfig" />
<add key="app:SessionTimeout" value="15"/>
on web.config try this
<machineKeyvalidationKey="F18753F2CF84EFFFB10600B1E29D9849A74F080A1E1170BF728D8381979271EF6894673001C877FD8A349F8D953024019AF6C4C5090309B4569C1933ECC90D94"
decryptionKey="504430FBB7D426A3C401600906CD5C121DC0808B0D40328E02EAF7A59652157B"
validation="SHA1" decryption="AES"/>

Specifying custom external login page using OWIN and ACS WSFedAuth

I have a web application that uses ACS to federate multiple identity providers which I'm trying to migrate to use OWIN. I have a custom login page in a separate application (that shares a SSO experience with mine) which I was able to specify using the issuer attribute in the wsfederation configuration element in my existing pre-OWIN setup.
I've tried to replicate this behaviour using OWIN, but no matter what I try, an unauthenticated request is redirected to the standard (ugly) ACS login page. Here's how I've configured the middleware components:
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = CookieAuthenticationDefaults.AuthenticationType,
AuthenticationMode = AuthenticationMode.Active,
Provider = new CookieAuthenticationProvider
{
OnResponseSignIn = ctx => TransformClaims(ctx.OwinContext.Authentication.User, loggingService)
},
ExpireTimeSpan = TimeSpan.FromMinutes(int.Parse(ConfigurationManager.AppSettings["security:slidingExpirationMins"])),
SlidingExpiration = true,
});
app.UseWsFederationAuthentication(
new WsFederationAuthenticationOptions
{
AuthenticationType = CookieAuthenticationDefaults.AuthenticationType,
MetadataAddress = "https://mylogin.accesscontrol.windows.net/FederationMetadata/2007-06/FederationMetadata.xml",
Wtrealm = siteUrl,
Wreply = siteUrl,
AuthenticationMode = AuthenticationMode.Active,
});
The LoginPath property of the CookieAuthenticationOptions object won't work as it's not in the same application.
Any help with how I would specify the external login URL would be appreciated!
I would recommend setting to Passive the WSFederation middleware AuthenticationMode, otherwise it will keep intercepting outgoing 401s.

Changing ReturnUrl in OWIN RedirectToIdentityProvider notification

We are currently overriding WSFederationAuthenticationModule.RedirectToIdentityProvider in our product to change the returnUrl to which the users agent is redirected to after authentication.
Now we're in the proces of adopting OWIN (Katana) middleware instead of HttpModules. In the RedirectToIdentityProvider notification in WsFederationAuthenticationOptions, I see the WCtx parameter now contains a WsFedOwinState parameter which is encrypted using DPAPI.
How do I implement the RedirectToIdentityProvider action to change the return URL? Do I need to decrypt the WsFedOwinState parameter to add the returnUrl query parameter or is there some other way?
inside RedirectToIdentityProvider, you will have access to the WsFederationMessage.
Set the Wreply property to the value you need.
As a note: MachineKey is used by default, not DPAPI for protecting wctx.
In my case, I changed the return URL in SecurityTokenValidated and had the redirection from ADFS always go to the same URL
public void ConfigureAuth(IAppBuilder app)
{
app.SetDefaultSignInAsAuthenticationType(WsFederationAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = WsFederationAuthenticationDefaults.AuthenticationType });
app.UseWsFederationAuthentication(new WsFederationAuthenticationOptions
{
Wtrealm = realm,
MetadataAddress = adfsMetadata,
Notifications = new WsFederationAuthenticationNotifications
{
SecurityTokenValidated = nx =>
{
nx.AuthenticationTicket.Properties.RedirectUri = "/RedirectionGoesHere.aspx";
return Task.FromResult(0);
}
}
});
// This makes any middleware defined above this line run before the Authorization rule is applied in web.config
app.UseStageMarker(PipelineStage.Authenticate);
}

How to enable basic authentication without user sessions with ServiceStack?

According ServiceStack github wiki In order to add/enable basic authentication in ServiceStack following lines of code are required:
Plugins.Add(new AuthFeature(() => new AuthUserSession(),
new IAuthProvider[] {
new BasicAuthProvider(), //Sign-in with Basic Auth
new CredentialsAuthProvider(), //HTML Form post of UserName/Password credentials
}));
But how can I add basic authentication without user sessions?
If you want to perform the authentication without using sessions then you can create a simple request filter that performs the basic authentication yourself.
You can then authenticate the credentials either against your own database or repositor, or you can authenticate against the standard ServiceStack repository shown below:
public class MyAuthenticateAttribute : RequestFilterAttribute
{
public override void Execute(IRequest req, IResponse res, object requestDto)
{
// Determine if request has basic authentication
var authorization = req.GetHeader(HttpHeaders.Authorization);
if(!String.IsNullOrEmpty(authorization) && authorization.StartsWith("basic", StringComparison.OrdinalIgnoreCase))
{
// Decode the credentials
var credentials = Encoding.UTF8.GetString(Convert.FromBase64String(authorization.Substring(6))).Split(':');
if(credentials.Length == 2)
{
// Perform authentication checks. You could do so against your own database
// or you may wish to use the ServiceStack authentication repository IUserAuthRepository
// If you want to check against ServiceStacks authentication repository
var repository = HostContext.TryResolve<IUserAuthRepository>();
if(repository == null)
throw new Exception("Authentication Repository is not configured");
// Try authenticate the credentials
IUserAuth user;
if(repository.TryAuthenticate(credentials[0], credentials[1], out user))
{
// Authenticated successfully
// If you need the user details available in your service method
// you can set an item on the request and access it again in your service
// i.e. req.SetItem("user", user);
// In your service: Request.GetItem("user") as IUserAuth
return;
}
}
}
// User requires to authenticate
res.StatusCode = (int)HttpStatusCode.Unauthorized;
res.AddHeader(HttpHeaders.WwwAuthenticate, "basic realm=\"My Secure Service\"");
res.EndRequest();
}
}
So instead of using the [Authenticate] attribute you would use the [MyAuthenticate] attribute.
In your AppHost Configure method do not add the AuthFeature plugin. You do still however need to add the repository, if that's how you choose to authenticate the credentials against.
container.Register<ICacheClient>(new MemoryCacheClient());
var userRep = new InMemoryAuthRepository();
container.Register<IUserAuthRepository>(userRep);
I hope this helps.

Resources