Why I have access to an authorized useron a local windows account and not when I am logged in a domain one? - asp.net-core

I can authorize a user for a specific Active Directory and get the user's groups when I execute the code as a local wndows account.
However I get acces denied, when I am logged in a specific domain account
What should I add to my api ? Maybe windows user credentials ? And where to add them ?
ADContext = new PrincipalContext(ContextType.Domain, ADSettings.Domain, ADSettings.User, ADSettings.Password);
UserPrincipal user = UserPrincipal.FindByIdentity(ADContext, IdentityType.SamAccountName, user.Username);
var groups = user.GetGroups(); //this one fails.
StackTrace
at System.DirectoryServices.ActiveDirectory.Utils.GetDSHandle(String domainControllerName, String domainName, IntPtr authIdentity, LoadLibrarySafeHandle libHandle)
at System.DirectoryServices.ActiveDirectory.DomainController.GetDSHandle()
at System.DirectoryServices.ActiveDirectory.DomainController.GetDomainControllerInfo()
at System.DirectoryServices.ActiveDirectory.DomainController.get_SiteName()
at System.DirectoryServices.AccountManagement.ADStoreCtx.GetGroupsMemberOf(Principal p)
at System.DirectoryServices.AccountManagement.Principal.GetGroupsHelper()
at System.DirectoryServices.AccountManagement.Principal.GetGroups()

Related

How to connect LDAP With username and password?

I have my Ldap working the only issue i'm facing was when I try to login with email that is when I land in the else part in the below code. If my username is different from email then it throws error. i.e if my email is 'skumar#gmail.com' and my username is 'saurakumar' then it will through invalid username password error.
As internally I'm using username to make email i.e if the user login with name 'karan' then i'm expecting the email to be karan #gmail.com which is not true in many scenario and the Authentication fails. I'm looking for some solution wherein I can login either via email or via username I'll be able to authenticate user. Below is the snippet of my code. Please suggest?
ldapEnv.put(Context.INITIAL_CONTEXT_FACTORY, initialContextFactory);
ldapEnv.put(Context.PROVIDER_URL, url);
ldapEnv.remove(Context.SECURITY_PROTOCOL);
if (email == null) {
lContext = new InitialLdapContext(ldapEnv, null);
entryResult = searchUserEntry(lContext, user, searchCtrls);
final String usrDN = ((Context) entryResult.getObject()).getNameInNamespace();
lContext.addToEnvironment(Context.SECURITY_AUTHENTICATION, "simple");
lContext.addToEnvironment(Context.SECURITY_PRINCIPAL, usrDN);
lContext.addToEnvironment(Context.SECURITY_CREDENTIALS, pass);
lContext.reconnect(null);
} else {
ldapEnv.put(Context.SECURITY_PRINCIPAL, email);
ldapEnv.put(Context.SECURITY_CREDENTIALS, credentials);
lContext = new InitialLdapContext(ldapEnv, null);
return lContext;
searchUserEntry(lContext, user, searchCtrls);
}
Normally this is a 3-step process:
Bind to LDAP as an administrative user. Note that this should not be the master user defined in the configuration file: that's for OpenLDAP's use itself. Instead it should be a user mentioned in the DIT that has the appropriate search access for the next step.
Search for the user via some unique attribute, e.g. in your case email.
Using the found DN of the user and the password he specified, attempt to bind as that user (with the reconnect() method, after changing the environment of the context appropriately).
If all that succeeds, you have a login success. If (2) or (3) fail, you have a failure, and note that you should not tell the user which it was: otherwise you are leaking information to attackers. You should not mention whether it was the username (email) or the password that was wrong.

How to obtain user's organization name from Google APIs

Our app authenticates users with Google using OpenID connect, then attempts to obtain the name of the user's organization using Google's APIs, since it is not available in the Open ID Connect UserInfo object. The code is as follows:
JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
HttpTransport httpTransport = GoogleCredential credential = getCredentials(jsonFactory, httpTransport, connection.getDomainAdminEmail());
Directory directory = new Directory.Builder(httpTransport, jsonFactory, null).setApplicationName(APP_NAME).setHttpRequestInitializer(setHttpTimeout(credential)).build();
User user = directory.users().get(id).execute();
Object organizations = user.getOrganizations();
Although the user is returned, the value of organizations is null, even though the organization is defined in the Google Apps Admin panel. How does one obtain the company name of an authenticated Google user?
The following call retrieves customer info using Google Directory API:
directory.customers().get("my_customer").execute();
Note: Use of my_customer will retrieve current customer. At minimum, this call requires the following scope:
https://www.googleapis.com/auth/admin.directory.customer.readonly
It seems customer info cannot be obtained using a service credential. It needs to be a Client ID credential. The user logging in has to consent to the above scope.
GoogleCredential credential = getCredentials(jsonFactory, httpTransport, connection.getDomainAdminEmail(),true);
Directory directory = new Directory.Builder(httpTransport, jsonFactory, null)
.setApplicationName(APP_NAME)
.setHttpRequestInitializer(setHttpTimeout(credential))
.build();
Customer customer = directory.customers().get("my_customer").execute();
CustomerPostalAddress postAddress = customer.getPostalAddress();
googleCustomer = new GoogleCustomer.Builder()
.setPhoneNumber(customer.getPhoneNumber())
.setLanguage(customer.getLanguage())
.setCompany(postAddress.getOrganizationName())
.setAddress1(postAddress.getAddressLine1())
.setAddress2(postAddress.getAddressLine2())
.setAddress3(postAddress.getAddressLine3())
.setAddressContactName(postAddress.getContactName())
.setAddressCountryCode(postAddress.getCountryCode())
.setAddressLocality(postAddress.getLocality())
.setAddressPostalCode(postAddress.getPostalCode())
.setAddressRegion(postAddress.getRegion())
.build();

How do I administratively set a new password for ASP.net Identity User who forgot their password?

I am not looking for a solution that involves the user, a token generated, and emailing in order to reset a user's password.
The scenario is a user contacts the admins and asks them to reset their password (internal organization web app). They are then told what that new temporary password is so they can log in and change it.
I see no function that lets me do the above. My attempt:
string passwordToken = await UM.GeneratePasswordResetTokenAsync(user.Id);
IdentityResult res = await UM.ResetPasswordAsync(user.Id, passwordToken, "newPassword##!$%");
UM is UserManager.
I get error "No IUserTokenProvider is registered". I think GeneratePasswordResetToken is the one causing the error. If so, why?
How do I properly do what I need?
Use the combination of RemovePasswordAsync and AddPasswordAsync
UserManager.RemovePasswordAsync(user.Id);
UserManager.AddPasswordAsync(user.Id, tempPassword);

authenticate user in LDAP with email and password

I am new to LDAP API. I am able to connect to a LDAP server and search the user. How would I authenticate a user with email/password using UnboundID LDAP API ?
I have not seen any authentication in LDAP which uses email and password to authenticate user?
Is it Possible to authenticate the user using email and password
What I am doing to authenticate the user given as below
Searching below the USERS Directory and matching Email and Finding his DN
Based on DN connecting the user and if Connection Successful, Authenticate the user or Execption occurs in Connecting then user is not Authenticated
Is there right way to authenticate the User?
You have to do two steps.
Using an administrative login, search the directory for the user.
Using that user's DN and the password he supplied, attempt to bind.
If either didn't succeed, either the identity or the password is incorrect.
Using the UnboundID LDAP SDK, this simple piece of code searches for the entry. If there is one entry that has the known email address, BIND using that DN (the password has to come from someplace else). Nothing happens (authenticated is false) is there is more one entry that matches the search parameters or if no entries match the search parameters. This code assumes that baseObject is dc=example,dc=com, subtree search is required, and the attribute with the email address has an alias mail. The code also assumes there is a bindDN and bindPassword that has sufficient access rights to search for the user with the email address. The email address for which it searches is assumed to be babs.jensen#example.com.
Exceptions are ignored throughout.
String baseObject = "dc=example,dc=com";
String bindDN = "dn-with-permission-to-search";
String bindPassword = "password-of-dn-with-permission-to-search";
// Exceptions ignored.
LDAPConnection ldapConnection =
new LDAPConnection(hostname,port,bindDN,bindPassword);
String emailAddress = "babs.jensen#example.com";
String filterText = String.format("mail=%s",emailAddress);
SearchRequest searchRequest = new SearchRequest(baseObject,
SearchScope.SUB,filterText,"1.1");
SearchResult searchResult = ldapConnection.search(searchRequest);
boolean authenticated = false;
if(searchResult.getEntryCount() == 1)
{
// There is one entry with that email address
SearchResultEntry entry = searchResult.getSearchEntries().get(0);
// Create a BIND request to authenticate. The password has
// has to come from someplace outside this code
BindRequest bindRequest =
new SimpleBindRequest(entry.getDN(),password);
ldapConnection.bind(bindRequest);
authenticated = true;
}
else if(searchResult.getEntryCount() > 1)
{
// more than one entry matches the search parameters
}
else if(searchResult.getEntryCount() == 0)
{
// no entries matched the search parameters
}

how to show notify to current account if this account is logged in another computer

I have a windows application and it connected to a server via WCF services, database is on the server. To using this software, you have to login. So I want to show a notify to UserA, who is working on the software, if UserA's account is logged (on another computer) by another people.
Please help !
Make your logon service operation on the service return a flag which indicates if this account is being used concurrently by another user.
// Pseudocode
LogonResponse response = Service.Logon :> username, password;
if response.UserAccountIsAlreadyLoggedOn print "User logged on already!"
To do this the service would have to persist the logged-on state of all users, probably in the database.
Your logon service operation would need to query the logged-on state of the user account being presented by the operation caller.
// Pseudocode
public LogonResponse Logon (string username, string password)
{
if database.IsThisAccountAlreadyLoggedOn :> username ?
return LogonResponse :> UserAccountIsAlreadyLoggedOn = true;
otherwise
return LogonResponse :> UserAccountIsAlreadyLoggedOn = false;
}
This is the easiest way I can think of to proceed with this.