Accessing user details using Active Directory in an ASP.NET Core MVC app with Windows authentication - active-directory

I was trying to access user information like first name, last name of the user in my ASP.NET Core MVC project with Windows authentication. I actually make it work after searching for a solution on the web but I am quite new to this stuff and beginner level programmer so not understanding what is happening in the part that I just copy paste in my project.
I couldn't find any explanation in that website as well. I would be really happy if someone can explain this to me. Many thanks in advance.
The website reference for this code: https://sensibledev.com/how-to-get-user-details-from-active-directory/
Home controller:
var username = User.Identity.Name;
using (var context = new PrincipalContext(ContextType.Domain, "yourdomain"))
{
var user = UserPrincipal.FindByIdentity(context, username);
if (user != null)
{
ViewData["UserName"] = user.Name;
ViewData["EmailAddress"] = user.EmailAddress;
ViewData["FullName"] = user.DisplayName;
ViewData["GivenName"] = user.GivenName;
}
}

That code takes the username of the user who logged into your website and looks it up on your domain to find more information about the person.
var username = User.Identity.Name;
The User property is ControllerBase.User, which refers to the user currently logged into your website. Since you're using Windows Authentication, this will refer to an Active Directory user. User.Identity.Name gets just the username.
The rest is for looking up the account in Active Directory.
new PrincipalContext(ContextType.Domain, "yourdomain")
This means "I want to talk to a domain called yourdomain".
UserPrincipal.FindByIdentity(context, username)
UserPrincipal.FindByIdentity finds an account on the domain. So this is saying "find this username on the domain".
Then the users details from the account are put into the ViewData collection so that the data is accessible in the view. More details on that here.

From your website's perspective, all Windows code runs under some Windows account.
If you use IIS and Forms authentication for example, then Windows knows nothing about you - you are likely to be running under an anonymous account name which all users will run under. If you drill down through your running code, it is possible to find different Windows accounts at different code levels, such as in your top level code, the underlying IIS thread, etc.
You are trying to use Windows accounts for your web site but you have to ensure that the web server it is running on is also using Windows Authentication - I know you checked this option when creating your site.
Your user identity can be cast to various types because it has to work seamlessly whichever authentication methodology is in use. You can also check your user to see if it is of a particular security regime.
Have a look at https://learn.microsoft.com/en-us/aspnet/core/security/authentication/windowsauth?view=aspnetcore-3.1&tabs=visual-studio

You get the security principle information using
var context = new PrincipalContext(ContextType.Domain, "yourdomain")
PrincipleContext is the class that has the information once you create a new instance of it, passing in parameters for the type of domain (an enumeration) and the name of your domain (a string).
The USING block ensures that the instance is disposed once the block completes - otherwise you have to call DISPOSE on that instance yourself (remember if there is an exception you might not have captured this so you will at least have to manage this scenario.
Once you have an instance of of your domain context you can use it to search (in the case of Windows, the LDAP database) for users, whether by SID or unique name, in your case (every name must be unique - two users in the domain cannot have the same name).
The website has the security ID of the user, the code you are following gets a Domain object for that user which has the properties you will display. You could call other objects that might tell you which Windows Security Groups the user is a member off. In that way you can have a web site where a users ability to view a web page or click a button is down to which Groups in the Domain the user is a member of.

Related

Use existing user accounts of an existing website

I have a website named satellite.com built by AngularJS+NodeJS+MongoDB, it has an authentication system by ID & password, or third-parties like Google, GitHub. It already has many user accounts.
Now, I want to build a new website named umbrella.com, its authentication system and its database by ReactJS+NodeJS+MongoDB. Umbrella.com will include the functionalities of satellite.com (which will ideally share code with satellite.com) and some other functionalities. In the future, I want both satellite.com and umbrella.com to exist and work (though satellite.com may systematically redirect to umbrella.com/satellite/).
I wonder how umbrella.com can use the existing user accounts of satellite.com. Ideally, I hope
existing users of satellite.com could sign in umbrella.com with their old credentials, and have access to their data of satellite.com
new users could sign up on satellite.com, which will be valid to umbrella.com too
new users could sign up on umbrella.com, which will be valid to satellite.com too
I have total control of the two websites. Does anyone have a clear suggestion on how to structure and share the authentication system and the database of these 2 websites?
Edit 1: one issue is that when I set up Google Authentication for satellite.com, I remember that the domain name (i.e., satellite.com) was required. So now, can we use these authentications for another domain name (i.e., umbrella.com)?
If you are not using third party authentication like Google Auth or something where you have to specifically register your domain you can achieve that by following steps:
You can keep one database structure for both website with different
front-end. For that you user can login to both websites using same
credentials.
You can also go with one backend (Node server) for both the websites
as its seems like both are same and having same functionality.
Front-end can be different.

How can an ASP.NET website authorize using Active Directory Groups without login prompts?

I want to build an intranet website that doesn't login-prompt a user that is already logged in to the AD (on a company computer in the same domain as the IIS server). So far, all my attempts have resulted in a basic login prompt or not being able to read HttpContext.User.Identity.Name. The User object would then be used to check if that user is a member of a certain Active Directory group in the domain.
I've seen different solutions that require the user to add a Trusted site in the browser or registry edits. That is not what the product owner would like. Would it be possible to create a completely automatic experience (the user would have had to log in to their computer anyway)?
MyAuthorizeAttribute
The code below is found inside my custom AuthorizeAttribute that is put on the index method of my home controller. This shouldn't matter though, because it works once there is a User object and the controller is called. Users that are members of the group will continue to the start page, others wont.
PrincipalContext context = new PrincipalContext(ContextType.Domain, "<domain name>");
UserPrincipal userPrincipal = UserPrincipal.FindByIdentity(context, httpContext.User.Identity.Name);
if (userPrincipal != null)
{
if (userPrincipal.IsMemberOf(context, IdentityType.SamAccountName, "<group name>"))
{
// The user belongs to the group
return true;
}
}
// The user is not a member of the group, handle the unauthorized request
return false;
Web.config
<authentication mode="Windows" />
<authorization>
<allow users="*" />
</authorization>
IIS
Site:
Authentication: only Windows enabled (I've tried with anonymous but I can't retrieve any User info)
edit: Provider: NTLM
Application Pool:
.NET 4.0.30319
Integrated
Identity: Network Service (I've tried app pool as well, but one solution suggested network service)
For what it's worth, within the context of Windows Auth, the user's roles are equivalent to their AD group memberships. As a result, you can simply use the standard AuthorizeAttribute and remove your custom one entirely.
[Authorize(Roles = "<domain>\<group>")]
There's not enough to work with here to tell you what the actual problem you're having is, but removing custom stuff you added, which is always prone to failure, is a good first step in reducing the variables.

apex how to login to another application from link in one application?

I have two applications in my workspace, APP 1 and APP 2.
In my case, user will log in to APP 1. from there, i put a menu(or a link) to APP 2. however APP 2 requires authentication. So it will take me to a login page. i would like to eliminate that and get the current user's credentials on APP 1 and login to APP 2.
i'm looking for a simple straightforward method (but need to consider security) to login to APP 2.
what i could think of is apex_collection..i could store credentials n use it to create a login process for APP 2. however apex_collection is session based. eventhough i've set session for APP 2, it still wont read values from my apex_collection.
Does anyone have a suggestion or a solution?
All you need to do is use the same authentication scheme in both applications and set the cookie name attribute to the same value in both authentication schemes like this:
APEX will then use the same session across the two applications and the user will not have to log in again when they navigate from one to the other, provided of course that you pass the SESSION_ID in the URL.
A Few Comments on Default APEX Workspace Authentication Security
It may also be helpful to expand on an explanation of why the solution posted by #TonyAndrews works.
For any Apex Apps within the same workspace, if they use the default "APEX Application Authentication" method, they will consult the same authentication user list... so USER1 and its password is a valid login for any of the "neighboring" applications...
This may be a concern if you are hosting different clients or users that should not be intermingling with the other applications. You can also define user GROUPS in the same place as you set up each workspace user. Each application can have its own security filter that permits access by membership of BOTH user/password authentication AND membership in the appropriate access group.
Sharing workspaces may also be a problem because of the unique user name restriction of a single workspace. You can get around that by:
Defining different name-spaces for each application:
Email addresses are good: "someuser#sampledomain.com"
An app id prefix such as: SHOP_EDNA, SHOP_GARRETT, TC_KAREN, TC_MARLOWE, MY_BORIS etc.
Different name styles: first name only, first name + last initial, etc.
To keep things simple, you can always just spin up a brand new workspace: a warning however is that common user names like `ADMIN` are NOT the same between separate workspaces. There shouldn't be much concern however because apps or workspace users may have the same or different schema access privileges to the database back end.
A Word of Caution to Administrators and Developers:
When you go live with an application or multiple applications on a user-facing system, keep in mind the deployment destination (i.e., the workspace) and what else is sharing that workspace. There are some real situations where apps are not intended to be shared or accessed by other "inside" users. Be sure to read up and understand the security constraints and methods of using Default Apex Authentication security so that it's more than luck that protects your own production/live deployed applications.
I do have the similar requirement, linking from one application page to another.
Tried the above mentioned solution, but still asking to login to second application. My Apex ver is 5.0.3 and trying in same workspace.
Created new authentication schemes for each app with same cookie name and set them as current authentication. Scheme type are Application express accounts.
Setting the link as below from first app page to second.
href="http://servername:port/apex/f?p=224:2:&APP_SESSION"
Could anyone provide a solution, please?
Just an update on this.
I am currently using v21.2 and this is how I do it:
In both applications, go to Shared Components > Authentication Schemes > (Select your Auth Scheme);
Scroll down to Session Sharing and select 'Workspace Sharing';
In one of the applications (source), create a link (as a Navigation Bar List entry, for example) like f?p=173:1:&SESSION., where 173 is the target application ID and 1 is the target page.
After some research, I've found out that this feature (Session Sharing Type) is available since v18 of APEX.

User.IsInRole("fake group") results in "The trust relationship between the primary domain and the trusted domain failed"

I have an MVC 3 app, using Windows Authentication with Claims using WIF 4.5.
Access to the application is controlled (currently) via membership in an AD group:
<deny users="?" />
<allow roles="domain\somegroup" />
<deny users="*" />
In addition to the AD groups, we have custom roles that need to be added. (This app is being converted from Forms to Windows authentication)
To support these custom roles (until they are managed in AD), we are adding them as ClaimTypes.GroupSid claims to the user, so that existing code utilizing [Authorize("ADMIN")] and User.IsInRole("ADMIN") continues to function:
Application_PostAuthenticateRequest(object sender, EventArgs e)
{
var identity = ClaimsPrincipal.Current.Identity as WindowsIdentity;
var roles = userDAL.GetRoles(identity.Name);
foreach(var role in roles)
{
identity.AddClaim(new Claim(ClaimTypes.GroupSid, role));
}
}
And this is all working as expected.
Except when the current user is NOT a member of some custom role (like ADMIN) and that role also doesn't exist in AD
We use [Authorize("ADMIN")] on Controller Action Methods, as well as various instances of User.IsInRole("ADMIN") depending in the scenario. It's in those instances where the error occurs and the app blows up.
The AD infrastructure is in the midst of an upgrade/migration. I'm not privy to all the details there, but I do know there are a handful of domains, supposedly with trust between them, and it's been alluded to me by the infrastructure folks that these trust relationships are up and running.
So really I guess I'm wondering 2 things:
This really doesn't seem like something our code should have to handle. So what could really be wrong with the domain? Can I find out what 'trusted' domain the trust relationship is failing for?
What is the best way to work around this? I dislike the idea of writing helper methods & Authorize() subclasses just to trap this exception.
Please go to inetmgr, sites, default web site, site name, iis group, double-click authentication, disable anonymous authentication, then reset the app pool.
This appears to happen when windows cannot decipher the roles defined under the 'authorization, allow roles' tag in the web.config file. For testing comment out the custom roles tags from the web.config file. The issue appears to be caused when mixing up Forms authentication and Windows authentication. The magic happens in the Global.asax file Application_PostAuthenticateRequest method, when using Forms authentication you can Cast the User.Identity as FormsIdentity, then create the custom identity from the FormsIdentity Ticket, then create the custom principle from the custom identity, you will then be able to attach the CustomPrincipal to the Current User and Current Principal, ie.
Dim fIdent As FormsIdentity = CType(User.Identity, FormsIdentity)
Dim ci As New CustomIdentity(fIdent.Ticket)
Dim cp As New CustomPrincipal(ci)
HttpContext.Current.User = cp : Thread.CurrentPrincipal = cp
For IIS you want to enable Forms authentication and anonymous authentication, everything else should be disabled. When using Windows authentication the Global.asax file Application_PostAuthenticateRequest method can create the custom principle directly from the User.Identity ie.
Dim cp As New CustomPrincipal(User.Identity)
HttpContext.Current.User = cp : Thread.CurrentPrincipal = cp
In this case the IIS settings should be Windows authentication and ASP.Net Impersonation is enabled and everything else is disabled.
Getting these authentication methods mixed up results in the 'The trust relationship between the primary domain and the trusted domain failed' error because if your Application_PostAuthenticateRequest method is not implementing the CustomPrinciple for some reason then windows will try to use the built in IsInRole function that checks the role against the domain roles instead of using your custom IsInRole that is in your CustomPrinciple code behind file.
Here is a useful article and links:
http://www.codeproject.com/Articles/8819/Authorize-and-authenticate-users-with-AD
https://msdn.microsoft.com/en-us/library/ff647405.aspx
https://support.microsoft.com/en-us/kb/306359
This happens if you have a trusted domain configuration that is not available, IsInRole searches the group in the trusted doamins as well, and if the trusted domain is not available, throws the Trust exemption.

Windows Live ID giving back different User Token for the same User on different Apps?

Windows Live ID seems to be giving back a different User Token for the same User on different Apps.
Heres the scoop.
Windows Live ID is supposed (i think) to give me Unique User Token.
I want to use this to identify the user.
My App is 2 parts ... 1 = ASP.NET webapp...2 is WPF.
(Same DB / User Table)
Problem:
When user logs in to ASP.Net - I get UserToken = 00202009399.
When user logs in to WPF - I get UserToken = 00829909233.
Question:
Is this a glich? If so - what is a
work around?
(If this is planned behaviour - I can only think MS wants to separate User Tokens per Application or Domain)
Is there a setting to Tell LiveID
that these 2 differnt Apps (WPf &
ASP.Net ) are from same
Orginization/Owner/Azure Account?
I know this answer is late in the game. Windows Live ID provides you with a unique, site-specific identifier for each Windows Live user who signs in to your site. It is designed that way to allow user confidentiality and security from one site to the next.
Is there a setting to Tell LiveID that these 2 differnt Apps (WPf & ASP.Net ) are from same Orginization/Owner/Azure Account?
If you want the to have the same identifier you will have to use the same App Id. If you are wanting to maintain the part of the application you are signing in from you can use the context Parameter to set the path to return too the only requirment is that they have to be in the same Domain you set when registering your application.

Resources