예제 #1
0
        // Gets an access token. First tries to get the access token from the token cache.
        // Using password (secret) to authenticate. Production apps should use a certificate.
        public async Task <string> GetUserAccessTokenAsync(string userId)
        {
            var cca = new ConfidentialClientApplication(
                _appId,
                _redirectUri,
                _credential,
                null,
                null);

            if (!cca.Users.Any())
            {
                throw new ServiceException(new Error
                {
                    Code    = "TokenNotFound",
                    Message = "User not found in token cache. Maybe the server was restarted."
                });
            }

            try
            {
                var result = await cca.AcquireTokenSilentAsync(_scopes, cca.Users.First());

                return(result.AccessToken);
            }

            // Unable to retrieve the access token silently.
            catch (Exception)
            {
                throw new ServiceException(new Error
                {
                    Code    = GraphErrorCode.AuthenticationFailure.ToString(),
                    Message = "Caller needs to authenticate. Unable to retrieve the access token silently."
                });
            }
        }
        private async Task <AuthenticationResult> GetToken()
        {
            var accounts = await _confidentialClientApplication.GetAccountsAsync();

            return(await _confidentialClientApplication.AcquireTokenSilentAsync(_azureAdB2COptions.Scopes,
                                                                                accounts.FirstOrDefault(), _azureAdB2COptions.Authority, false));
        }
예제 #3
0
        private static GraphServiceClient GetAuthenticatedClient()
        {
            return(new GraphServiceClient(
                       new DelegateAuthenticationProvider(
                           async(requestMessage) =>
            {
                // Get the signed in user's id and create a token cache
                string signedInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
                SessionTokenStore tokenStore = new SessionTokenStore(signedInUserId,
                                                                     new HttpContextWrapper(HttpContext.Current));

                var idClient = new ConfidentialClientApplication(
                    appId, redirectUri, new ClientCredential(appSecret),
                    tokenStore.GetMsalCacheInstance(), null);

                var accounts = await idClient.GetAccountsAsync();

                // By calling this here, the token can be refreshed
                // if it's expired right before the Graph call is made
                var result = await idClient.AcquireTokenSilentAsync(
                    graphScopes.Split(' '), accounts.FirstOrDefault());

                requestMessage.Headers.Authorization =
                    new AuthenticationHeaderValue("Bearer", result.AccessToken);
            })));
        }
예제 #4
0
        public async Task <AuthResult> GetAccessToken(AuthenticationOptions authOptions, IDialogContext context)
        {
            AuthResult authResult;
            string     validated = null;

            if (context.UserData.TryGetValue($"{this.Name}{ContextConstants.AuthResultKey}", out authResult) &&
                context.UserData.TryGetValue($"{this.Name}{ContextConstants.MagicNumberValidated}", out validated) &&
                validated == "true")
            {
                try
                {
                    InMemoryTokenCacheMSAL        tokenCache = new InMemoryTokenCacheMSAL(authResult.TokenCache);
                    ConfidentialClientApplication client     = new ConfidentialClientApplication(authOptions.ClientId,
                                                                                                 authOptions.RedirectUrl, new ClientCredential(authOptions.ClientSecret), tokenCache);
                    var result = await client.AcquireTokenSilentAsync(authOptions.Scopes, authResult.UserUniqueId);

                    authResult = result.FromMSALAuthenticationResult(tokenCache);
                    context.StoreAuthResult(authResult, this);
                }
                catch (Exception ex)
                {
                    Trace.TraceError("Failed to renew token: " + ex.Message);
                    await context.PostAsync("Your credentials expired and could not be renewed automatically!");
                    await Logout(authOptions, context);

                    return(null);
                }
                return(authResult);
            }

            return(null);
        }
예제 #5
0
        // GET: Admin
        public async Task <ActionResult> Index()
        {
            // try to get token silently
            string     signedInUserID = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
            TokenCache theCache       = new MSALSessionCache(signedInUserID, this.HttpContext).GetMsalCacheInstance();

            ConfidentialClientApplication cca = new ConfidentialClientApplication(clientId, redirectUri,
                                                                                  new ClientCredential(appKey), theCache, null);

            string[] scopes = adminScopes.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            try
            {
                AuthenticationResult result = await cca.AcquireTokenSilentAsync(scopes, cca.Users.First());
            }
            catch (Exception)
            {
                try
                {// when failing, manufacture the URL and assign it
                    string authReqUrl = await OAuth2RequestManager.GenerateAuthorizationRequestUrl(scopes, cca, this.HttpContext, Url);

                    ViewBag.AuthorizationRequest = authReqUrl;
                }
                catch (Exception ee)
                {
                }
            }
            return(View("Admin"));
        }
        private async Task <string> GetAccessTokenAsync()
        {
            var        scope                  = _veracityIntegrationOptions.VeracityPlatformServiceScopes.Split(' ');
            TokenCache userTokenCache         = new MSALSessionCache(_httpContext).GetMsalCacheInstance();
            ConfidentialClientApplication cca = new ConfidentialClientApplication(_veracityIntegrationOptions.ClientId,
                                                                                  _veracityIntegrationOptions.Authority,
                                                                                  _veracityIntegrationOptions.RedirectUri,
                                                                                  new ClientCredential(_veracityIntegrationOptions.ClientSecret),
                                                                                  userTokenCache,
                                                                                  null);

            try
            {
                IEnumerable <IAccount> accounts = await cca.GetAccountsAsync();

                IAccount firstAccount = accounts.FirstOrDefault();
                var      result       = await cca.AcquireTokenSilentAsync(
                    scope,
                    firstAccount,
                    _veracityIntegrationOptions.Authority,
                    false);

                return(result.AccessToken);
            }
            catch (MsalUiRequiredException)
            {
                // Cannot find any cache user in memory, you should sign out and login again.
                throw new AuthenticationException("Cannot find login user credential, please sign out and login again");
            }
        }
예제 #7
0
        public async Task <string> GetAccessToken(SessionTokenCache tokenCache)
        {
            string accessToken = null;

            // Load the app config from web.config
            var appId       = ConfigurationManager.AppSettings["ida:AppId"];
            var appPassword = ConfigurationManager.AppSettings["ida:AppPassword"];
            var redirectUri = ConfigurationManager.AppSettings["ida:RedirectUri"];
            var scopes      = ConfigurationManager.AppSettings["ida:AppScopes"]
                              .Replace(' ', ',').Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

            var confidentialClientApplication = new ConfidentialClientApplication(
                appId,
                redirectUri,
                new ClientCredential(appPassword),
                tokenCache.GetMsalCacheInstance(),
                null);

            // Call AcquireTokenSilentAsync, which will return the cached
            // access token if it has not expired. If it has expired, it will
            // handle using the refresh token to get a new one.
            var result = await confidentialClientApplication.AcquireTokenSilentAsync(scopes, confidentialClientApplication.Users.First());

            accessToken = result.AccessToken;

            return(accessToken);
        }
        // Get an access token. First tries to get the token from the token cache.
        public async Task <string> GetUserAccessTokenAsync()
        {
            string signedInUserID = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;

            tokenCache = new SessionTokenCache(
                signedInUserID,
                HttpContext.Current.GetOwinContext().Environment["System.Web.HttpContextBase"] as HttpContextBase);
            //var cachedItems = tokenCache.ReadItems(appId); // see what's in the cache

            ConfidentialClientApplication cca = new ConfidentialClientApplication(
                appId,
                redirectUri,
                new ClientCredential(appSecret),
                tokenCache);

            try
            {
                AuthenticationResult result = await cca.AcquireTokenSilentAsync(scopes.Split(new char[] { ' ' }));

                return(result.Token);
            }

            // Unable to retrieve the access token silently.
            catch (MsalSilentTokenAcquisitionException)
            {
                HttpContext.Current.Request.GetOwinContext().Authentication.Challenge(
                    new AuthenticationProperties()
                {
                    RedirectUri = "/"
                },
                    OpenIdConnectAuthenticationDefaults.AuthenticationType);

                throw new Exception(Resource.Error_AuthChallengeNeeded);
            }
        }
예제 #9
0
        public async Task <string> GetUserAccessTokenAsync()
        {
            string                        signedInUserID = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
            HttpContextWrapper            httpContext    = new HttpContextWrapper(HttpContext.Current);
            TokenCache                    userTokenCache = new SessionTokenCache(signedInUserID, httpContext).GetMsalCacheInstance();
            ConfidentialClientApplication cca            = new ConfidentialClientApplication(appId, redirectUri, new ClientCredential(appSecret), userTokenCache, null);

            try
            {
                var accounts = await cca.GetAccountsAsync();

                AuthenticationResult result = await cca.AcquireTokenSilentAsync(scopes.Split(new char[] { ' ' }), accounts.First());

                return(result.AccessToken);
            }

            catch (Exception)
            {
                HttpContext.Current.Request.GetOwinContext().Authentication.Challenge(
                    new AuthenticationProperties()
                {
                    RedirectUri = "/"
                },
                    OpenIdConnectAuthenticationDefaults.AuthenticationType);

                throw new Exception();
            }
        }
예제 #10
0
        /// <summary>
        ///     Helper method to silently retrieve a valid Access Token
        ///     that contains the needed scope.
        /// </summary>
        /// <param name="confidentialClientApplication"></param>
        /// <param name="authority"></param>
        /// <param name="fqScopes"></param>
        /// <returns></returns>
        public async Task <string> AcquireTokenSilently(ConfidentialClientApplication confidentialClientApplication,
                                                        string authority, string[] fqScopes)
        {
            var user = confidentialClientApplication.Users.FirstOrDefault();

            //        if (user == null)
            //        {
            //            throw new Exception(
            //                "The User is NULL.  Please clear your cookies and try again.  Specifically delete cookies for 'login.microsoftonline.com'.  See this GitHub issue for more details: https://github.com/Azure-Samples/active-directory-b2c-dotnet-webapp-and-webapi/issues/9");
            //        }
            using (ElapsedTime elapsedTime = new ElapsedTime())
            {
                var result = await confidentialClientApplication.AcquireTokenSilentAsync(
                    fqScopes,
                    user,
                    authority,
                    false
                    );

                var elapsed = elapsedTime.ElapsedText;

                this._diagnosticsTracingService.Trace(TraceLevel.Debug, $"OidcRequestHelper.AcquireTokenSilently took {elapsed}.");
                return(result.AccessToken);
            }
        }
예제 #11
0
        public static async Task <string> GetUserToken(string userId)
        {
            var confidentialClient = new ConfidentialClientApplication(notifAppId,
                                                                       authority, redirectUri, notifClientCreds, BlobTokenCache.GetMsalCacheInstance(), null);

            //Logger.LogCallback = AuthLog;
            //Logger.Level = Microsoft.Identity.Client.LogLevel.Verbose;
            //Logger.PiiLoggingEnabled = true;

            var account = await confidentialClient.GetAccountAsync($"{userId}.{tid}");

            if (account == null)
            {
                return(string.Empty);
            }

            try
            {
                var result = await confidentialClient.AcquireTokenSilentAsync(notifScopes, account);

                return(result.AccessToken);
            }
            catch (MsalException)
            {
                return(string.Empty);
            }
        }
        public async Task <ActionResult> SendMail()
        {
            // try to get token silently
            string           signedInUserID = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
            MSALSessionCache theCache       = new MSALSessionCache(signedInUserID, this.HttpContext);

            ConfidentialClientApplication cca = new ConfidentialClientApplication(clientId, redirectUri,
                                                                                  new ClientCredential(appKey), theCache);

            string[] scopes = { "Mail.Send" };
            try
            {
                AuthenticationResult result = await cca.AcquireTokenSilentAsync(scopes);
            }
            catch (MsalSilentTokenAcquisitionException)
            {
                try
                {// when failing, manufacture the URL and assign it
                    string authReqUrl = await WebApp.Utils.OAuth2RequestManager.GenerateAuthorizationRequestUrl(scopes, cca, this.HttpContext, Url);

                    ViewBag.AuthorizationRequest = authReqUrl;
                }
                catch (Exception ee)
                {
                }
            }
            return(View());
        }
        public async Task <ActionResult> ReadMail()
        {
            try
            {
                string signedInUserID             = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
                ConfidentialClientApplication cca = new ConfidentialClientApplication(clientId, null,
                                                                                      new ClientCredential(appKey), new MSALSessionCache(signedInUserID, this.HttpContext));
                string[]             scopes = { "Mail.Read" };
                AuthenticationResult result = await cca.AcquireTokenSilentAsync(scopes);

                HttpClient hc = new HttpClient();
                hc.DefaultRequestHeaders.Authorization =
                    new System.Net.Http.Headers.AuthenticationHeaderValue("bearer", result.Token);
                HttpResponseMessage hrm = await hc.GetAsync("https://graph.microsoft.com/v1.0/me/messages");

                string rez = await hrm.Content.ReadAsStringAsync();

                ViewBag.Message = rez;

                return(View());
            }
            catch (MsalSilentTokenAcquisitionException)
            {
                ViewBag.Relogin = "******";
                return(View());
            }
            catch (Exception eee)
            {
                ViewBag.Error = "An error has occurred. Details: " + eee.Message;
                return(View());
            }
        }
        /// <summary>
        /// 使用该方法获取Access Token
        /// </summary>
        /// <returns></returns>
        public async Task <string> GetUserAccesstokenAsync()
        {
            string             singedInUserID = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
            HttpContextWrapper httpContext    = new HttpContextWrapper(HttpContext.Current);
            TokenCache         userTokenCache = new TokenSessionCache(singedInUserID, httpContext)
                                                .GetMsalCacheInstance();
            ConfidentialClientApplication cca = new ConfidentialClientApplication(
                ClientID,
                RedirectUri,
                new ClientCredential(ClientSecret),
                userTokenCache, null);

            string[] scopes = GraphScopes.Split(new char[] { ' ' });
            try
            {
                AuthenticationResult result = await cca.AcquireTokenSilentAsync(scopes, cca.Users.First());//confidential.Users.First());

                return(result.AccessToken);
            }
            catch (Exception ex)
            {
                HttpContext.Current.Request.GetOwinContext().Authentication.Challenge(
                    new Microsoft.Owin.Security.AuthenticationProperties()
                {
                    RedirectUri = "/"
                },
                    OpenIdConnectAuthenticationDefaults.AuthenticationType);
                throw new ServiceException(
                          new Error
                {
                    Code    = GraphErrorCode.AuthenticationFailure.ToString(),
                    Message = Resource.Error_AuthChallengeNeeded,
                });
            }
        }
        // Gets an access token. First tries to get the token from the token cache.
        public async Task <string> GetUserAccessTokenAsync()
        {
            string             signedInUserID = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
            HttpContextWrapper httpContext    = new HttpContextWrapper(HttpContext.Current);
            TokenCache         userTokenCache = new SessionTokenCache(signedInUserID, httpContext).GetMsalCacheInstance();
            //var cachedItems = tokenCache.ReadItems(appId); // see what's in the cache

            ConfidentialClientApplication cca = new ConfidentialClientApplication(
                appId,
                redirectUri,
                new ClientCredential(appSecret),
                userTokenCache,
                null);

            try
            {
                AuthenticationResult result = await cca.AcquireTokenSilentAsync(scopes.Split(new char[] { ' ' }), cca.Users.First());

                return(result.AccessToken);
            }

            // Unable to retrieve the access token silently.
            catch (Exception)
            {
                HttpContext.Current.Request.GetOwinContext().Authentication.Challenge(
                    new AuthenticationProperties()
                {
                    RedirectUri = "/"
                },
                    OpenIdConnectAuthenticationDefaults.AuthenticationType);

                throw new Exception(Resource.Error_AuthChallengeNeeded);
            }
        }
예제 #16
0
        private async Task <string> GetUserAccessTokenAsync(IEnumerable <string> scopes)
        {
            var userId    = this.GetUserObjectId();
            var appSecret = await this.keyVaultService.GetSecret(this.config.AppSecretKeyVaultKey);

            var credential = new ClientCredential(appSecret);

            var request    = this.httpContextAccessor.HttpContext.Request;
            var currentUri = UriHelper.BuildAbsolute(request.Scheme, request.Host, request.PathBase);

            var tokenCache  = new DistributedTokenCacheHelper(this.cache, this.dataProtectionProvider, userId).GetTokenCache();
            var application = new ConfidentialClientApplication(this.config.ClientId, this.config.Authority, currentUri, credential, tokenCache, null);

            AuthenticationResult result;

            try
            {
                IAccount account = await application.GetAccountAsync($"{userId}.{this.config.TenantId}");

                result = await application.AcquireTokenSilentAsync(scopes, account);
            }
            catch
            {
                var token = await this.httpContextAccessor.HttpContext.GetTokenAsync("access_token");

                var userAssertion = new UserAssertion(token, "urn:ietf:params:oauth:grant-type:jwt-bearer");
                result = await application.AcquireTokenOnBehalfOfAsync(scopes, userAssertion);
            }

            return(result.AccessToken);
        }
        public async Task <AuthResult> GetAccessTokenSilent(AuthenticationOptions options, IDialogContext context)
        {
            if (context.UserData.TryGetValue($"{Name}{ContextConstants.AuthResultKey}", out AuthResult result) &&
                context.UserData.TryGetValue($"{Name}{ContextConstants.MagicNumberValidated}", out string validated) &&
                validated == "true")
            {
                try
                {
                    var tokenCache = new InMemoryTokenCacheMSAL(result.TokenCache).GetMsalCacheInstance();
                    var client     = new ConfidentialClientApplication(options.ClientId,
                                                                       options.RedirectUrl, new ClientCredential(options.ClientSecret), tokenCache, null);
                    var r = await client.AcquireTokenSilentAsync(options.Scopes, client.GetUser(result.UserUniqueId));

                    result = r.FromMSALAuthenticationResult(tokenCache);
                    context.StoreAuthResult(result, this);
                    return(result);
                }
                catch (Exception)
                {
                    return(null);
                }
            }

            return(null);
        }
예제 #18
0
        // Use MSAL to get a the token we need for the Microsoft Graph
        private async Task <string> GetGraphAccessToken(string userId, string[] scopes)
        {
            ConfidentialClientApplication cc     = new ConfidentialClientApplication(Globals.ClientId, Globals.RedirectUri, new ClientCredential(Globals.ClientSecret), new MsalSessionTokenCache(userId, HttpContext));
            AuthenticationResult          result = await cc.AcquireTokenSilentAsync(scopes);

            return(result.Token);
        }
예제 #19
0
        protected override string GetBearerToken()
        {
            string accessToken = (HttpContext.Current.User.Identity as ClaimsIdentity)?.FindFirst("AccessToken").Value;

            if (!string.IsNullOrEmpty(accessToken))
            {
                return(accessToken);
            }

            var signedInUserId = (HttpContext.Current.User.Identity as ClaimsIdentity)?.FindFirst("userId").Value;
            var cache          = new MSALSessionCache(signedInUserId, HttpContext.Current.GetOwinContext().Environment["System.Web.HttpContextBase"] as HttpContextBase).GetMsalCacheInstance();
            var clientCred     = new ClientCredential(ConfigurationManager.AppSettings["ida:ClientSecret"]);
            var context        = new ConfidentialClientApplication(Startup.ClientId, Startup.Authority, ConfigurationManager.AppSettings["ida:RedirectUri"], clientCred, cache, null);
            var user           = context.Users.FirstOrDefault();

            if (user == null)
            {//Clear cookies and notify error handler that cache is corrupted
                HttpContext.Current.GetOwinContext().Authentication.SignOut(CookieAuthenticationDefaults.AuthenticationType);
                throw new ServerException(new ErrorDetail
                {
                    Message = "Invalid token cache"
                }, HttpStatusCode.Unauthorized);
            }
            var token = Task.Run(async() => await context.AcquireTokenSilentAsync(new[] { ConfigurationManager.AppSettings["api:scope"] }, user, Startup.Authority, false)).Result;

            return(token.AccessToken);
        }
예제 #20
0
        private async Task AddAccessToken(System.Net.Http.HttpRequestMessage request)
        {
            // Load the app config from web.config
            string appId       = ConfigurationManager.AppSettings["ida:AppId"];
            string appSecret   = ConfigurationManager.AppSettings["ida:AppSecret"];
            string redirectUri = ConfigurationManager.AppSettings["ida:RedirectUri"];

            // Get the current user's ID
            string userId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;

            // Get the user's token cache
            SessionTokenCache tokenCache = new SessionTokenCache(userId, HttpContext);

            ConfidentialClientApplication cca = new ConfidentialClientApplication(
                appId, redirectUri, new ClientCredential(appSecret), tokenCache);

            // Call AcquireTokenSilentAsync, which will return the cached
            // access token if it has not expired. If it has expired, it will
            // handle using the refresh token to get a new one.
            string[]             scopes = { "User.Read", "Mail.Send" };
            AuthenticationResult result = await cca.AcquireTokenSilentAsync(scopes);

            // Set the token on the request
            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.Token);
        }
예제 #21
0
        public async Task <AuthResult> GetTokenByContextAsync(AuthenticationOptions authOptions, IDialogContext context)
        {
            var isValidAuth = IsValidAuth(context, out var authResult);

            if (!isValidAuth)
            {
                return(null);
            }

            try
            {
                var tokenCache = new AuthTokenCache(authResult.TokenCache).GetCacheInstance();
                var client     = new ConfidentialClientApplication(authOptions.ClientId, authOptions.RedirectUrl, new ClientCredential(authOptions.ClientSecret), tokenCache, null);
                var result     = await client.AcquireTokenSilentAsync(authOptions.Scopes, client.GetUser(authResult.UserId));

                authResult = result.ToAuthResult(tokenCache);
                context.StoreAuthResult(authResult, this);
            }
            catch (Exception)
            {
                await context.PostAsync("Your credentials expired and could not be renewed automatically!");

                return(null);
            }

            return(authResult);
        }
예제 #22
0
        /*----------------------------------------------------------------------------
        *       %%Function: GetAccessToken
        *       %%Qualified: WebApp._default.GetAccessToken
        *
        *   Get an access token for accessing the WebApi. This will use
        *   AcquireTokenSilentAsync to get the token. Since this is using the
        *   same tokencache as we populated when the user logged in, we will
        *   get the access token from that cache.
        *  ----------------------------------------------------------------------------*/
        string GetAccessToken()
        {
            // Retrieve the token with the specified scopes
            var        scopes                 = new string[] { Startup.scopeWebApi };
            string     userId                 = GetUserId();
            TokenCache tokenCache             = new MSALSessionCache(userId, GetContextBase()).GetMsalCacheInstance();
            ConfidentialClientApplication cca = new ConfidentialClientApplication(Startup.clientId, Startup.authority,
                                                                                  Startup.redirectUri, new ClientCredential(Startup.appKey), tokenCache, null);

            Task <IEnumerable <IAccount> > tskAccounts = cca.GetAccountsAsync();

            tskAccounts.Wait();

            IAccount account = tskAccounts.Result.FirstOrDefault();

            if (account == null)
            {
                return(null);
            }

            Task <AuthenticationResult> tskResult =
                cca.AcquireTokenSilentAsync(scopes, account, Startup.authority, false);

            tskResult.Wait();
            return(tskResult.Result.AccessToken);
        }
        public async Task <ActionResult> SendMail()
        {
            // try to get token silently
            string     signedInUserID         = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
            TokenCache userTokenCache         = new MSALSessionCache(signedInUserID, this.HttpContext).GetMsalCacheInstance();
            ConfidentialClientApplication cca = new ConfidentialClientApplication(clientId, redirectUri, new ClientCredential(appKey), userTokenCache, null);
            var accounts = await cca.GetAccountsAsync();

            if (accounts.Any())
            {
                string[] scopes = { "Mail.Send" };
                try
                {
                    AuthenticationResult result = await cca.AcquireTokenSilentAsync(scopes, accounts.First());
                }
                catch (MsalUiRequiredException)
                {
                    try
                    {// when failing, manufacture the URL and assign it
                        string authReqUrl = await WebApp.Utils.OAuth2RequestManager.GenerateAuthorizationRequestUrl(scopes, cca, this.HttpContext, Url);

                        ViewBag.AuthorizationRequest = authReqUrl;
                    }
                    catch (Exception ee)
                    {
                        Response.Write(ee.Message);
                    }
                }
            }
            else
            {
            }
            return(View());
        }
예제 #24
0
        public async Task <string> GetAccessToken()
        {
            string accessToken = null;

            // Load the app config from web.config
            string appId       = ConfigurationManager.AppSettings["ida:AppId"];
            string appPassword = ConfigurationManager.AppSettings["ida:AppPassword"];
            string redirectUri = ConfigurationManager.AppSettings["ida:RedirectUri"];

            string[] scopes = ConfigurationManager.AppSettings["ida:AppScopes"]
                              .Replace(' ', ',').Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

            // Get the current user's ID
            string userId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;

            if (!string.IsNullOrEmpty(userId))
            {
                // Get the user's token cache
                SessionTokenCache tokenCache = new SessionTokenCache(userId, HttpContext);

                ConfidentialClientApplication cca = new ConfidentialClientApplication(
                    appId, redirectUri, new ClientCredential(appPassword), tokenCache.GetMsalCacheInstance(), null);

                // Call AcquireTokenSilentAsync, which will return the cached
                // access token if it has not expired. If it has expired, it will
                // handle using the refresh token to get a new one.
                AuthenticationResult result = await cca.AcquireTokenSilentAsync(scopes, cca.Users.First());

                accessToken = result.AccessToken;
            }

            return(accessToken);
        }
        // this is how you get tokens obtained by the OIDC middleware
        //private Task<string> GetAccessTokenAsync()
        //{
        //    return httpContextAccessor.HttpContext.GetTokenAsync("access_token");
        //}

        // this is how you get tokens with MSAL
        private async Task <string> GetAccessTokenAsync()
        {
            try
            {
                var principal = httpContextAccessor.HttpContext.User;

                var tokenCache = new DistributedTokenCache(distributedCache, principal.FindFirst(Constants.ObjectIdClaimType).Value).GetMSALCache();
                var client     = new ConfidentialClientApplication(authOptions.ClientId,
                                                                   authOptions.GetAuthority(principal.FindFirst(Constants.AcrClaimType).Value),
                                                                   "https://app", // it's not really needed
                                                                   new ClientCredential(authOptions.ClientSecret),
                                                                   tokenCache,
                                                                   null);

                var account = (await client.GetAccountsAsync()).FirstOrDefault();

                var result = await client.AcquireTokenSilentAsync(new[] { $"{authOptions.ApiIdentifier}/read_values" },
                                                                  account);

                return(result.IdToken);
            }
            catch (MsalUiRequiredException)
            {
                throw new ReauthenticationRequiredException();
            }
        }
예제 #26
0
        public async Task <ActionResult> CallAPI()
        {
            string responseString = "";

            try
            {
                // Retrieve the token with the specified scopes
                var    scope          = new string[] { Startup.ReadTasksScope };
                string signedInUserID = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;

                TokenCache userTokenCache         = new MSALSessionCache(signedInUserID, this.HttpContext).GetMsalCacheInstance();
                ConfidentialClientApplication cca = new ConfidentialClientApplication(Startup.ClientId, Startup.Authority, Startup.RedirectUri, new ClientCredential(Startup.ClientSecret), userTokenCache, null);

                var user = cca.Users.FirstOrDefault();
                if (user == null)
                {
                    HttpContext.GetOwinContext().Authentication.Challenge();
                    return(null);
                    //throw new Exception("The User is NULL.  Please clear your cookies and try again.  Specifically delete cookies for 'login.microsoftonline.com'.  See this GitHub issue for more details: https://github.com/Azure-Samples/active-directory-b2c-dotnet-webapp-and-webapi/issues/9");
                }

                AuthenticationResult result = await cca.AcquireTokenSilentAsync(scope, user, Startup.Authority, false);

                var myApi           = ConfigurationManager.AppSettings["api:myApiV3Url"];
                var myApiProfileUrl = $"{myApi}my/profile";

                HttpClient         client  = new HttpClient();
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, myApiProfileUrl);

                // Add token to the Authorization header and make the request
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
                HttpResponseMessage response = await client.SendAsync(request);

                // Handle the response
                switch (response.StatusCode)
                {
                case HttpStatusCode.OK:
                    responseString = await response.Content.ReadAsStringAsync();

                    break;

                case HttpStatusCode.Unauthorized:
                    responseString = $"Please sign in again. {response.ReasonPhrase}";
                    break;

                default:
                    responseString = $"Error calling API. StatusCode=${response.StatusCode}";
                    break;
                }
            }
            catch (Exception ex)
            {
                responseString = $"Error calling API: {ex.Message}";
                //return ErrorAction("Error reading to do list: " + ex.Message);
            }

            ViewData["Payload"] = $"{responseString}";
            return(View());
        }
        public async Task <string> GetTokenForApplication()
        {
            var signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
            ConfidentialClientApplication cca = new ConfidentialClientApplication(clientId, redirectUri, new ClientCredential(appKey), new MSALTokenCache(signInUserId));
            var result = await cca.AcquireTokenSilentAsync(scopes);

            return(result.Token);
        }
예제 #28
0
        private async Task <string> GetGraphAccessToken(string userId)
        {
            TokenCache userTokenCache            = new MsalSessionTokenCache(userId, HttpContext).GetMsalCacheInstance();
            ConfidentialClientApplication cc     = new ConfidentialClientApplication(Globals.ClientId, Globals.RedirectUri, new ClientCredential(Globals.ClientSecret), userTokenCache, null);
            AuthenticationResult          result = await cc.AcquireTokenSilentAsync(new string[] { "user.readbasic.all" }, cc.Users.First());

            return(result.AccessToken);
        }
        // Gets an access token and its expiration date. First tries to get the token from the token cache.
        public async Task <string> GetUserAccessTokenAsync()
        {
            // Initialize the cache.
            HttpContextBase context = HttpContext.Current.GetOwinContext().Environment["System.Web.HttpContextBase"] as HttpContextBase;

            //string userId1 = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
            //string userId = "8880"; //"AAAAAAAAAAAAAAAAAAAAAL02Tq7RYbK5-Ai_97RwbP8";
            tokenCache = new EFTokenCache(
                userId, context).GetMsalCacheInstance();
            //var cachedItems = tokenCache.ReadItems(appId); // see what's in the cache

            if (!redirectUri.EndsWith("/"))
            {
                redirectUri = redirectUri + "/";
            }
            string[] segments = context.Request.Path.Split(new char[] { '/' });
            ConfidentialClientApplication cca = new ConfidentialClientApplication(
                appId,
                redirectUri + segments[1],
                new ClientCredential(appSecret),
                tokenCache,
                null);
            bool?isAdmin = HttpContext.Current.Session["IsAdmin"] as bool?;

            string allScopes = nonAdminScopes;

            if (isAdmin.GetValueOrDefault())
            {
                allScopes += " " + adminScopes;
            }
            string[] scopes = allScopes.Split(new char[] { ' ' });
            try
            {
                AuthenticationResult result = await cca.AcquireTokenSilentAsync(scopes, cca.Users.First());

                return(result.AccessToken);
            }

            // Unable to retrieve the access token silently.
            catch (Exception)
            {
                HttpContext.Current.Request.GetOwinContext().Authentication.Challenge(
                    new AuthenticationProperties()
                {
                    RedirectUri = redirectUri + segments[1]
                },
                    OpenIdConnectAuthenticationDefaults.AuthenticationType);

                throw new ServiceException(
                          new Error
                {
                    Code    = GraphErrorCode.AuthenticationFailure.ToString(),
                    Message = Resource.Error_AuthChallengeNeeded,
                });
            }
        }
        // Use MSAL to get a the token we need for the Microsoft Graph
        private async Task <string> GetGraphAccessToken(string userId, string[] scopes)
        {
            TokenCache userTokenCache        = new MsalSessionTokenCache(userId, HttpContext).GetMsalCacheInstance();
            ConfidentialClientApplication cc = new ConfidentialClientApplication(Globals.ClientId, Globals.RedirectUri, new ClientCredential(Globals.ClientSecret), userTokenCache, null);
            var accounts = await cc.GetAccountsAsync();

            AuthenticationResult result = await cc.AcquireTokenSilentAsync(scopes, accounts.First());

            return(result.AccessToken);
        }