Accessing user info from a one way trust - c#

I have two domains, MINE and THEIRS. MINE is my local domain and has a one way trust with THEIRS (using LDAPS port 636), so that MINE trusts THEIRS but THEIRS does not trust MINE. I can add users from THEIRS to groups in MINE, and have users from THEIR log into machines and applications on the MINE network. The trust appears to be working properly.
I am writing a little .Net application (not ASP.Net) to test connectivity over the WAN. We have one app that isn't seeing users from THEIRS in groups in MINE. Other apps, like SharePoint, work fine.
I tried using ASP.Net 4 option with System.DirectoryServices.AccountManagement objects, like PrincipalContext, UserPrincipal, GroupPrincipal, etc. Quick code snippet
PrincipalContext domainContext = GetDomainContext(DomainName, ConnectionPort,
UseSpecifiedCredentials, Credentials);
GroupPrincipal theGroup = GroupPrincipal.FindByIdentity(domainContext,
IdentityType.SamAccountName, GroupName);
PrincipalCollection theUsers = theGroup.Members;
var users = from u in theUsers
select u.Name;
return users.ToArray();
It all works GREAT when I connect directly to MINE. The issue comes in with connecting to THEIRS. Either the 1 way trust of the LDAPS traffic is returning the error:
System.DirectoryServices.Protocols.LdapException: The LDAP server is unavailable.
So I switch to .Net 2 variations using DirectoryEntry, DirectorySearcher, etc. This actually works against THEIRS domain.
List<string> userNames = new List<string>();
string searchString = string.Format("(sAMAccountName={0})", GroupName);
SearchResult result = SearchAD(DomainName, ConnectionPort, searchString);
I can connect directly to the THEIRS domain, using some impersonation in the code.
When I query the groups in MINE, I get back the SID for the users from THEIRS, not a user account.
The following users are a member of testGroup:
CN=S-1-5-21-....,CN=ForeignSecurityPrincipals,DC=MINE,DC=local
CN=S-1-5-21-....,CN=ForeignSecurityPrincipals,DC=MINE,DC=local
I tried the impersonation on this as well, running it as a user from THEIRS but no luck.
How can I get user info from THEIRS when the user is in MINE? Do I have to take the above CN/SID and query THEIRS domain? What am I missing in the .Net 4 stuff?

I assume you have your ASP.NET machine running in MINE.
Your System.DirectoryServices.AccountManagement approach should just work if you make sure you use a domain user account from THEIR domain to run the application. In normal one-way trust configuration (unless you are doing selective authentication trust), the domain user account from THEIR should have permissions to read from both MINE and THEIR.
To make sure you use a domain user from THEIR domain, you can simply set the AppPool identity. Of course, you can use impersonation to do it too.

Related

C# Give Permissions to Everyone in Active Directory

We want to give permissions (in .Net Application) to everyone in AD but could not find the group that contains everyone. Tried with “NT Authority\Authenticated Users” but getting "user not found". Please provide any pointers to achieve this functionality.Below is sample code snippet.
DirectorySearcher user = new DirectorySearcher(connString);
user.Filter = String.Format("(sAMAccountName={0})", alias);
var result = user.FindOne();
Note: we can give permissions to all the users in SharePoint using “All Authenticated Users” but the same option is not working in .Net Application.
Regards,
Parveen
In a domain, everyone means all the Domain users, so in order to give permission to all domain users you need to use this: DOMAIN\Domain Users

Why might UserPrincipal.GetAuthorizationGroups() fail for one principal but not another?

I am running the following code in an ASP.Net MVC website:
using (var ctx = new PrincipalContext(ContextType.Domain, DOMAIN))
using (var userPrincipal = UserPrincipal.FindByIdentity(ctx, principal.Identity.Name))
using (var groups = userPrincipal.GetAuthorizationGroups())
The code is used a custom RoleProvider and the variable "principal" is HttpContext.Current.User. DOMAIN is my local domain.
This code works fine when I log in to the site, but throws an exception on the last line if I log in as either of a couple of test users.
While trying to retrieve the authorization groups, an error (5) occurred.
The test users have fewer permissions on the domain but are users in active directory. I tried creating the PrincipalContext with an alternative constructor supplying my username and password but it didn't make any difference to the behaviour.
This happens both on my dev machine and also on a separate staging server so I don't think it has anything to do with local permissions. I also don't see how it can be related to the users' permissions as I would expect the active directory request to be made as the IIS App Pool user (impersonation is turned off) or perhaps the user specified in the PrincipalContext constructor.
Any suggestions as to what is going on gratefully received.
It's not enough that they are users in Active Directory. The IIS App Pool user needs to be a member of the Windows Authorization Access Group to execute GetAuthorizationGroups.
Answered here: While trying to retrieve the authorization groups, an error (5) occurred

Domain user automatic autentication for intranet

I'm developing an intranet application. The application is working on an IIS on a windows server 2008. I'm using C# for coding the ASP.NET.
So, I only want to allow the domain users who are member of the OU ICT.
I don't want a login form, just an automatic authentication.
Sql Server Reporting Services works like this. Users don't have to login and the security is based on the AD. -> exactly what I'm looking for.
I have tried several ways, like with WidowsImpersonationContext I hit a dead-end on the OU.
If there would be anyone who can help me, I would be very thankful.
Solved the part where I check if the user is in the group/ou.
But I can't get the windows user from the client machine without logging in.
Greetings, Jeff
I´m not to sure about the mixture between OU´s and Groups here, but maybe the following will help you:
Reference System.DirectoryServices.AccountManagement,
var pc = new PrincipalContext(ContextType.Domain);
var user = UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName,"DOMAIN\\USER");
var g = System.DirectoryServices.AccountManagement.GroupPrincipal.FindByIdentity(pc, IdentityType.DistinguishedName, "Everyone");
var check = user.IsMemberOf(g);
HTH
Dominik

How can I convince Internet Explorer to allow authentication as another user?

Thanks for reading and for your thoughts; this is a hairy problem, so I thought I'd share to see if it is actually a fair challenge for more seasoned developers than ourselves.
We're developing a web application for a corporate Microsoft Active Directory environment, and we use Windows Authentication provided by IIS to authenticate users for single-sign-on, alongside Forms Authentication. I know IIS complains when both are enabled, but it works very well, and every site we've deployed at has had no weird quirks to work around - until now.
The new site has "shared" machines, logged in permanently with a generic account that has read-only access to the applications they need to use. This means that we can't differentiate between users who should have different permissions to the application; we need some way of prompting the user for authentication details.
First try was some serious googling; nobody else in the world seemed to have our problem except for a few misguided souls who had asked questions into the ether and received no response.
After a bit of brainstorming and nutting out the way IIS's authentication works, it seemed that the most straightforward way to approach the problem was to issue a 401 Unauthorized in response to a user known to be a shared account. Initial tests here seemed fruitful, yielding successful changes of username inside the browser, however a prototype at the site did not prompt for credentials, and the browser kept the same account details. We also hit on the IE-specific javascript
document.execCommand("ClearAuthenticationCache")
which, again, worked in the lab but not onsite. Further experiments with IE security settings onsite revealed that the browser would automatically reauthenticate if the webapp site was excluded from the Intranet Zone, regardless of the method used to trick the browser into prompting the user for new account details.
Now we're stuck. We've got workaround options for getting it going on time, but they're definitely not the "right" answers:
require users to log out of the shared account before logging into our app (...yuck)
exclude our webapp from Intranet Zone on all machines
provide a non-SSO login service for users
I'm convinced that there's a canonical way to do this - a known pattern, a common base problem that's already been solved, something like that - and I'm very interested to hear what sort of inventive methods there are to solve this sort of problem, and if anyone else has actually ever experienced anything remotely like it.
We ended up settling on a solution that submits a query to the LDAP directory the server knows about. It means having to accept the user's password, but no other solution was solid enough to run in a production environment.
Hopefully this helps someone. .NET Framework 3.5+ required.
using System.DirectoryServices.AccountManagement;
private static bool IsLdapAuthenticated(string username, string password)
{
PrincipalContext context;
UserPrincipal principal;
try
{
context = new PrincipalContext(ContextType.Domain);
principal = Principal.FindByIdentity(context, IdentityType.SamAccountName, username) as UserPrincipal;
}
catch (Exception ex)
{
// handle server failure / user not found / etc
}
return context.ValidateCredentials(principal.UserPrincipalName, password);
}
Could you not create a page to which the shared accounts are denied access. Then do a redirect to that page, with a return URL encoded in the query string, at any point where you need the user to reauthenticate with a non-shared account? This should trigger the browser to put up the usual login dialog.
After the user reauthenticates, the new page should just redirect back to the return URL in the query string.

How to query AD to get name email from lan id

I have some code in asp.net ( kindly given by someone else ) to query AD to get user name and email etc.
using System.DirectoryServices;
using System.DirectoryServices.ActiveDirectory;
using ActiveDs;
DirectorySearcher search = new DirectorySearcher(new DirectoryEntry(), string.Format("(samaccountname={0})", id));
if (search == null)
return id;
if (search.FindOne() == null)
return id;
DirectoryEntry usr = search.FindOne().GetDirectoryEntry();
IADsUser oUsr = (IADsUser)usr.NativeObject;
return string.Format("{0} {1}", usr.Properties["givenname"].Value, usr.Properties["sn"].Value);
However this requires impersonation with an id that's required to be changed every 2 weeks and then updated in the web.config which is often forgotten
Is there any non impersonation code to achieve the same result ?
UPDATE - it's a config tool and it looks up name, email id etc.
I like the service a/c idea
Q - How is it possible to run ( impersonate ) just the AD code with a "service" a/c ? any samples/code ?
how do you impersona
For your particular purpose, a ServiceAccount shall be added to AD;
If you ASP.NET application is for a LAN in your organization, you could simply forget about providing Username and Password and only provide the root domain. This way, Active directory will search for Windows authenticated user instead of using impersonnation (this assumes that the user accessing your application has the rights to perform the tasks provided by your application).
What exactly does your application need to do?
If your application manages user accounts, groups and OU, then you need to use impersonnation only if the user doing these tasks through the application has no rights of managing the AD with her/his regular user account. This, should not happen. So, event for this, if the user has the proper rights, omitting your credentials will only allow AD to search for the current logged on user.
We usually request IT to give us a domain service account. You still need to impersonate, but with a service account, the password will not have to be changed every 2 weeks, and is granted specific rights for the particular function you need it for, so it would mean very low maintenance for you.
I don't think so, because you need to bind to the domain with valid credentials in order to read from active directory.
Think of the username/password as part of a connection string to a database. I'd request a complex username and password from your domain administrator and request that they give it limited login permissions and set the password to never expire. Then store and use those in your Web.config file.

Categories