ASP.NET MVC - Same authentication between two applications - c#

I have created two MVC applications that share the same authentication. In the applications I'm using different user roles that can be assigned to every user. When I log in as an administrator, everything works fine, I log in to the first application and the same cookie is used to log in to the second application, no login prompts involved.
When I log in as a user with a different role assigned to them, the login screen pops up again after logging in to the first application and it doesn't go away, even if I log in there also.
The applications are both on the same IIS server. The machine key is configured correctly in IIS server (obviously, since it works if I log in as a user with the administrator role assigned) and here is the code in Startup.Auth.cs for both applications:
1st Application:
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
CookieName = "DefaultCookie",
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))
}
});
2nd Application:
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
CookieName = "DefaultCookie",
AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active,
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)),
OnApplyRedirect = ApplyRedirect
},
});
private static void ApplyRedirect(CookieApplyRedirectContext context)
{
Uri absoluteUri;
if (Uri.TryCreate(context.RedirectUri, UriKind.Absolute, out absoluteUri))
{
var path = PathString.FromUriComponent(absoluteUri);
Trace.WriteLine(path);
if (path == context.OwinContext.Request.PathBase + context.Options.LoginPath)
context.RedirectUri = "/Account/Login" +
new QueryString(
context.Options.ReturnUrlParameter,
context.Request.Uri.AbsoluteUri);
}
context.Response.Redirect(context.RedirectUri);
}
Does anyone know why this is happening and what I can do to fix it?

This is an authorization issue, not an authentication issue. If you can share the login at all, i.e. in the case of your admin user, then everything is fine on that front. However, the user's role must be authorized to access the controller/action or they will still be redirected to the login page, even though they are already authenticated. This is intended as an opportunity for them to re-authenticate with an account with the appropriate privileges, since the one they used apparently does not have access.
Long an short, you need to ensure that whatever controller(s)/action(s) you want the user to be able to access allow the role that is assigned to them.

Related

Login/logout issue for multiple IIS same applications under the same site

I have deployed same application as two sites[Production and Development] in IIS 8.0 with two port number. The problem is the follow:
Open the browser and login the first application[Production];
Open another browser tab and login the second application[Development];
The first application automatically logout.
Any idea of having both should be logged in and use?
My file Startup.Auth.cs:
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"),
SlidingExpiration = true,
CookieName="my-very-own-cookie-name",
//ExpireTimeSpan = TimeSpan.FromMinutes(2.0),
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.FromHours(applTime),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager)),
OnResponseSignIn = context =>
{
context.Properties.AllowRefresh = true;
context.Properties.ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(idleTime);
}
}
});
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

ASP.NET 5 MVC6 User.GetUserId() returns incorrect id

I have simple project in ASP.NET 5 with one registered user. I have tried to get id of current logged user by extension method GetUserId() from using System.Security.Claims namespace.
Unfortunately this method returns me not existing id and i don't know why.
Here is my simple code:
var currentUserId = User.GetUserId();
Method result:
Database:
More than likely you're getting an old auth ticket that is still valid OR your getting an authentication ticket for another site your running locally. I would clear the browser cache and cookies and run it again.
Also, Try changing the name of the cookie, by default it is set to .AspNet.Cookies which can cause issues if you're running multiple apps locally. This caught me up a while back.
The cookie name can be changed like this
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
{
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<UserManager, ApplicationUser>(
validateInterval: TimeSpan.FromMinutes(0),
regenerateIdentity: (manager, user) => manager.GenerateUserIdentityAsync(user))
},
CookieName = "myAuthCookie",
});
The MSDN documentation on it can be found here.

AuthenticationManager.GetExternalLoginInfoAsync() always null

ExternalLoginInfo loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
Why must this line always return null? It happens when the user tries to login using ANY provider. I know the FLOW is correct because actually it works locally, but when I deploy the website it always returns null.
From what I understand it's using an external cookie to track this and I can be sure it's not the browser because it works locally on the same browser.
This happens for ALL providers, even though I've double checked that all of them have the domain as "allowed" in each respective control panel. Like I said everything works locally.
I've tried restarting IIS as some answers suggested.
Also have these lines in Startup.Auth.cs with the cookie domian correctly set
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
CookieDomain = ".example.com",
...
});
//use a cookie to temporarily store information about a user logging in with a third party login provider
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
Make sure your (facebook, twitter etc.) provider settings are not overriden on deployment.
Also make sure that your callback url is correctly registered at the provider. I'm using LinkedIn which needs a full url to your callback, eg. https://domain.com/signin-linkedin
I have the following setup, which works without any problems:
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
CookieSecure = CookieSecureOption.SameAsRequest,
CookieName = "CustomCookieName",
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
{
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, User>(
validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentity: (manager, user) => Some.Custom.Identity.Helper.GenerateUserIdentityHelperAsync(user, manager)) // This helper method returns ClaimsIdentity for the user
}
});
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

WebForms authentication against Azure AD

I have a WebForms site that has been running on an internal server and authenticating users against our internal Active Directory. Due to some new features that we are implementing, this site needs to be moved to an external server and then authentication changed so that it authenticates users against our Office 365 accounts. To this end I have:
Created a new WebForms site (not using MVC)
Set up a new application in Azure.
Modified the Startup.Auth.cs as follows:
public void ConfigureAuth(IAppBuilder app)
{
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
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 = "MyApplicationGUID", Authority = "https://login.windows.net/MyDomain.com" });
When I go to the default page and click Log On, it takes me to the correct Login page and the button for OpenID is shown. If I click the button, I am taken to the Microsoft Login page where I am able to enter my credentials. However, at that point, I am redirected back to my site's login page where it is still asking for a username/password.
What I would like to have happen is to set the site up so that if a user is not authenticated, they are redirected directly to the Microsoft login page and upon successful login are redirected back to the page they requested originally. Failing this, I would be satisfied with getting the default login page working so that when I click OpenID I'm not redirected back to the login page.
I don't have time to learn MVC at this point and port the whole thing over so going that route is not an option at this time.
I don't know enough about this process, so if my question doesn't make sense or if you need more information, please let me know and I'll be glad to try and find what you need to assist me in this.
Maybe I'm missing something, but I don't see why you need the custom login page or the external signin cookie. A typical Startup.Auth for OIDC/AAD looks something like this:
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
ClientId = "AppGUID",
Authority = "https://login.windows.net/MyDomain.com",
// After authentication return user to the page they were trying
// to access before being redirected to the Azure AD signin page.
Notifications = new OpenIdConnectAuthenticationNotifications()
{
RedirectToIdentityProvider = (context) =>
{
string currentUrl = context.Request.Scheme + "://" + context.Request.Host + context.Request.Path;
context.ProtocolMessage.RedirectUri = currentUrl;
return Task.FromResult(0);
}
}
});
The cookie auth is just to keep from going to AAD for every single request. All the real work happens in the OpenIdConnectAuthentication.
Here's an example of WebForms, Azure AD, and OpenID Connect:
http://www.cloudidentity.com/blog/2014/07/24/protecting-an-asp-net-webforms-app-with-openid-connect-and-azure-ad/

How do I forcefully propagate role changes to users with ASP.NET Identity 2.0.1?

I've read this and while it explains how role changes will eventually propagate to the user cookie after some time interval, I still don't understand how I force an immediate change to user roles.
Do I really have to sign the user out when I change his roles as administrator? If so — how? If I use AuthenticationManager.SignOut(); then I sign off myself (admin), not the user, whose roles I want to change.
Currently I use await UserManager.UpdateSecurityStampAsync(user.Id); to generate a new security stamp, but it does not work. When I refresh a page in another browser while logged in as another user his claims (including security stamp) do not change.
If you want to enable immediate revocation of cookies, then every request must hit the database to validate the cookie. So the tradeoff between delay is with your database load. But you can always set the validationInterval to 0.
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))
}
});

Categories