Esempio n. 1
0
        public async Task <JwsPayload> Unsign(string jws, string clientId, CancellationToken cancellationToken)
        {
            var client = await _oauthClientRepository.FindOAuthClientById(clientId, cancellationToken);

            if (client == null)
            {
                throw new OAuthException(ErrorCodes.INVALID_CLIENT, string.Format(ErrorMessages.UNKNOWN_CLIENT, clientId));
            }

            return(await Unsign(jws, client));
        }
Esempio n. 2
0
        protected async Task <IActionResult> Authenticate(string returnUrl, string currentAmr, OAuthUser user, bool rememberLogin = false)
        {
            var unprotectedUrl = Unprotect(returnUrl);
            var query          = unprotectedUrl.GetQueries().ToJObj();
            var acrValues      = query.GetAcrValuesFromAuthorizationRequest();
            var clientId       = query.GetClientIdFromAuthorizationRequest();
            var client         = (OpenIdClient)await _oauthClientRepository.FindOAuthClientById(clientId);

            var acr = await _amrHelper.FetchDefaultAcr(acrValues, client);

            string amr;

            if (acr == null || string.IsNullOrWhiteSpace(amr = _amrHelper.FetchNextAmr(acr, currentAmr)))
            {
                var claims = user.ToClaims();
                claims.Add(new Claim(ClaimTypes.AuthenticationInstant, DateTime.UtcNow.ToString()));
                var claimsIdentity  = new ClaimsIdentity(claims, currentAmr);
                var claimsPrincipal = new ClaimsPrincipal(claimsIdentity);
                await HttpContext.SignInAsync(claimsPrincipal, new AuthenticationProperties
                {
                    IsPersistent = rememberLogin
                });

                return(Redirect(unprotectedUrl));
            }

            return(RedirectToAction("Index", "Authenticate", new { area = amr, ReturnUrl = returnUrl }));
        }
Esempio n. 3
0
        public virtual async Task <IActionResult> GetClient(string id)
        {
            var client = await _oauthClientQueryRepository.FindOAuthClientById(id);

            if (client == null)
            {
                return(new NotFoundResult());
            }

            return(new OkObjectResult(client.ToDto()));
        }
        public virtual async Task <IActionResult> GetClient(string id, CancellationToken cancellationToken)
        {
            var client = await _oauthClientQueryRepository.FindOAuthClientById(id, cancellationToken);

            if (client == null)
            {
                return(new NotFoundResult());
            }

            return(new OkObjectResult(client.ToDto(Request.GetAbsoluteUriWithVirtualPath())));
        }
        public async Task <IActionResult> Index(string returnUrl)
        {
            if (string.IsNullOrWhiteSpace(returnUrl))
            {
                return(RedirectToAction("Index", "Errors", new { code = "invalid_request", ReturnUrl = $"{Request.Path}{Request.QueryString}" }));
            }

            try
            {
                var unprotectedUrl  = _dataProtector.Unprotect(returnUrl);
                var query           = unprotectedUrl.GetQueries().ToJObj();
                var uiLocales       = query.GetUILocalesFromAuthorizationRequest();
                var cancellationUrl = query.GetRedirectUriFromAuthorizationRequest();
                if (!string.IsNullOrWhiteSpace(cancellationUrl))
                {
                    var state = query.GetStateFromAuthorizationRequest();
                    if (!string.IsNullOrWhiteSpace(state))
                    {
                        cancellationUrl = QueryHelpers.AddQueryString(cancellationUrl, AuthorizationRequestParameters.State, state);
                    }
                }

                var scopes      = query.GetScopesFromAuthorizationRequest();
                var claims      = query.GetClaimsFromAuthorizationRequest();
                var clientId    = query.GetClientIdFromAuthorizationRequest();
                var oauthClient = await _oauthClientRepository.FindOAuthClientById(clientId);

                var defaultLanguage   = TranslationHelper.SwitchCulture(uiLocales, _oauthHostOptions.DefaultCulture);
                var consent           = _userConsentFetcher.BuildFromAuthorizationRequest(query);
                var claimDescriptions = new List <string>();
                if (claims != null && claims.Any())
                {
                    claimDescriptions = claims.Select(c => c.Name).ToList();
                }

                return(View(new ConsentsIndexViewModel(
                                oauthClient.ClientNames.GetTranslation(defaultLanguage, oauthClient.ClientId),
                                returnUrl,
                                oauthClient.AllowedScopes.Where(c => scopes.Contains(c.Name)).Select(s => s.Name),
                                claimDescriptions,
                                cancellationUrl)));
            }
            catch (CryptographicException)
            {
                return(RedirectToAction("Index", "Errors", new { code = "invalid_request", ReturnUrl = $"{Request.Path}{Request.QueryString}" }));
            }
        }
        private async Task <OAuthClient> Validate(JObject jObj)
        {
            var responseTypes = jObj.GetResponseTypesFromAuthorizationRequest();
            var responseMode  = jObj.GetResponseModeFromAuthorizationRequest();
            var clientId      = jObj.GetClientIdFromAuthorizationRequest();
            var state         = jObj.GetStateFromAuthorizationRequest();
            var redirectUri   = jObj.GetRedirectUriFromAuthorizationRequest();

            if (string.IsNullOrWhiteSpace(clientId))
            {
                throw new OAuthException(ErrorCodes.INVALID_REQUEST, string.Format(ErrorMessages.MISSING_PARAMETER, AuthorizationRequestParameters.ClientId));
            }

            if (string.IsNullOrWhiteSpace(state))
            {
                throw new OAuthException(ErrorCodes.INVALID_REQUEST, string.Format(ErrorMessages.MISSING_PARAMETER, AuthorizationRequestParameters.State));
            }

            var client = await _oauthClientRepository.FindOAuthClientById(clientId);

            if (client == null)
            {
                throw new OAuthException(ErrorCodes.INVALID_CLIENT, string.Format(ErrorMessages.UNKNOWN_CLIENT, clientId));
            }

            var redirectionUrls = await client.GetRedirectionUrls(_httpClientFactory);

            if (!string.IsNullOrWhiteSpace(redirectUri) && !redirectionUrls.Contains(redirectUri))
            {
                throw new OAuthException(ErrorCodes.INVALID_REQUEST, string.Format(ErrorMessages.BAD_REDIRECT_URI, redirectUri));
            }

            if (!string.IsNullOrWhiteSpace(responseMode) && !_oauthResponseModes.Any(o => o.ResponseMode == responseMode))
            {
                throw new OAuthException(ErrorCodes.UNSUPPORTED_RESPONSE_MODE, string.Format(ErrorMessages.BAD_RESPONSE_MODE, responseMode));
            }

            var unsupportedResponseTypes = responseTypes.Where(t => !client.ResponseTypes.Contains(t));

            if (unsupportedResponseTypes.Any())
            {
                throw new OAuthException(ErrorCodes.UNSUPPORTED_RESPONSE_TYPE, string.Format(ErrorMessages.BAD_RESPONSE_TYPES_CLIENT, string.Join(",", unsupportedResponseTypes)));
            }

            return(client);
        }
        public async Task <OAuthClient> Authenticate(AuthenticateInstruction authenticateInstruction, string issuerName, bool isAuthorizationCodeGrantType = false)
        {
            if (authenticateInstruction == null)
            {
                throw new ArgumentNullException(nameof(authenticateInstruction));
            }

            OAuthClient client   = null;
            var         clientId = TryGettingClientId(authenticateInstruction);

            if (!string.IsNullOrWhiteSpace(clientId))
            {
                client = await _oauthClientRepository.FindOAuthClientById(clientId);
            }

            if (client == null)
            {
                throw new OAuthException(ErrorCodes.INVALID_CLIENT, string.Format(ErrorMessages.UNKNOWN_CLIENT, clientId));
            }

            if (isAuthorizationCodeGrantType)
            {
                return(client);
            }

            var tokenEndPointAuthMethod = client.TokenEndPointAuthMethod;
            var handler = _handlers.FirstOrDefault(h => h.AuthMethod == tokenEndPointAuthMethod);

            if (handler == null)
            {
                throw new OAuthException(ErrorCodes.INVALID_CLIENT_AUTH, string.Format(ErrorMessages.UNKNOWN_AUTH_METHOD, tokenEndPointAuthMethod));
            }

            if (!await handler.Handle(authenticateInstruction, client, issuerName).ConfigureAwait(false))
            {
                throw new OAuthException(ErrorCodes.INVALID_CLIENT_AUTH, ErrorMessages.BAD_CLIENT_CREDENTIAL);
            }

            return(client);
        }
        public async Task <IActionResult> Index(string returnUrl, CancellationToken cancellationToken)
        {
            if (string.IsNullOrWhiteSpace(returnUrl))
            {
                return(RedirectToAction("Index", "Errors", new { code = "invalid_request", ReturnUrl = $"{Request.Path}{Request.QueryString}" }));
            }

            try
            {
                var unprotectedUrl  = _dataProtector.Unprotect(returnUrl);
                var query           = unprotectedUrl.GetQueries().ToJObj();
                var cancellationUrl = query.GetRedirectUriFromAuthorizationRequest();
                if (!string.IsNullOrWhiteSpace(cancellationUrl))
                {
                    var state = query.GetStateFromAuthorizationRequest();
                    if (!string.IsNullOrWhiteSpace(state))
                    {
                        cancellationUrl = QueryHelpers.AddQueryString(cancellationUrl, AuthorizationRequestParameters.State, state);
                    }
                }

                var clientId    = query.GetClientIdFromAuthorizationRequest();
                var claims      = query.GetClaimsFromAuthorizationRequest();
                var claimName   = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier);
                var consentId   = claims.Single(c => c.Name == _openbankingApiOptions.OpenBankingApiConsentClaimName).Values.First();
                var oauthClient = await _oauthClientRepository.FindOAuthClientById(clientId, cancellationToken);

                var defaultLanguage   = CultureInfo.DefaultThreadCurrentUICulture != null ? CultureInfo.DefaultThreadCurrentUICulture.Name : _oauthHostOptions.DefaultCulture;
                var claimDescriptions = new List <string>();
                if (claims != null && claims.Any())
                {
                    claimDescriptions = claims.Select(c => c.Name).ToList();
                }

                var consent = await _accountAccessConsentRepository.Get(consentId, cancellationToken);

                if (consent == null)
                {
                    _logger.LogError($"Account Access Consent '{consentId}' doesn't exist");
                    throw new OAuthException(ErrorCodes.INVALID_REQUEST, string.Format(Global.UnknownAccountAccessConsent, consentId));
                }

                var accounts = await _accountRepository.GetBySubject(claimName.Value, cancellationToken);

                return(View(new OpenBankingApiAccountConsentIndexViewModel(
                                returnUrl,
                                cancellationUrl,
                                oauthClient.ClientNames.GetTranslation(defaultLanguage, oauthClient.ClientId),
                                accounts.Select(a => new OpenBankingApiAccountViewModel
                {
                    Id = a.AggregateId,
                    AccountSubType = a.AccountSubType.Name,
                    CashAccounts = a.Accounts.Select(ac => new OpenBankingApiCashAccountViewModel
                    {
                        Identification = ac.Identification,
                        SecondaryIdentification = ac.SecondaryIdentification
                    })
                }).ToList(),
                                new OpenBankingApiConsentAccountViewModel
                {
                    Id = consent.AggregateId,
                    ExpirationDateTime = consent.ExpirationDateTime,
                    Permissions = consent.Permissions.Select(p => p.Name)
                })));
            }
            catch (CryptographicException)
            {
                return(RedirectToAction("Index", "Errors", new { code = "invalid_request", ReturnUrl = $"{Request.Path}{Request.QueryString}" }));
            }
        }