示例#1
0
        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 clientId       = query.GetClientIdFromAuthorizationRequest();
                var oauthClient    = await _oauthClientRepository.FindOAuthClientById(clientId, cancellationToken);

                query = await _extractRequestHelper.Extract(Request.GetAbsoluteUriWithVirtualPath(), query, oauthClient);

                var scopes            = query.GetScopesFromAuthorizationRequest();
                var claims            = query.GetClaimsFromAuthorizationRequest();
                var claimDescriptions = new List <string>();
                if (claims != null && claims.Any())
                {
                    claimDescriptions = claims.Select(c => c.Name).ToList();
                }

                return(View(new ConsentsIndexViewModel(
                                _translationHelper.Translate(oauthClient.ClientNames, oauthClient.ClientId),
                                returnUrl,
                                oauthClient.AllowedScopes.Where(c => scopes.Contains(c.Name)).Select(s => s.Name),
                                claimDescriptions)));
            }
            catch (CryptographicException)
            {
                return(RedirectToAction("Index", "Errors", new { code = "invalid_request", ReturnUrl = $"{Request.Path}{Request.QueryString}" }));
            }
        }
示例#2
0
        public async Task <JwsPayload> Unsign(string jws, string clientId, CancellationToken cancellationToken, string errorCode = ErrorCodes.INVALID_REQUEST_OBJECT)
        {
            var client = await _oauthClientRepository.FindOAuthClientById(clientId, cancellationToken);

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

            return(await Unsign(jws, client, errorCode));
        }
        public async Task <JObject> Handle(string clientId, string issuer, CancellationToken cancellationToken)
        {
            var oauthClient = await _oauthClientRepository.FindOAuthClientById(clientId, cancellationToken);

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

            return(ToDto(oauthClient, issuer));
        }
示例#4
0
        protected async Task <IActionResult> Authenticate(string returnUrl, string currentAmr, OAuthUser user, CancellationToken token, bool rememberLogin = false)
        {
            var unprotectedUrl  = Unprotect(returnUrl);
            var query           = unprotectedUrl.GetQueries().ToJObj();
            var acrValues       = query.GetAcrValuesFromAuthorizationRequest();
            var clientId        = query.GetClientIdFromAuthorizationRequest();
            var requestedClaims = query.GetClaimsFromAuthorizationRequest();
            var client          = (OpenIdClient)await _oauthClientRepository.FindOAuthClientById(clientId, token);

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

            string amr;

            if (acr == null || string.IsNullOrWhiteSpace(amr = _amrHelper.FetchNextAmr(acr, currentAmr)))
            {
                var currentDateTime    = DateTime.UtcNow;
                var expirationDateTime = currentDateTime.AddSeconds(_options.CookieAuthExpirationTimeInSeconds);
                var offset             = DateTimeOffset.UtcNow.AddSeconds(_options.CookieAuthExpirationTimeInSeconds);
                var claims             = user.ToClaims();
                var claimsIdentity     = new ClaimsIdentity(claims, currentAmr);
                var claimsPrincipal    = new ClaimsPrincipal(claimsIdentity);
                user.AddSession(expirationDateTime);
                await _oauthUserCommandRepository.Update(user, token);

                await _oauthUserCommandRepository.SaveChanges(token);

                Response.Cookies.Append(_options.SessionCookieName, user.GetActiveSession().SessionId, new CookieOptions
                {
                    Secure   = true,
                    HttpOnly = false,
                    SameSite = SameSiteMode.None
                });
                if (rememberLogin)
                {
                    await HttpContext.SignInAsync(claimsPrincipal, new AuthenticationProperties
                    {
                        IsPersistent = true
                    });
                }
                else
                {
                    await HttpContext.SignInAsync(claimsPrincipal, new AuthenticationProperties
                    {
                        IsPersistent = true,
                        ExpiresUtc   = offset
                    });
                }

                return(Redirect(unprotectedUrl));
            }

            return(RedirectToAction("Index", "Authenticate", new { area = amr, ReturnUrl = returnUrl }));
        }
示例#5
0
        public async Task <bool> Notify(BCAuthorize bcAuthorize, CancellationToken cancellationToken)
        {
            try
            {
                var handler = new HttpClientHandler
                {
                    AllowAutoRedirect = false
                };
                using (var httpClient = _httpClientFactory.GetHttpClient(handler))
                {
                    var jObjBody = new JObject();
                    var context  = new HandlerContext(new HandlerContextRequest(null, null, jObjBody, null, null, null));
                    var user     = await _oauthUserRepository.FindOAuthUserByLogin(bcAuthorize.UserId, cancellationToken);

                    var oauthClient = await _oauthClientRepository.FindOAuthClientById(bcAuthorize.ClientId, cancellationToken);

                    context.SetUser(user);
                    context.SetClient(oauthClient);
                    foreach (var tokenBuilder in _tokenBuilders)
                    {
                        await tokenBuilder.Build(bcAuthorize.Scopes, context, cancellationToken);
                    }

                    var content = new JObject
                    {
                        { BCAuthenticationResponseParameters.AuthReqId, bcAuthorize.Id }
                    };
                    foreach (var resp in context.Response.Parameters)
                    {
                        content.Add(resp.Key, resp.Value);
                    }

                    var httpRequestMessage = new HttpRequestMessage
                    {
                        RequestUri = new Uri(bcAuthorize.NotificationEdp),
                        Content    = new StringContent(content.ToString(), Encoding.UTF8, "application/json")
                    };
                    httpRequestMessage.Headers.Add("Authorization", bcAuthorize.NotificationToken);
                    var httpResult = await httpClient.SendAsync(httpRequestMessage, cancellationToken);

                    httpResult.EnsureSuccessStatusCode();
                    return(true);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.ToString());
                return(false);
            }
        }
示例#6
0
        public async Task <bool> Handle(string clientId, CancellationToken cancellationToken)
        {
            var client = await _oauthClientRepository.FindOAuthClientById(clientId, cancellationToken);

            if (client == null)
            {
                _logger.LogError($"Client cannot be deleted because the client '{clientId}' doesn't exist");
                throw new OAuthClientNotFoundException(ErrorCodes.INVALID_REQUEST, string.Format(ErrorMessages.UNKNOWN_CLIENT, clientId));
            }

            await _oauthClientRepository.Delete(client, cancellationToken);

            await _oauthClientRepository.SaveChanges(cancellationToken);

            _logger.LogInformation($"The client '{clientId}' has been removed");
            return(true);
        }
        private async Task <BaseClient> AuthenticateClient(JObject jObj, CancellationToken cancellationToken)
        {
            var clientId = jObj.GetClientIdFromAuthorizationRequest();

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

            var client = await _oauthClientRepository.FindOAuthClientById(clientId, cancellationToken);

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

            return(client);
        }
示例#8
0
        public async Task <bool> Handle(string clientId, JObject content, CancellationToken cancellationToken)
        {
            var extractedClient = ExtractClient(content);
            var oauthClient     = await _oauthClientRepository.FindOAuthClientById(clientId, cancellationToken);

            if (oauthClient == null)
            {
                _logger.LogError($"The client '{clientId}' doesn't exist");
                throw new OAuthClientNotFoundException(ErrorCodes.INVALID_REQUEST, string.Format(ErrorMessages.UNKNOWN_CLIENT, clientId));
            }

            await UpdateClient(oauthClient, extractedClient, cancellationToken);

            await _oauthClientRepository.Update(oauthClient, cancellationToken);

            await _oauthClientRepository.SaveChanges(cancellationToken);

            return(true);
        }
示例#9
0
        protected async Task <IActionResult> Authenticate(string returnUrl, string currentAmr, OAuthUser user, CancellationToken token, bool rememberLogin = false)
        {
            var unprotectedUrl  = Unprotect(returnUrl);
            var query           = unprotectedUrl.GetQueries().ToJObj();
            var acrValues       = query.GetAcrValuesFromAuthorizationRequest();
            var clientId        = query.GetClientIdFromAuthorizationRequest();
            var requestedClaims = query.GetClaimsFromAuthorizationRequest();
            var client          = (OpenIdClient)await _oauthClientRepository.FindOAuthClientById(clientId, token);

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

            string amr;

            if (acr == null || string.IsNullOrWhiteSpace(amr = _amrHelper.FetchNextAmr(acr, currentAmr)))
            {
                return(await Sign(unprotectedUrl, currentAmr, user, token, rememberLogin));
            }

            return(RedirectToAction("Index", "Authenticate", new { area = amr, ReturnUrl = returnUrl }));
        }
示例#10
0
        public async Task <BaseClient> Authenticate(AuthenticateInstruction authenticateInstruction, string issuerName, CancellationToken cancellationToken, bool isAuthorizationCodeGrantType = false, string errorCode = ErrorCodes.INVALID_CLIENT)
        {
            if (authenticateInstruction == null)
            {
                throw new ArgumentNullException(nameof(authenticateInstruction));
            }

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

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

            if (client == null)
            {
                throw new OAuthException(errorCode, 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(errorCode, string.Format(ErrorMessages.UNKNOWN_AUTH_METHOD, tokenEndPointAuthMethod));
            }

            if (!await handler.Handle(authenticateInstruction, client, issuerName, cancellationToken, errorCode))
            {
                throw new OAuthException(errorCode, ErrorMessages.BAD_CLIENT_CREDENTIAL);
            }

            return(client);
        }
示例#11
0
        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 clientId       = query.GetClientIdFromAuthorizationRequest();
                var oauthClient    = await _oauthClientRepository.FindOAuthClientById(clientId, cancellationToken);

                query = await _extractRequestHelper.Extract(Request.GetAbsoluteUriWithVirtualPath(), query, oauthClient);

                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 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,
                                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}" }));
            }
        }