I am using Windows Identity foundation to manage login to our site.
When a user logs in i am using some information in his request to put into the claims.
It is all working fine, but now I need to manage this scenario:
user is already logged in, athenticated and has a valid token.
But user decides to browses in again (via a redirect from another site)
So his information in his request is different.
I want to either
Sign him out - so that he naturally creates a new token with his new information
OR update his existing token.
So my question is:
How do i Sign out of Windows Identity foundation?
Or How do I update the existing claims?
I have tried this code:
public void ExpireClaims(HttpContextBase httpContextBase)
{
var module =
httpContextBase.ApplicationInstance.Modules["WSFederationAuthenticationModule"] as
WSFederationAuthenticationModule;
if (module == null)
{
return;
}
module.SignOut(true);
}
But module is alway null.
and i tried this:
public void FederatedSignOut(string replyUrl)
{
WSFederationAuthenticationModule.FederatedSignOut(null, new Uri(replyUrl));
}
But i get a null reference execption when i do this.
Thanks very much.
Essentially sign-out is just deleting the cookie so:
FormsAuthentication.SignOut
or
FederatedAuthentication.SessionAuthenticationModule.SignOut
or
FederatedAuthentication.SessionAuthenticationModule.DeleteSessionTokenCookie
will work.
Or use the FederatedPassiveSignInStatus (should be in your Toolbox). Set the property SignOutAction to FederatedSignOut and the control will clear out your STS session as well.
Related
I want to add a new feature to my WebApp for events - build with .Net MVC - to send a magic link to each participant - after they register in the event - to access the WebApp and be able to participate in a Gamification challenge.
I am using Microsoft Owin for the backoffice access, and I would like to use it to create the magic link, but I cant find any solution for that.
I have searched a token login solution but no success.
Is it ASP.NET or ASP.NET Core application? It shouldn't matter if you're using OWIN or not. In a ASP.NET project I have used MachineKey's Protect and Unprotect methods. Set a static machine key using machineKey element in the web.config, because it keeps being regenerated by default. If it's a load-balancing environment, set identical machine key on each node.
For example, let's say you have some key identifying the participant, most likely the email address. Include ?user=key&token=token in the link. To generate the token
var unprotected = Encoding.UTF8.GetBytes(key);
var protected = MachineKey.Protect(unprotected);
var token = HttpServerUtility.UrlTokenEncode(protected);
To validate the token, when the user accesses the application:
bool Validate(string token, string expectedKey)
{
var protected = HttpServerUtility.UrlTokenDecode(token);
try
{
var unprotected = MachineKey.Unprotect(protected);
var key = Encoding.UTF8.GetString(unprotected);
return key == expectedKey;
}
catch (CryptographicException)
{
return false;
}
}
The MachineKey's successor in ASP.NET Core is Data Protection.
I have a sharepoint site which has different authentication options available for users to login like Windows, Trusted SAML etc
How can i determine which is the authentication mode of the current request?
I have tried the "SPSecurity.AuthenticationMode" but its value is always forms.
You would need to get it via SPOriginalIssuerType Property
var localClaimManager = SPClaimProviderManager.Local;
if (localClaimManager != null)
{
var issuerType=SPOriginalIssuers.GetIssuerType(localClaimManager.DecodeClaim(SPContext.Current.Web.CurrentUser.LoginName).OriginalIssuer);
//Write your logic based on the issuerType received
//https://learn.microsoft.com/en-us/dotnet/api/microsoft.sharepoint.administration.claims.sporiginalissuertype?view=sharepoint-server
}
I created an asp.net webform application using ADFS. Sign in and sign out work perfectly using the default method that comes with the template.
Eg of signout button method that is included in the template
protected void Unnamed_LoggingOut(object sender, LoginCancelEventArgs e)
{
// Redirect to ~/Account/SignOut after signing out.
string callbackUrl = Request.Url.GetLeftPart(UriPartial.Authority) + Response.ApplyAppPathModifier("~/Account/SignOut");
HttpContext.Current.GetOwinContext().Authentication.SignOut(
new AuthenticationProperties { RedirectUri = callbackUrl },
WsFederationAuthenticationDefaults.AuthenticationType,
CookieAuthenticationDefaults.AuthenticationType);
}
I have set up a timer and upon reaching zero I tried using the above code to log the user out but it doesn't work.No error thrown.
Any suggestion how to perform logout here?
What worked for me is to upon timeout to call the click event of a hidden button which in turn causes the below code to run.
// Redirect to ~/Account/SignOut after signing out.
string callbackUrl = Request.Url.GetLeftPart(UriPartial.Authority) + Response.ApplyAppPathModifier("~/Account/SignOut");
HttpContext.Current.GetOwinContext().Authentication.SignOut(
new AuthenticationProperties { RedirectUri = callbackUrl },
WsFederationAuthenticationDefaults.AuthenticationType,
CookieAuthenticationDefaults.AuthenticationType);
ADFS is the server that is responsible for authenticating the user and for managing the user session. The website/form is just using this service. It makes sense that a site that uses this service cannot have full control over it. It would make more sense to me to log out the user from the ADFS server and have that server do the heavy lifting for you.
Note the ADFS server keeps a user logged in into ADFS server, and note that when a user requests access to a resource this manifests in an access_token. They are different things. Typically when signing somebody out with a product like identity server, in order to log out you’ll need to do two things:
Revoke the access token
Log out on the authentication server, (if
that is desired, one could argue that isn’t desirable)
Note the explicit difference between session and token. You’ll notice these concepts are also in ADFS. After a quick google search you’ll find the difference between WebSSOLifetime and TokenLifetime. I would suggest configuring those to invalidate the tokens and sessions, and thereby logging the user out after an x amount of minutes.
Hope this helps.
Have you tried the above code that you have posted directly without the timer? and did it work?
Also, Try implementing the below code and see if it works.
public void LogOut()
{
var module = FederatedAuthentication.WSFederationAuthenticationModule;
module.SignOut(false);
var request = new SignOutRequestMessage(new Uri(module.Issuer), module.Realm);
Response.Redirect(request.WriteQueryString());
}
I have an MVC site that allows logging in using both Forms login and Windows Authentication. I use a custom MembershipProvider that authenticated the users against Active Directory, the System.Web.Helpers AntiForgery class for CSRF protection, and Owin cookie authentication middle-ware.
During login, once a user has passed authentication against Active Directory, I do the following:
IAuthenticationManager authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
authenticationManager.SignOut(StringConstants.ApplicationCookie);
var identity = new ClaimsIdentity(StringConstants.ApplicationCookie,
ClaimsIdentity.DefaultNameClaimType,
ClaimsIdentity.DefaultRoleClaimType);
if(HttpContext.Current.User.Identity is WindowsIdentity)
{
identity.AddClaims(((WindowsIdentity)HttpContext.Current.User.Identity).Claims);
}
else
{
identity.AddClaim(new Claim(ClaimTypes.Name, userData.Name));
}
identity.AddClaim(new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "Active Directory"));
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, userData.userGuid));
authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = false }, identity);
My SignOut function looks like this:
IAuthenticationManager authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
authenticationManager.SignOut(StringConstants.ApplicationCookie);
Logging in is performed via a jQuery.ajax request. On success, the Window.location is updated to the site's main page.
Logging in with both Forms and IntegratedWindowsAuthentication (IWA) works, but I've run into a problem when logging in with IWA. This is what happens:
The user selects IWA on the login page and hits the submit button. This is sent to the regular login action via an ajax request.
The site receives the request, sees the "use IWA" option and redirects to the relevant action. 302 response is sent.
The browser automatically handles the 302 response and calls the redirect target.
A filter sees that the request is headed to the IWA login action and that User.Identity.IsAuthenticated == false. 401 response is sent.
The browser automatically handles the 401 response. If the user has not authenticated using IWA in the browser yet, they get a popup to do so (default browser behavior). Once credentials have been received, the browser performs the same request with user credentials.
The site receives the authenticated request and impersonates the user to perform a check against Active Directory. If the user passes authentication, we finalize SignIn using the code above.
User is forwarded to the site's main page.
The site receives the request to load the main page. This is where things sometimes go awry.
The User.Identity at this point is of type WindowsIdentity with AuthenticationType set to Negotiate, and NOT as I would expect, the ClaimsIdentity created in the SignIn method above.
The site prepares the main page for the user by calling #AntiForgery.GetHtml() in the view. This is done to create a new AntiForgery token with the logged in user's details. The token is created with the WindowsIdentity
As the main page loads, ajax requests made to the server arrive with ClaimsIdentity! The first POST request to arrive therefore inevitably causes an AntiForgeryException where the anti-forgery token it sent is "for a different user".
Refreshing the page causes the main page to load with ClaimsIdentity and allows POST requests to function.
Second, related, problem: At any point after the refresh, once things are supposedly working properly, a POST request may arrive with WindowsIdentity and not with ClaimsIdentity, once again throwing an AntiForgeryException.
It is not any specific post request,
it is not after any specific amount of time (may be the first/second request, may be the hundredth),
it is not necessarily the first time that specific post request got called during that session.
I feel like I'm either missing something regarding the User.Identity or that I did something wrong in the log-in process... Any ideas?
Note: Setting AntiForgeryConfig.SuppressIdentityHeuristicChecks = true; allows the AntiForgery.Validate action to succeed whether WindowsIdentity or ClaimsIdentity are received, but as is stated on MSDN:
Use caution when setting this value. Using it improperly can open
security vulnerabilities in the application.
With no more explanation than that, I don't know what security vulnerabilities are actually being opened here, and am therefore loathe to use this as a solution.
Turns out the problem was the ClaimsPrincipal support multiple identities. If you are in a situation where you have multiple identities, it chooses one on its own. I don't know what determines the order of the identities in the IEnumerable but whatever it is, it apparently does necessarily result in a constant order over the life-cycle of a user's session.
As mentioned in the asp.net/Security git's Issues section, NTLM and cookie authentication #1467:
Identities contains both, the windows identity and the cookie identity.
and
It looks like with ClaimsPrincipals you can set a static Func<IEnumerable<ClaimsIdentity>, ClaimsIdentity> called PrimaryIdentitySelector which you can use in order to select the primary identity to work with.
To do this, create a static method with the signature:
static ClaimsIdentity MyPrimaryIdentitySelectorFunc(IEnumerable<ClaimsIdentity> identities)
This method will be used to go over the list of ClaimsIdentitys and select the one that you prefer.
Then, in your Global.asax.cs set this method as the PrimaryIdentitySelector, like so:
System.Security.Claims.ClaimsPrincipal.PrimaryIdentitySelector = MyPrimaryIdentitySelectorFunc;
My PrimaryIdentitySelector method ended up looking like this:
public static ClaimsIdentity PrimaryIdentitySelector(IEnumerable<ClaimsIdentity> identities)
{
//check for null (the default PIS also does this)
if (identities == null) throw new ArgumentNullException(nameof(identities));
//if there is only one, there is no need to check further
if (identities.Count() == 1) return identities.First();
//Prefer my cookie identity. I can recognize it by the IdentityProvider
//claim. This doesn't need to be a unique value, simply one that I know
//belongs to the cookie identity I created. AntiForgery will use this
//identity in the anti-CSRF check.
var primaryIdentity = identities.FirstOrDefault(identity => {
return identity.Claims.FirstOrDefault(c => {
return c.Type.Equals(StringConstants.ClaimTypes_IdentityProvider, StringComparison.Ordinal) &&
c.Value == StringConstants.Claim_IdentityProvider;
}) != null;
});
//if none found, default to the first identity
if (primaryIdentity == null) return identities.First();
return primaryIdentity;
}
[Edit]
Now, this turned out to not be enough, as the PrimaryIdentitySelector doesn't seem to run when there is only one Identity in the Identities list. This caused problems in the login page where sometimes the browser would pass a WindowsIdentity when loading the page but not pass it on the login request {exasperated sigh}. To solve this I ended up creating a ClaimsIdentity for the login page, then manually overwriting the the thread's Principal, as described in this SO question.
This creates a problem with Windows Authentication as OnAuthenticate will not send a 401 to request Windows Identity. To solve this you must sign out the Login identity. If the login fails, make sure to recreate the Login user. (You may also need to recreate a CSRF token)
I'm not sure if this will help, but this is how I've fixed this problem for me.
When I added Windows Authentication, it fluctuated between Windows and Claims identities. What I noticed is that GET requests get ClaimsIdentity but POST requests gets WindowsIdentity. It was very frustrating, and I've decided to debug and put a breakpoint to DefaultHttpContext.set_User. IISMiddleware was setting the User property, then I've noticed that it has an AutomaticAuthentication, default is true, that sets the User property. I changed that to false, so HttpContext.User became ClaimsPrincipal all the time, hurray.
Now my problem become how I can use Windows Authentication. Luckily, even if I set AutomaticAuthentication to false, IISMiddleware updates HttpContext.Features with the WindowsPrincipal, so var windowsUser = HttpContext.Features.Get<WindowsPrincipal>(); returns the Windows User on my SSO page.
Everything is working fine, and without a hitch, there are no fluctuations, no nothing. Forms base and Windows Authentication works together.
services.Configure<IISOptions>(opts =>
{
opts.AutomaticAuthentication = false;
});
This is not necessarily an issue, I am just curious as to how it works. I have a method:
public static bool UserIsAuthenticated()
{
bool isAuthed = false;
try
{
if (HttpContext.Current.User.Identity.Name != null)
{
if (HttpContext.Current.User.Identity.Name.Length != 0)
{
FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;
FormsAuthenticationTicket ticket = id.Ticket;
isAuthed = true;
string MyUserData = ticket.UserData;
}
}
}
catch { } // not authed
return isAuthed;
}
The HttpContext.Current.User.Identity.Name returns null if the user does not exist, but how does it know which usernames exist or do not exist?
For windows authentication
select your project.
Press F4
Disable "Anonymous Authentication" and enable "Windows Authentication"
The HttpContext.Current.User.Identity.Name returns null
This depends on whether the authentication mode is set to Forms or Windows in your web.config file.
For example, if I write the authentication like this:
<authentication mode="Forms"/>
Then because the authentication mode="Forms", I will get null for the username. But if I change the authentication mode to Windows like this:
<authentication mode="Windows"/>
I can run the application again and check for the username, and I will get the username successfully.
For more information, see System.Web.HttpContext.Current.User.Identity.Name Vs System.Environment.UserName in ASP.NET.
How does [HttpContext.Current.User] know which usernames exist or do
not exist?
Let's look at an example of one way this works. Suppose you are using Forms Authentication and the "OnAuthenticate" event fires. This event occurs "when the application authenticates the current request"
(Reference Source).
Up until this point, the application has no idea who you are.
Since you are using Forms Authentication, it first checks by parsing the authentication cookie (usually .ASPAUTH) via a call to ExtractTicketFromCookie. This calls FormsAuthentication.Decrypt (This method is public; you can call this yourself!). Next, it calls Context.SetPrincipalNoDemand, turning the cookie into a user and stuffing it into Context.User (Reference Source).
Assume a network environment where a "user" (aka you) has to logon. Usually this is a User ID (UID) and a Password (PW). OK then, what is your Identity, or who are you? You are the UID, and this gleans that "name" from your logon session. Simple! It should also work in an internet application that needs you to login, like Best Buy and others.
This will pull my UID, or "Name", from my session when I open the default page of the web application I need to use. Now, in my instance, I am part of a Domain, so I can use initial Windows authentication, and it needs to verify who I am, thus the 2nd part of the code. As for Forms Authentication, it would rely on the ticket (aka cookie most likely) sent to your workstation/computer. And the code would look like:
string id = HttpContext.Current.User.Identity.Name;
// Strip the domain off of the result
id = id.Substring(id.LastIndexOf(#"\", StringComparison.InvariantCulture) + 1);
Now it has my business name (aka UID) and can display it on the screen.
Also check that
<modules>
<remove name="FormsAuthentication"/>
</modules>
If you found anything like this just remove:
<remove name="FormsAuthentication"/>
Line from web.config and here you go it will work fine I have tested it.
Actually it doesn't! It just holds the username of the user that is currently logged in. After login successful authentication, the username is automatically stored by login authentication system to "HttpContext.Current.User.Identity.Name" property.
To check if the current user is authenticated, you MUST (for security reasons) check "HttpContext.Current.User.Identity.IsAuthenticated" boolean property that automatically holds this information instead of writing your own code.
If the current user is NOT authenticated, "HttpContext.Current.User.Identity.Name" property will be null or an empty string or "can take other values" (https://learn.microsoft.com/en-us/dotnet/api/system.security.principal.iidentity.name?view=netframework-4.8) obviously depending on the authentication mode used.
See: https://learn.microsoft.com/en-us/dotnet/api/system.security.principal.iidentity?view=netframework-4.8
Windows authentication gives the information about the user who is logged in. Here is how to set the windows authentication in your project:
you can select project from the menu bar, select yourProject Properties, select Debug, and check the "Enable Windows Authentication" as the image below,
then you will be able to know the user who is logged in by running this code in any controller
var strUserName = User;