OWIN Signin not working - owin

User.Identity.IsAuthenticated is always false. I've been googling for hours and I cannot get this to work. I have a set of claims and I'm creating the identity and signing in with it using OWIN, but for some reason, IsAuthenticated is always false.
Here is my web.config relevant portion:
<authentication mode="Forms">
<forms name="FormsAuth1" loginUrl="https://localhost/SecureAuth.ClaimsAdapter.WebApp/Oidc/Authenticate" timeout="5" requireSSL="false" domain="localhost" />
</authentication>
Here is Startup.Auth.cs
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ExternalCookie,
LoginPath = new PathString("/OIDC/Authenticate")
});
Here is my controller
var identity = new ClaimsIdentity(validatedToken.Claims, DefaultAuthenticationTypes.ExternalCookie);
//Sign in using the created identity
HttpContext.GetOwinContext().Authentication.SignIn(identity);
//redirect to Pass the cookie to the client app
return RedirectToAction("Confirm");
In the "Confirm" action, the "User.Identity.IsAuthenticated" is still set to false.

You have to set your CookieAuthenticationMiddleware.AuthenticationType to the same type as your DefaultSignInAsAuthenticationType.
This should work
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
//Change this to CookieAuthenticationDefaults.AuthenticationType
AuthenticationType = CookieAuthenticationDefaults.AuthenticationType,
LoginPath = new PathString("/OIDC/Authenticate")
});
//Change this to CookieAuthenticationDefaults.AuthenticationType
var identity = new ClaimsIdentity(validatedToken.Claims, CookieAuthenticationDefaults.AuthenticationType);
//Sign in using the created identity
HttpContext.GetOwinContext().Authentication.SignIn(identity);
//redirect to Pass the cookie to the client app
return RedirectToAction("Confirm");

Apparently, I wasn't calling the
ConfigureAuth(IappBuilder app) ....
Proceed to slap self...

Related

Logout Redirection to login page in MVC5

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.

Not able to solve Infinite Loop Issue after Azure AD Authentication using OpenIDConnect - Authorization Code grant

We are implementing Azure AD Authentication in ASP.NET MVC 5 using Open ID Connect. When the application was running on premise we had windows Authentication, so there is no login page or Login button.
We have put [Authorize] attribute to all the controllers so that the user is authenticated before accessing the page. Below is the code in start up Auth.
app.UseKentorOwinCookieSaver();
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = "Cookies",
CookieManager = new Microsoft.Owin.Host.SystemWeb.SystemWebChunkingCookieManager()
});
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
ClientId = clientId,
Authority = authority,
PostLogoutRedirectUri = postLogoutRedirectUri,
RedirectUri = RedirectUri,
ResponseType = OpenIdConnectResponseType.Code,
Notifications = new OpenIdConnectAuthenticationNotifications()
{
AuthenticationFailed = (context) => {
context.HandleResponse();
return Task.FromResult(0);
}
}
});
But we are facing the Infinite loop once the user is authenticated. And I tried all the solutions on internet, but my issue is not solved.
https://stackoverflow.com/a/37666371/55775
https://github.com/Sustainsys/owin-cookie-saver
https://github.com/aspnet/AspNetKatana/wiki/System.Web-response-cookie-integration-issues
ASP.NET_SessionId + OWIN Cookies do not send to browser
asp.net mvc azure AAD authentication infinite loop

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

Resources