'Retrieve logged user info from microsoft graph in a framework .net environment

I need to implement SSO in a .net framework web application environment. Need to authenticate and retrieve the samaccountname of the logged user.

I have a working code, but only works on a Desktop and mobile device environments, I guess because I’m using "PublicClientApplicationBuilder".

Sample working code for desktop:

string clientId = "c8a73432-9383-4e7c....."; 
string tenantId = "efe4a126-2f4f-42ef....."; 

var app = PublicClientApplicationBuilder.Create(clientId)
  .WithTenantId(tenantId)
  .WithRedirectUri(http://localhost)  
  .Build();

string[] scopes = new string[]
{
https://graph.microsoft.com/User.Read
};

var result = await app.AcquireTokenInteractive(scopes)
                     .ExecuteAsync();
var stream = result.IdToken.ToString(); // return IDtoken with samaccountname

Does anybody have a sample code working for a web app?

I have tried with "ConfidentialClientApplicationBuilder", but doesn’t work:

string clientId = "c8a73432-9383..."; 
string tenantId = "efe4a126-2f4f..."; 
string secret = "1qN8Q~4m7qD5_...";
string authorityUri = $https://login.microsoftonline.com/efe4e126-2f4f-42ef...;

var app = ConfidentialClientApplicationBuilder.Create(clientId)
    .WithClientSecret(secret)
    .WithAuthority(new Uri(authorityUri))                    
    .WithRedirectUri(http://localhost) 
    .Build();

string[] scopes = new string[]
{
 https://graph.microsoft.com/User.Read
};

var accessTokenRequest = app.AcquireTokenForClient(scopes); 

var accessToken = accessTokenRequest.ExecuteAsync().Result.AccessToken;

Thx in advance!

  • List item


Solution 1:[1]

In a confidential client application, you usually have a cache per user. Therefore you will need to get the cache associated with the user and inform the application builder that you want to use it. In the same way, you might have a dynamically computed redirect URI.

could you please add below code , TokenCache userTokenCache = _tokenCacheProvider.SerializeCache(app.UserTokenCache,httpContext, claimsPrincipal);

please refer doc- Retrieve logged user info from microsoft graph in a framework .net environment .

if still it doesn't work, as you said it doesn't work , we would like to know what error you got?

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 vicky kumar