Пример #1
0
        public async Task <string> GetBearerTokenAsync(string scopes)
        {
            try
            {
                var httpContext = _appApplicationServices.GetService <IHttpContextAccessor>().HttpContext;
                var cache       = httpContext.RequestServices.GetService <TokenCacheBase>();
                var context     = _configuration.ConfidentialClientApplication(cache, null);
                var user        = (await context.GetAccountsAsync()).FirstOrDefault();
                if (user == null)
                {
                    throw new ServerException(new ErrorDetail
                    {
                        Message = "Invalid token cache"
                    }, HttpStatusCode.Unauthorized);
                }
                var token = await context.AcquireTokenSilent(scopes.Split(' '), user).ExecuteAsync();

                return(token.CreateAuthorizationHeader());
            }
            catch (Exception ex)
            {
                _appApplicationServices.GetService <ILogger <TokenProvider> >().LogError(ex, ex.Message);
                return(null);
            }
        }
        private static async Task ExchangeAuthCodeWithToken(AuthorizationCodeReceivedNotification notification, TokenProviderConfiguration configuration)
        {
            HttpContext.Current.User = new ClaimsPrincipal(notification.AuthenticationTicket.Identity);
            var c       = HttpContext.Current;
            var cache   = CacheFactoryFunc().Invoke();
            var context = configuration.ConfidentialClientApplication(cache, _debugLogger);
            var user    = await context.AcquireTokenByAuthorizationCode(new[] { configuration.Scope }, notification.Code)
                          .ExecuteAsync();

            HttpContext.Current = c;
        }
Пример #3
0
            private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedContext arg, TokenProviderConfiguration configuration, Func <AuthorizationCodeReceivedContext, Task> handler)
            {
                _logger?.Message("Auth code received...");
                var timer = Stopwatch.StartNew();

                try
                {
                    arg.HttpContext.User = arg.Principal;
                    if (IsMfaRequired(arg, configuration) && !arg.Principal.Claims.Any(c => c.Type == "mfa_required" && c.Value == "true"))
                    {
                        throw new UnauthorizedAccessException("MFA required");
                    }
                    var cache   = arg.HttpContext.RequestServices.GetService <TokenCacheBase>();
                    var context = configuration.ConfidentialClientApplication(cache, s => { _logger?.Message(s); });
                    var user    = await context.AcquireTokenByAuthorizationCode(new[] { configuration.Scope }, arg.ProtocolMessage.Code).ExecuteAsync();

                    _logger?.Message($"exchanging code with access token took: {timer.ElapsedMilliseconds}ms");
                    var policyValidator = arg.HttpContext.RequestServices.GetService <IPolicyValidation>();
                    try
                    {
                        if (policyValidator != null)
                        {
                            var timer2 = Stopwatch.StartNew();
                            var policy = await ValidatePolicies(configuration, policyValidator, arg.ProtocolMessage.RedirectUri ?? configuration.PolicyRedirectUrl ?? configuration.RedirectUrl);

                            timer2.Stop();
                            _logger?.Message($"Policy check took {timer2.ElapsedMilliseconds}ms. ");
                            if (policy.AllPoliciesValid)
                            {
                                _logger?.Message("Policies validated!");
                                AdditionalAuthCodeHandling?.Invoke(arg);
                            }
                            else
                            {
                                _logger?.Message("Not all policies is valid, redirecting to Veracity");
                                arg.Response.Redirect(policy.RedirectUrl); //Getting the redirect url from the error message.
                                arg.HandleResponse();
                            }
                        }
                        else
                        {
                            AdditionalAuthCodeHandling?.Invoke(arg);
                        }
                    }
                    catch (AggregateException aex)
                    {
                        var e = aex.InnerException as ServerException;
                        if (e != null)
                        {
                            HandleServerException(arg, e);
                        }
                    }
                    catch (ServerException ex)
                    {
                        HandleServerException(arg, ex);
                    }
                }
                catch (Exception ex)
                {
                    ex.Log();
                }
                timer.Stop();
                _logger?.Message($"Total on code received  took {timer.ElapsedMilliseconds}ms. ");
                await handler(arg);
            }