Created a mvc5 app with Identity2, how do i set it up to use session cookies, so they expire when the browser closes - asp.net

Created a mvc5 app with Identity2,using google login (pretty much the empty app, with google stuff turned on)
How do I set it up to use session cookies, so they expire when the browser closes.
The app will be used by students who may hot swap seats, so i need the login to expire when the browser closes.
I read an SO article that implies this is the default, but when i close the browser, and go back to the site, it remembers the google login.
Edit
Sorry to burst everyone bubble, but this isn't a duplicate.
It reproduced in Chrome after the settings in the supposed "answer" are changed, and it also reproduces in IE... This is an Asp.net Identity 2 +Google login issue, not a Chrome issue.
Edit
Adding Startup Auth file for Setup Help
using System;
using System.Configuration;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.Google;
using Owin;
using StudentPortalGSuite.Models;
namespace StudentPortalGSuite
{
public partial class Startup
{
// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
public void ConfigureAuth(IAppBuilder app)
{
// Configure the db context, user manager and signin manager to use a single instance per request
app.CreatePerOwinContext(ApplicationDbContext.Create);
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
{
// 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 )
)
},
});
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
// Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));
// per https://learn.microsoft.com/en-us/aspnet/mvc/overview/security/create-an-aspnet-mvc-5-app-with-facebook-and-google-oauth2-and-openid-sign-on - EWB
//dev-jcsn email
app.UseGoogleAuthentication( new GoogleOAuth2AuthenticationOptions()
{
ClientId = "...",
ClientSecret = "..."
} );
//});
}
}
}
EDIT
The use case I'm trying to fix is, since our app is used in a classroom, that student A Closes his/her browser instead of logging out, and then next user tries to login. As it stands they are autologged into user A's account.
I'd also be up for a way to 100% log out the user when redirected to the login page, but all the ways I've tried that aren't working.

Maybe you can catch the window close event on page and call logout method
$(window).on("beforeunload", function() {
//ajax call to a post controller that logs the user out
})

Calling this at the top of the LogIn controller Method solved the issue.
Request.GetOwinContext().Authentication.SignOut( DefaultAuthenticationTypes.ApplicationCookie );// https://stackoverflow.com/questions/28999318/owin-authentication-signout-doesnt-seem-to-remove-the-cookie - stralos s answer
Request.GetOwinContext().Authentication.SignOut( DefaultAuthenticationTypes.ExternalCookie );

Related

Update UserIdentities with roles after Azure AD B2C login

I have a Blazor WASM application communicating with a ASP.NET 6 Web API.
User authentication is done via Azure AD B2C by attaching the AD token to Http requests sent to the Server using
builder.Services.AddHttpClient("Portal.ServerAPI", client => client.BaseAddress = new Uri("https://localhost:7001/api/"))
.AddHttpMessageHandler<SslAuthorizationMessageHandler>();
User specific information like UserRoles is stored in a user database.
I'm using the RemoteAuthenticatorView.OnLoginSuceeded handler to load the user profile containing the roles from the API server.
Then I add a new identity to the existing ClaimsPrincipal which I get from the AuthenticationStateProvider like so:
var state = await authStateProvider.GetAuthenticationStateAsync();
var user = state.User;
if (user.Identities.Any(x => x.Label == "myAuthToken"))
{
return;
}
// Turn the JWT token into a ClaimsPrincipal
var principal = tokenService.GetClaimsPrincipal(sslToken);
var identity = new ClaimsIdentity(principal.Identity);
identity.Label = "myAuthToken";
user.AddIdentity(identity);
Not sure if that's the right way to do this but it works fine.
Now my problem:
When I refresh the page by hitting F5 in the browser the above handler is not called and the roles are not written to the new identity, means user.IsInRole("myRole") doesn't work.
Does anyone have an idea how to solve the issue of enriching an existing user identity on Blazor with roles coming from the server?
Any help is much appreciated.

What to do to clear all cache about my client credential in 'logout' function

I made an app in xamarin forms that provides login/logout functionality.
This steps work correctly in UWP:
User start the app
User put correct credential and login (here wrong credential always doesn't work and this is ok)
User click logout
User put wrong credential and can't login
Unfortunately in Android in third step user still can login.
I've tried using functions like Abort() Close() Dispose() on my client. Regardless of that after make new object of my client and put in wrong credential still everything works.
this I make while login
BasicHttpBinding binding = new BasicHttpBinding();
binding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows; // (I can use here NTLM and basic, result is the same)
MyClient myClient = new MyClient(binding, new EndpointAddress(myUrl));
myClient.ClientCredentials.Windows.ClientCredential.UserName = username
myClient.ClientCredentials.Windows.ClientCredential.Password = password;
myClient.ClientCredentials.UserName.UserName = username;
myClient.ClientCredentials.UserName.Password = password;
// this I've tried after logout and idk what I can do more
myClient.InnerChannel.Abort();
myClient.InnerChannel.Close();
myClient.InnerChannel.Dispose();
myClient.Abort();
myClient.Close();
myClient = null;
// Edit
// I used Android.Webkit.CookieManager on Android when logout in this way:
var cookieManager = CookieManager.Instance;
cookieManager.RemoveAllCookie();
cookieManager.RemoveSessionCookie();
cookieManager.RemoveExpiredCookie();
cookieManager.Flush();
// but still the same problem, I'm using Android 8.1 so I don't need CookieSyncManager.Instance.Sync(), because it's deprecated since api 21
I expect that app will prevent from use wrong credential after logout in Android. Currently only UWP provides that succesfully.

How do I issue the corresponding Bearer and Cookie identity in ASP.NET with multiple Authorization schemes?

This documentation describes in part how to use more than one authentication scheme:
In some scenarios, such as Single Page Applications it is possible to end up with multiple authentication methods. For example, your application may use cookie-based authentication to log in and bearer authentication for JavaScript requests. In some cases you may have multiple instances of an authentication middleware. For example, two cookie middlewares where one contains a basic identity and one is created when a multi-factor authentication has triggered because the user requested an operation that requires extra security.
Example:
app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
AuthenticationScheme = "Cookie",
LoginPath = new PathString("/Account/Unauthorized/"),
AccessDeniedPath = new PathString("/Account/Forbidden/"),
AutomaticAuthenticate = false
});
app.UseBearerAuthentication(options =>
{
options.AuthenticationScheme = "Bearer";
options.AutomaticAuthenticate = false;
});
However it only describes how to use Bearer or Cookie auth. What isn't clear is what other combinations are valid, or how to properly issue bearer or cookies to the client.
How can that be accomplished?
One common use case for this which large sites like Facebook, Google etc. use is to use multiple cookie authentication middleware's and set one of them to be the default using AutomaticAuthenticate
app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
AuthenticationScheme = "InsecureLongLived",
LoginPath = new PathString("/Account/Unauthorized/"),
AccessDeniedPath = new PathString("/Account/Forbidden/"),
AutomaticAuthenticate = true
});
app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
AuthenticationScheme = "SecureAndShortLived",
LoginPath = new PathString("/Account/Unauthorized/"),
AccessDeniedPath = new PathString("/Account/Forbidden/"),
AutomaticAuthenticate = false
});
The default one is long lived and used for non-critical auth scenarios e.g. on Facebook, this may be to view your profile page.
The more secure and short lived on is used for security critical user actions like changing your password or profile information.
This gives you the convenience of not having to login all the time with a long lived cookie but as soon as you need to do something potentially dangerous, you switch to doing auth with a much shorter lived and thus more secure cookie which requires the user to login again.

Single page redirect issue for public url using thinktecture

I am creating a single page application with angularJs, aspnet and thinktecture. I have created a login screen in thinktecture (as localhost:44304) for customer login and after successful login, it redirects to customer portal like https://localhost:44302.
when I run the customer app then it redirected to thinktecture login screen and after a login success, it come back to customer portal.
Now issue is that any customer can register a request by using registration page which is placed on the customer portal and we are redirecting it from thinktecture login screen as shown
When I click on "here" link then redirect me again same login screen.
I added the code as below in startup.cs for customer poratal.
System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en-us");
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = "Cookies"
});
string thinkTectureUrl = ConfigurationManager.AppSettings["ThinkTectureUrl"].ToString();
string loginSuccessUrl = ConfigurationManager.AppSettings["LoginSuccessUrl"].ToString();
string clientSecret = ConfigurationManager.AppSettings["ClientSecret"].ToString();
app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions()
{
ClientId = "Provista.CustomerPortal.WebApp.External",
Authority = thinkTectureUrl,
RedirectUri = loginSuccessUrl,
ResponseType = "id_token",
Scope = "openid email",
SignInAsAuthenticationType = "Cookies",
ClientSecret = clientSecret.Sha256()
});
I searched on google and stackoverflow a lot but didn't get a reliable link that help me to solve this.
Please reply as soon as possible if any one have any idea.
You might have global authorization filter which redirects unauthenticated users to identity server. Probably in Global.asax
filters.Add(new System.Web.Mvc.AuthorizeAttribute());
Requests to your 'Register User controller' also treated by this filter and redirect to identity server will happen.
To override global filter and allow unauthenticated users to your Register User controller use [AllowAnonymous] attribute in your 'Register User controller'.

DotNetOpenAuth Failing to work on Live Server

I worked on a sample application integrating OpenID into ASP.NET Web Forms. It works fine when hosted locally on my machine. However, when I uploaded the application to a live server, it started giving "Login Failed".
You can try a sample here: http://samples.bhaidar.net/openidsso
Any ideas?
Here is the source code that fails to process the OpenID response:
private void HandleOpenIdProviderResponse()
{
// Define a new instance of OpenIdRelyingParty class
using (var openid = new OpenIdRelyingParty())
{
// Get authentication response from OpenId Provider Create IAuthenticationResponse instance to be used
// to retreive the response from OP
var response = openid.GetResponse();
// No authentication request was sent
if (response == null) return;
switch (response.Status)
{
// If user was authenticated
case AuthenticationStatus.Authenticated:
// This is where you would look for any OpenID extension responses included
// in the authentication assertion.
var fetchResponse = response.GetExtension<FetchResponse>();
// Store the "Queried Fields"
Session["FetchResponse"] = fetchResponse;
// Use FormsAuthentication to tell ASP.NET that the user is now logged in,
// with the OpenID Claimed Identifier as their username.
FormsAuthentication.RedirectFromLoginPage(response.ClaimedIdentifier, false);
break;
// User has cancelled the OpenID Dance
case AuthenticationStatus.Canceled:
this.loginCanceledLabel.Visible = true;
break;
// Authentication failed
case AuthenticationStatus.Failed:
this.loginFailedLabel.Visible = true;
break;
}
}
As Andrew suggested, check the exception. In my case, my production server's time & date were off and it wouldn't authenticate because the ticket expired.
Turn on logging on your live server and inspect them for additional diagnostics. It's most likely a firewall or permissions problem on your server that prevents outbound HTTP requests.
You may also find it useful to look at the IAuthenticationResponse.Exception property when an authentication fails for clues.

Resources