Quantcast
Channel: ASP.NET Core
Viewing all articles
Browse latest Browse all 9386

Accessing AAD in a ASP.NET Core 2.0 WebAPI project with AAD authentication

$
0
0

Hi there,

I am developing a MVC/WebAPI project, that authenticates the user against an AAD. This works perfectly (because it was set up by the project creation assistant ;)). But now I am faced with the problem to access more user details in AAD. I am using the Graph Client library, but cannot get access to it, because I am a little confused by all the token stuff and didn't find a working example for that.

What I have done till now:

1. Changed AzureAdAuthenticationBuilderExtensions.cs to access the tokens afterwards:

options.ResponseType = "token id_token";
options.Resource = _azureOptions.ClientId;
options.SaveTokens = true;

2. Added following code to a WebAPI method to retrieve the current user's profile:

var accessTokenRequest = HttpContext.GetTokenAsync("access_token");
accessTokenRequest.Wait();

//Update cloud data
AuthenticationContext authContext = new AuthenticationContext(Configuration.GetValue<string>("AzureAd:Instance") + Configuration.GetValue<string>("AzureAd:Domain"));
var ua = new UserAssertion(accessTokenRequest.Result);
var at = authContext.AcquireTokenAsync("https://graph.microsoft.com", Configuration.GetValue<string>("AzureAd:ClientId"), ua);
at.Wait();

GraphServiceClient graphClient = new GraphServiceClient(new DelegateAuthenticationProvider(
    (requestMessage) =>
    {
        requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", at.Result.AccessToken);
        return Task.FromResult(0);
    }));
var request = graphClient.Me.Request();
var b = request.GetAsync().Result;

I am sure, that I am mixing up the token types, because I don't get the Access Token from the AuthenticationContext. It fails with the exception

"One or more errors occurred. (AADSTS50027: Invalid JWT token. AADSTS50027: Invalid JWT token. Token format not valid."

Can anyone lead me into the right direction?

Thanks in advance!


Viewing all articles
Browse latest Browse all 9386

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>