3

I used the following configuration for requesting the token from AAD.

The app.module.ts file:

MsalModule.forRoot({
            clientID: 'CLIENT_ID',
            authority: "https://login.microsoftonline.com/TENANT_ID",
            validateAuthority: true,
            cacheLocation: 'sessionStorage',
            postLogoutRedirectUri: 'http://localhost:4200/authorize/signin',
            navigateToLoginRequestUrl: true,
            popUp: true,
            consentScopes: ['user.read', 'https://graph.microsoft.com']
        }

It returns the msal.idtoken, accesstoken, and some more msal key value pairs. Now following code is used to get the profile of the user by pasting the acquired MSAL_IDTOKEN.

const request = require('request');
const tok = 'MSAL_IDTOKEN HERE';
request.get({ url: "https://graph.microsoft.com/v1.0/me", headers: { "Authorization": "Bearer " + tok, "Content-type": "application/json" } }, function (err, response, body) {

    if (err) {
        console.log('err', err);
    }
    else
        console.log(response.body);
})

Now after running the app on Node, it used to return the profile of the user, as found after decoding the token, but now it does not.

Aniket Singh
  • 35
  • 1
  • 5

3 Answers3

2

I see that you have the right config on the Portal.

If you are using MSAL.js, given some code like this:

    this.app = new Msal.UserAgentApplication(

        this.applicationConfig.clientID,

        `https://login.microsoftonline.com/${AzureADName}/`,

        () => {

            // callback for login redirect

        },

        {

            redirectUri

        }

    );

You would then call this to get user information:

this.app.getUser();

or

this.app.getAccount();

You would have to provide version information to be sure, as the API was changed.

mvrak
  • 501
  • 3
  • 12
1

Get User Profile only works for msal": "^0.2.4" and not for the current version 1.1.

0

It seems that your are trying to read user profile from your access token.

To do that you need to assign profile dedicated permission on azure portal.

See the screen shot below:

enter image description here

Note: After assigning permission you can check your token on https://jwt.io/ whether it contains required permission.

Token Claim:

enter image description here

Read User data:

enter image description here

Code Snippet:

Token Class:

 public class AccessTokenClass
        {
            public string token_type { get; set; }
            public string expires_in { get; set; }
            public string resource { get; set; }
            public string scope { get; set; }
            public string access_token { get; set; }
            public string refresh_token { get; set; }

        }

Token Method:

private async Task<string> GetTokenByROPCFormat()
        {

            string tokenUrl = $"https://login.microsoftonline.com/YourTenantIdOrName/oauth2/token";

            var tokenRequest = new HttpRequestMessage(HttpMethod.Post, tokenUrl);

            tokenRequest.Content = new FormUrlEncodedContent(new Dictionary<string, string>
            {
                ["grant_type"] = "password",
                ["client_id"] = "b603c7be-a866--e6921e61f925",
                ["client_secret"] = "Vxf1SluKbgu4PF0Nf3wE5oG",
                ["resource"] = "https://graph.microsoft.com",
                ["username"] = "kironmemb@MyTenant.onmicrosoft.com",
                ["password"] = "@Mypassword"

            });

            dynamic json;
            dynamic results;
            HttpClient client = new HttpClient();

            var tokenResponse = await client.SendAsync(tokenRequest);

            json = await tokenResponse.Content.ReadAsStringAsync();
            results = JsonConvert.DeserializeObject<AccessTokenClass>(json);
            Console.WriteLine("Your Refresh Token=>{0}", results.refresh_token);



            //  New Block For Accessing Data from API
            HttpClient newClient = new HttpClient();

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "https://graph.microsoft.com/v1.0/me");

            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", results.access_token);
            HttpResponseMessage response = await newClient.SendAsync(request);

            string output = await response.Content.ReadAsStringAsync();
            return output;




        }
Md Farid Uddin Kiron
  • 16,817
  • 3
  • 17
  • 43
  • Yes, the profile permission is added in the portal. It still does not returns the profile. FYI, when I paste the token in jwt.ms, it decodes and gives the profile almost like I need. – Aniket Singh May 30 '19 at 08:28
  • @AniketSingh have you decoded your token on jwt? does it contain that permission? – Md Farid Uddin Kiron May 30 '19 at 08:30
  • "aud": "CLIENT_ID", "iss": "https://login.microsoftonline.com/TENANT_ID/v2.0", "iat": , "nbf": , "exp": 1559207087, "aio": "", "name": "Aniket Singh", "nonce": "", "oid": "", "preferred_username": "Aniket@ssrx.com", "sub": "", "tid": "", "uti": "", "ver": "2.0" – Aniket Singh May 30 '19 at 08:34
  • This is the JSON that I received. I have removed and aliased the values purposefully. – Aniket Singh May 30 '19 at 08:36
  • Can you let me know how you're generating the token? The URL and rest? Thank you ! – Aniket Singh May 30 '19 at 09:20
  • @AniketSingh I have updated the answer. Please consider `C#` I am not expert on node.js. But given the proper [node.js example here](https://github.com/auth0/node-jsonwebtoken#jwtverifytoken-secretorpublickey-options-callback) also can [see](https://medium.com/swlh/a-practical-guide-for-jwt-authentication-using-nodejs-and-express-d48369e7e6d4) – Md Farid Uddin Kiron May 30 '19 at 09:34