/// <summary> /// Retrieve an access token for the specified resource (e.g. MS Graph) /// </summary> /// <param name="attribute">TokenAttribute with desired resource & user's principal ID or ID token</param> /// <returns>JWT with audience, scopes, user id</returns> public async Task <string> GetAccessTokenAsync(TokenAttribute attribute) { attribute.CheckValidity(); switch (attribute.Identity) { case TokenIdentityMode.UserFromId: // If the attribute has no identity provider, assume AAD attribute.IdentityProvider = attribute.IdentityProvider ?? "AAD"; string signingKey = AppSettings.Resolve(Constants.AppSettingWebsiteAuthSigningKey); var easyAuthTokenManager = new EasyAuthTokenManager(EasyAuthClient, signingKey); return(await easyAuthTokenManager.GetEasyAuthAccessTokenAsync(attribute)); case TokenIdentityMode.UserFromToken: return(await GetAuthTokenFromUserToken(attribute.UserToken, attribute.Resource)); case TokenIdentityMode.ClientCredentials: return(await AadClient.GetTokenFromClientCredentials(attribute.Resource)); } throw new InvalidOperationException("Unable to authorize without Principal ID or ID Token."); }
private async Task <string> GetAuthTokenFromUserToken(string userToken, string resource) { if (string.IsNullOrWhiteSpace(resource)) { throw new ArgumentException("A resource is required to get an auth token on behalf of a user."); } // If the incoming token already has the correct audience (resource), then skip the exchange (it will fail with AADSTS50013!) var currentAudience = GetAudience(userToken); if (currentAudience != resource) { string token = await AadClient.GetTokenOnBehalfOfUserAsync( userToken, resource); return(token); } // No exchange requested, return token directly. return(userToken); }