How to get the logged in user details(user email id and user name) using Access Token in AAD Single Sign on using java script back-end? - authentication

Hi am developing a windows store 8.1 app using C# and xaml
For log in, am authenticating the user with Windows Azure Active directory Single Sign-on using JavaScript back-end.
Once the user is logged in and i have the access token, how to get the logged in user's user email id and Username using the access token in the app?
Anybody please provide me a solution to get the user email using the access token?

If you have the access token then that should contain the user id value. For retrieving the e-mail address you have to query the Graph API to get user details. The full documentation on that is here but in short you should make a get request like below, placing the AccessToken in the Authorization header, after "Bearer ".
GET https://graph.windows.net/contoso.onmicrosoft.com/users/Alex#contoso.onmicrosoft.com?api-version=2013-04-05 HTTP/1.1
Authorization: Bearer eyJ0eX ... FWSXfwtQ
Content-Type: application/json
You can use either user principal name or objectId in the address. Better yet, you can use the Azure AD Graph Client nuget package and call their API to get user information.
Uri servicePointUri = new Uri("https://graph.windows.net");
Uri serviceRoot = new Uri(servicePointUri, "contoso.onmicrosoft.com");
ActiveDirectoryClient activeDirectoryClient = new ActiveDirectoryClient(serviceRoot, accessToken);
IUser user = activeDirectoryClient.Users
.Where(user => user.UserPrincipalName.Equals("alex#contoso.onmicrosoft.com"))
.ExecuteAsync().Result.CurrentPage.ToList().SingleOrDefault();
See here for the full sample.

Related

I want to use MsGraph in B2C, but I get a corrs error when getting an access token

I have an SPA that uses B2C as its certification.
not AD, im using B2C.
Now I want to display user information on the SPA,
so I want to use MsGraphAPI to get data from B2C.
Therefore, we are trying to obtain an access token using credential flow.
The code is as follows
requestUri = "https://login.microsoftonline.com/{tenandId}/oauth2/v2.0/token";
var params = new URLSearchParams();
params.append("grant_type","client_credentials");
params.append("client_id","XXXX");
params.append("client_secret","ZZZZ");
params.append("scope","https://graph.microsoft.com/.default");
const response = fetch(requestUri, {
method:"POST",
body:params
});
At this time, the developer tool shows a corrs error.
The following error.
access to fetch "https://login.microsoftonline.com/{tenandId}/oauth2/v2.0/token" from origin "http://localhost:3000" has been blocked by CORS policy.
How can I resolve this?
SPA is available at http://localhost:3000.
Is the localhost no good?
The purpose of authenticating is to get user information. You can insert any attribute into the token, and then parse the id_token to display the users profile information in your application. Calling MS Graph API for this seems counter intuitive.
Next, you shouldnt be using client_credentials in your SPA, those are secret credentails, and should only be used by your server. By exposing those credentials in your SPA, any user could extract them and use them to read your entire directroy store. This is why you are getting a CORS error, it's never supposed to be running on the client browser.

FusionAUth : How to merge user signup + sign in FusionAuth, to make user Auto login to web application

We are trying FusionAuth & looking to have a single step flow for Sign up + Sign In.
After user signs up, we want to show/land him directly to our application's dashboard page (without showing him login page in between the flow). The authentication should happen but internally i.e we are expecting OAuth2 standard IdToken in response to "WebApplication" so that web application can use IdToken to allow user to application.
Please note that we don't want to use approaches where we need to pass Username/password to our web application, don't want to handle user credentials. Also that we dont want to use Authentication Tokens returned in Registration flow because AuthenticationTokens are not that secure, looking to use OAuth2 based IdToken instead.
I have came across this post "https://fusionauth.io/community/forum/topic/165/taking-a-user-directly-to-the-registration-page/3" and tried following request, but it is showing Login page instead of registration.
/oauth2/register?client_id=<Configured_client_id>&redirect_uri=<Configured_redirect_uri>&response_type=code
(I have not used CSRF parameter though)
Please can you suggest why its showing Login Page?
You should be able to have a user register and be sent directly to your application, as long as you set the correct redirect_uri and put that on the registration URL:
https://local.fusionauth.io/oauth2/register?client_id=c50329fa-93e5-4618-8d9f-73d0ab069a23&response_type=code&redirect_uri=https%3A%2F%2Fapp.example.com%2F
The application will then receive a code that can be exchanged for an access token. You can call the userinfo endpoint with that token and get user information like email address, etc.
What you won't get that it seems like you might want is an id token. For that you'll have to send the user through the login process with a scope of profile. However, you could mind your own 'id token'-lite using the values from the userinfo endpoint and the JWT vending: https://fusionauth.io/docs/v1/tech/apis/jwt/#vend-a-jwt

IdentityServer4 with LDAP/AD authentication without UI

I'm currently working on a project where I'm trying to set up a service based on IdentityServer4 (https://github.com/IdentityServer/IdentityServer4) that authenticates users by querying a local Active Directory via LDAP.
To achieve that, I also included the IdentityServer4.LdapExtension (https://github.com/Nordes/IdentityServer4.LdapExtension) in my project. The working example from the repository works fine (https://github.com/Nordes/IdentityServer4.LdapExtension/tree/master/Sample/IdentityServer) - but the custom logic is part of the UI, and I need my service to operate without any UI.
Simply adding
.AddLdapUsers<ActiveDirectoryAppUser>(Conf.GetSection("ldap"), UserStore.InMemory)
as described in the documentation does not change the request pipeline, as the provided login/validation methods are never executed - they are only triggered with calls from the UI (AccountController). However, as I said, I don't want to integrate any UI in this service and rather use the interface which the Token-Endpoint already provides (POST request with client_id and client_secret, response with JWT).
Is there a way to integrate LDAP authentication without rewriting big parts that work out-of-the-box as desired?
From your question it sounds like you already have a username and password. Note client_id != username and client_secret != password. client_id is the identity for a client application.
The grant type you are trying to use is called Resource Owner Password when using the authorize endpoint or password when using the token endpoint.
This grant type is used to support legacy systems and is not recommended for new development.
The code that you want to executed to authenticate a user is in LdapUserResourceOwnerPasswordValidator.cs and it should be executed if you pass the correct parameters to the token endpoint:
POST /connect/token
client_id=yourclientid&
client_secret=yourclientsecret&
grant_type=password&
username=yourusername&password=yourusernamespassword
See token endpoint documentation: https://identityserver4.readthedocs.io/en/release/endpoints/token.html
You can use Identity Model to help you make the token request:
var response = await client.RequestPasswordTokenAsync(new PasswordTokenRequest
{
Address = "https://demo.identityserver.io/connect/token",
ClientId = "yourclientid",
ClientSecret = "yourclientsecret",
UserName = "yourusername",
Password = "yourusernamespassword"
});
This is documented here https://identitymodel.readthedocs.io/en/latest/client/token.html

G Suit - Token Validation like unprotect

I have an G-Suite Account..I have created a project in developer console. In that i have chosen the Oauth client Id credential for Application Type (Others). I have received client secret and Client ID..... Using this i have tried the sample mvc https://developers.google.com/drive/v3/web/quickstart/dotnet I have received the token with Below information
1.access_token
2.Experiences
3.refresh_token
4.Token_Type and so on…
I cant find any user related information (eg: UserId) in the token for Authenticate in our application (used tokeninfo api to validate token). I get below response
{
"issued_to": "123456789234.apps.googleusercontent.com",
"audience": "123456789234.apps.googleusercontent.com",
"scope": "https://www.googleapis.com/auth/admin.directory.user https://www.googleapis.com/auth/admin.directory.user.readonly",
"expires_in": 3520,
"access_type": "online"
}
How to get userid in access_token?
If you are try to get their user information you have to add https://www.googleapis.com/auth/userinfo.profile in your scopes.
View your basic profile info
Here is some additional reference:
How to get user email from google plus oauth
How to identify a Google OAuth2 user?
Hope this helps.

Using Office Outlook API with hard-code user name and password

I'm trying to build a (C#) web app that allows clients to make appointments with me.
I'd like the web app to be able to read and add entries to my outlook calendar.
Many users will use the web app, but the web app will only access one outlook calendar - mine.
All of the examples I have been able to get working have involved the web app user interactively authenticating - but my users will not know my password.
I would like to hard code my username/email address and password in the web app.
When trying to acquire a token I get an error:
Microsoft.IdentityModel.Clients.ActiveDirectory.AdalServiceException:
AADSTS65001: The user or administrator has not consented to use the application.
Send an interactive authorization request for this user and resource.
I am not an administrator of the tenant. Is there any way I can get this to work without administrator involvement?
Would using some kind of certificate rather than a user name and password as user credentials help?
My code (currently in a simple C# console application) is as follows:
UserCredential uc = new UserCredential(MyUsername, MyPassword);
var AuthContext = new AuthenticationContext("https://login.windows.net/Common");
// this doesn't work unless an unexpired token already exists
ar = AuthContext.AcquireToken("https://outlook.office365.com/", MyClientId, uc);
// this does work, but requires the app user to know the password
ar = AuthContext.AcquireToken("https://outlook.office365.com/", MyClientId, new Uri(MyReturnURI));
To enable use the username and password to request the token directly, we need to consent to use the app.
We can use the OAuth 2.0 authorization code grant flow to grant the consent by user. Here is an sample use the ADAL authentication library(3.13.1.846) to acquire the delegate token:
static string authority= "https://login.microsoftonline.com/common";
public static string GetDeligateToken(string resource, string clientId,string redirectURL)
{
AuthenticationContext authContext = new AuthenticationContext(authority);
AuthenticationResult authResult= authContext.AcquireTokenAsync(resource, clientId,new Uri(redirectURL), new PlatformParameters(PromptBehavior.Auto)).Result;
return authResult.AccessToken;
}
After we consent the app, now we can use the code in your post to acquire the token.