コード例 #1
0
        private async Task <string> GetAccessToken(string[] graphScopes)
        {
            string        bootstrapContext = ClaimsPrincipal.Current.Identities.First().BootstrapContext.ToString();
            UserAssertion userAssertion    = new UserAssertion(bootstrapContext);

            string authority = String.Format(ConfigurationManager.AppSettings["Authority"], ConfigurationManager.AppSettings["DirectoryID"]);

            string appID     = ConfigurationManager.AppSettings["ClientID"];
            string appSecret = ConfigurationManager.AppSettings["ClientSecret"];
            var    cca       = ConfidentialClientApplicationBuilder.Create(appID)
                               .WithRedirectUri("https://localhost:44397")
                               .WithClientSecret(appSecret)
                               .WithAuthority(authority)
                               .Build();
            AcquireTokenOnBehalfOfParameterBuilder parameterBuilder = null;
            AuthenticationResult authResult = null;

            try
            {
                parameterBuilder = cca.AcquireTokenOnBehalfOf(graphScopes, userAssertion);
                authResult       = await parameterBuilder.ExecuteAsync();

                return(authResult.AccessToken);
            }
            catch (MsalServiceException e)
            {
                return(null);
            }
        }
コード例 #2
0
        // GET api/values
        public async Task <HttpResponseMessage> Get()
        {
            // OWIN middleware validated the audience, but the scope must also be validated. It must contain "access_as_user".
            string[] addinScopes = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/scope").Value.Split(' ');
            if (!(addinScopes.Contains("access_as_user")))
            {
                return(HttpErrorHelper.SendErrorToClient(HttpStatusCode.Unauthorized, null, "Missing access_as_user."));
            }

            // Assemble all the information that is needed to get a token for Microsoft Graph using the "on behalf of" flow.
            // Beginning with MSAL.NET 3.x.x, the bootstrapContext is just the bootstrap token itself.
            string        bootstrapContext = ClaimsPrincipal.Current.Identities.First().BootstrapContext.ToString();
            UserAssertion userAssertion    = new UserAssertion(bootstrapContext);

            var cca = ConfidentialClientApplicationBuilder.Create(ConfigurationManager.AppSettings["ida:ClientID"])
                      .WithRedirectUri("https://localhost:44355")
                      .WithClientSecret(ConfigurationManager.AppSettings["ida:Password"])
                      .WithAuthority(ConfigurationManager.AppSettings["ida:Authority"])
                      .Build();

            // MSAL.NET adds the profile, offline_access, and openid scopes itself. It will throw an error if you add
            // them redundantly here.
            string[] graphScopes = { "https://graph.microsoft.com/Files.Read.All" };

            // Get the access token for Microsoft Graph.
            AcquireTokenOnBehalfOfParameterBuilder parameterBuilder = null;
            AuthenticationResult authResult = null;

            try
            {
                parameterBuilder = cca.AcquireTokenOnBehalfOf(graphScopes, userAssertion);
                authResult       = await parameterBuilder.ExecuteAsync();
            }
            catch (MsalServiceException e)
            {
                // Handle request for multi-factor authentication.
                if (e.Message.StartsWith("AADSTS50076"))
                {
                    string responseMessage = String.Format("{{\"AADError\":\"AADSTS50076\",\"Claims\":{0}}}", e.Claims);
                    return(HttpErrorHelper.SendErrorToClient(HttpStatusCode.Forbidden, null, responseMessage));
                    // The client should recall the getAccessToken function and pass the claims string as the
                    // authChallenge value in the function's Options parameter.
                }

                // Handle lack of consent (AADSTS65001) and invalid scope (permission).
                if ((e.Message.StartsWith("AADSTS65001")) || (e.Message.StartsWith("AADSTS70011: The provided value for the input parameter 'scope' is not valid.")))
                {
                    return(HttpErrorHelper.SendErrorToClient(HttpStatusCode.Forbidden, e, null));
                }

                // Handle all other MsalServiceExceptions.
                else
                {
                    throw e;
                }
            }

            return(await GraphApiHelper.GetOneDriveFileNames(authResult.AccessToken));
        }
コード例 #3
0
        public async Task TestAcquireTokenOnBehalfOfBuilderAsync()
        {
            await AcquireTokenOnBehalfOfParameterBuilder.Create(_harness.Executor,
                                                                TestConstants.s_scope,
                                                                new UserAssertion(TestConstants.UserAssertion))
            .ExecuteAsync()
            .ConfigureAwait(false);

            _harness.ValidateCommonParameters(ApiEvent.ApiIds.AcquireTokenOnBehalfOf);
            _harness.ValidateOnBehalfOfParameters(TestConstants.UserAssertion);
        }