Ejemplo n.º 1
0
        public async Task <IActionResult> Login([FromBody] UserLoginViewModel model)
        {
            User user = await DataContext.Store.GetOneAsync <User>(u => u.UserName.ToLower() == model.Username.ToLower());

            if (user == null)
            {
                return(NotFound());
            }

            bool valid = await UserManager.CheckPasswordAsync(user, model.Password);

            if (!valid)
            {
                return(Unauthorized());
            }

            return(Ok(new AccessTokenModel()
            {
                AccessToken = await JwtFactory.GenerateToken(user)
            }));
        }
Ejemplo n.º 2
0
        public async Task WhenGeneratingJwtTokenItShouldReturnAWellFormatedOne()
        {
            var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("ASecretKeyGoesHere......"));

            var jwtOptions = new JwtOptions
            {
                Audience           = "",
                Issuer             = "",
                SigningCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256),
                Subject            = "ASubject",
                ValidFor           = new TimeSpan(0, 0, 7200)
            };

            var jwtOptionsnMock = new Mock <IOptions <JwtOptions> >();

            jwtOptionsnMock.Setup(p => p.Value).Returns(jwtOptions);

            var jwtFactory = new JwtFactory(jwtOptionsnMock.Object);

            var identity = jwtFactory.GenerateClaimsIdentity("AUserName", "Id");


            var jwt = await TokenGenerator.GenerateJwt(
                identity,
                jwtFactory,
                "AUserName",
                jwtOptions,
                new JsonSerializerSettings { Formatting = Formatting.Indented });

            Assert.NotNull(jwt);
            dynamic jsonObject = JObject.Parse(jwt);

            string id        = (string)jsonObject.id;
            string authToken = (string)jsonObject.authToken;
            string expiresIn = (string)jsonObject.expiresIn;

            Assert.Equal("Id", id);
            Assert.NotNull(authToken);
            Assert.Equal("7200", expiresIn);
        }
Ejemplo n.º 3
0
        public void JWT_Test_05_CreateToken()
        {
            using (JwtFactory Factory = new JwtFactory(Encoding.ASCII.GetBytes("secret")))
            {
                DateTime Expires  = new DateTime(2018, 1, 1, 0, 0, 0, DateTimeKind.Utc);
                string   TokenStr = Factory.Create(
                    new KeyValuePair <string, object>("sub", "test user"),
                    new KeyValuePair <string, object>("exp", Expires));
                JwtToken Token = new JwtToken(TokenStr);

                Assert.AreEqual("JWT", Token.Type);
                Assert.AreEqual(JwtAlgorithm.HS256, Token.Algorithm);

                Assert.AreEqual(true, Token.TryGetClaim("sub", out object Subject));
                Assert.AreEqual("test user", Subject);
                Assert.AreEqual("test user", Token.Subject);

                Assert.AreEqual(Expires, Token.Expiration);

                Assert.AreEqual(true, Factory.IsValid(Token));
            }
        }
Ejemplo n.º 4
0
        public void JWT_Test_05_CreateToken()
        {
            using (JwtFactory Factory = new JwtFactory(Encoding.ASCII.GetBytes("secret")))
            {
                DateTime Expires  = DateTime.Today.ToUniversalTime().AddDays(2);
                string   TokenStr = Factory.Create(
                    new KeyValuePair <string, object>("sub", "test user"),
                    new KeyValuePair <string, object>("exp", Expires));
                JwtToken Token = new JwtToken(TokenStr);

                Assert.AreEqual("JWT", Token.Type);
                Assert.IsTrue(Token.Algorithm is HmacSha256);

                Assert.AreEqual(true, Token.TryGetClaim("sub", out object Subject));
                Assert.AreEqual("test user", Subject);
                Assert.AreEqual("test user", Token.Subject);

                Assert.AreEqual(Expires, Token.Expiration);

                Assert.AreEqual(true, Factory.IsValid(Token));
            }
        }
Ejemplo n.º 5
0
        public void JWT_Test_04_Validate_InvalidToken()
        {
            JwtToken Token = new JwtToken("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ");

            Assert.AreEqual("JWT", Token.Type);
            Assert.IsTrue(Token.Algorithm is HmacSha256);

            Assert.AreEqual(true, Token.TryGetClaim("sub", out object Subject));
            Assert.AreEqual("1234567890", Subject);
            Assert.AreEqual("1234567890", Token.Subject);

            Assert.AreEqual(true, Token.TryGetClaim("name", out object Name));
            Assert.AreEqual("John Doe", Name);

            Assert.AreEqual(true, Token.TryGetClaim("admin", out object Admin));
            Assert.AreEqual(true, Admin);

            using (JwtFactory Factory = new JwtFactory(Encoding.ASCII.GetBytes("wrong secret")))
            {
                Assert.AreEqual(false, Factory.IsValid(Token));
            }
        }
        public void CanEncodeToken()
        {
            // arrange
            var token            = Guid.NewGuid().ToString();
            var jwtIssuerOptions = new JwtIssuerOptions
            {
                Issuer             = "",
                Audience           = "",
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.ASCII.GetBytes("secretkey")), SecurityAlgorithms.HmacSha256)
            };

            var mockJwtTokenHandler = new Mock <IJwtTokenHandler>();

            mockJwtTokenHandler.Setup(handler => handler.WriteToken(It.IsAny <JwtSecurityToken>())).Returns(token);
            var jwtFactory = new JwtFactory(mockJwtTokenHandler.Object, Options.Create(jwtIssuerOptions));

            // act
            var result = jwtFactory.EncodeToken("userName");

            // assert
            Assert.Equal(token, result);
        }
            public async Task <Result> Handle(Command request, CancellationToken cancellationToken)
            {
                var bearerToken = await _httpContextAccessor.HttpContext.GetTokenAsync("access_token");

                var principal = TryGetPrincipalFromToken(bearerToken);

                if (principal != null)
                {
                    var username = principal.FindFirst(ClaimTypes.NameIdentifier).Value;
                    var user     = await _userManager.FindByNameAsync(username);

                    if (user != null && TokenMatchesAndNotExpired(user, request.RefreshToken))
                    {
                        // TODO: Use IdentityServer4
                        var jwtToken = JwtFactory.Create(user);
                        await SaveRefreshToken(user, jwtToken.RefreshToken, DateTime.Now.AddDays(1));

                        return(new Result(true, jwtToken));
                    }
                }

                return(new Result(false));
            }
Ejemplo n.º 8
0
            public async Task <CommandResult> Handle(Command request, CancellationToken cancellationToken)
            {
                var user = await _userManager.FindByNameAsync(request.UserName);

                if (user == null)
                {
                    return(new CommandResult(false));
                }

                var passwordIsValid = await _userManager.CheckPasswordAsync(user, request.Password);

                if (!passwordIsValid)
                {
                    return(new CommandResult(false));
                }

                // TODO: Use IdentityServer4
                var jwtToken = JwtFactory.Create(user);

                await SaveRefreshToken(user, jwtToken.RefreshToken, DateTime.Now.AddDays(1));

                return(new CommandResult(true, jwtToken));
            }
        private CommandRequest BuildRequest(string asid, string resourceId, string nhsNumber, string custodianOrgCode, string typeCode, string jwtOrgCode, HttpMethod method, HttpContent content)
        {
            var command = new CommandRequest
            {
                BaseUrl          = $"{(_spineSettings.NrlsUseSecure ? _spineSettings.NrlsSecureServerUrl : _spineSettings.NrlsServerUrl)}",
                ResourceId       = resourceId,
                ResourceType     = ResourceType.DocumentReference,
                SearchParams     = GetParams(nhsNumber, custodianOrgCode, resourceId, typeCode),
                Method           = method,
                Content          = content,
                UseSecure        = _spineSettings.NrlsUseSecure,
                ClientThumbprint = ClientSettings(asid)?.Thumbprint,
                ServerThumbprint = _spineSettings.SpineThumbprint
            };

            var jwt = JwtFactory.Generate(method == HttpMethod.Get ? JwtScopes.Read : JwtScopes.Write, jwtOrgCode, "fakeRoleId", asid, command.FullUrl.AbsoluteUri, SystemUrlBase);

            command.Headers.Add(HeaderNames.Authorization, $"Bearer {jwt}");
            command.Headers.Add(FhirConstants.HeaderFromAsid, asid);
            command.Headers.Add(FhirConstants.HeaderToAsid, _spineSettings.SpineAsid);

            return(command);
        }
Ejemplo n.º 10
0
        private async Task <ApiResponseType> PostDomesticConsent <ApiRequestType, ApiResponseType>(
            JwtFactory jwtFactory,
            SoftwareStatementProfile softwareStatementProfile,
            ApiRequestType consent,
            ApiProfile apiProfile,
            BankClientProfile bankClientProfile,
            TokenEndpointResponse tokenEndpointResponse)
            where ApiRequestType : class
            where ApiResponseType : class
        {
            string jwt = jwtFactory.CreateJwt(
                profile: softwareStatementProfile,
                claims: consent,
                useOpenBankingJwtHeaders: true);

            string[]          jwsComponents = jwt.Split('.');
            string            jwsSignature  = $"{jwsComponents[0]}..{jwsComponents[2]}";
            UriBuilder        ub            = new UriBuilder(new Uri(apiProfile.BaseUrl + "/domestic-payment-consents"));
            string            payloadJson   = JsonConvert.SerializeObject(consent);
            List <HttpHeader> headers       = new List <HttpHeader>
            {
                new HttpHeader(name: "x-fapi-financial-id", value: bankClientProfile.XFapiFinancialId),
                new HttpHeader(name: "Authorization", value: "Bearer " + tokenEndpointResponse.AccessToken),
                new HttpHeader(name: "x-idempotency-key", value: Guid.NewGuid().ToString()),
                new HttpHeader(name: "x-jws-signature", value: jwsSignature)
            };

            return(await new HttpRequestBuilder()
                   .SetMethod(HttpMethod.Post)
                   .SetUri(ub.Uri)
                   .SetHeaders(headers)
                   .SetContentType("application/json")
                   .SetContent(payloadJson)
                   .Create()
                   .RequestJsonAsync <ApiResponseType>(client: _apiClient, requestContentIsJson: true));
        }
Ejemplo n.º 11
0
        public async void GenerateEncodedToken_GivenValidInputs_ReturnsExpectedTokenData()
        {
            // arrange
            var token            = Guid.NewGuid().ToString();
            var id               = Guid.NewGuid().ToString();
            var jwtIssuerOptions = new JwtIssuerOptions
            {
                Issuer             = "",
                Audience           = "",
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.ASCII.GetBytes("secret_key")), SecurityAlgorithms.HmacSha256)
            };

            var mockJwtTokenHandler = new Mock <IJwtHandler>();

            mockJwtTokenHandler.Setup(handler => handler.WriteToken(It.IsAny <JwtSecurityToken>())).Returns(token);

            var jwtFactory = new JwtFactory(mockJwtTokenHandler.Object, Options.Create(jwtIssuerOptions));

            // act
            var result = await jwtFactory.GenerateEncodedToken(id, "userName");

            // assert
            Assert.Equal(token, result);
        }
Ejemplo n.º 12
0
        private static void Main(string[] args)
        {
            // Create a random key using a random number generator. This would be the
            //  secret key shared by sender and receiver.
            byte[] privateKey = new Byte[64];
            using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
            {
                // The array is now filled with cryptographically strong random bytes.
                rng.GetBytes(privateKey);

                Debug.WriteLine($"Private key: {Base64Url.Encode(privateKey)}");

                var payload = new Dictionary <string, string>();
                payload.Add("uid", "Glen");

                var jwtFactory = new JwtFactory();
                var jwt        = jwtFactory.Create(JwtAuthentication.HashAlgorithm.HS256, privateKey, payload);

                Console.WriteLine($"JWT: {jwt}");
                Debug.WriteLine($"JWT: {jwt}");

                Console.ReadLine();
            }
        }
Ejemplo n.º 13
0
        public async Task Should_ReturnJwtToken_WhenUser_Provided()
        {
            // Arrange
            var options = Options.Create(new JwtIssuerOptions());

            var userMock = new Mock <ApplicationUser>();

            // needed for non virtual property
            userMock.SetupAllProperties();
            userMock.Object.FirstName = "Test";

            // asp.net user virtual properties
            userMock.Setup(m => m.Id).Returns("001");
            userMock.Setup(m => m.Email).Returns("*****@*****.**");
            userMock.Setup(m => m.UserName).Returns("*****@*****.**");

            var sut = new JwtFactory(options);

            // Act
            var token = await sut.GenerateToken(userMock.Object);

            // Assert
            token.ShouldNotBeNull();
        }
        private CommandRequest BuildRequest(string asid, string jwtOrgCode, string providerOds)
        {
            var consumer = _sdsService.GetFor(asid);
            var provider = _sdsService.GetFor(providerOds, FhirConstants.ReadBinaryInteractionId);

            if (consumer == null)
            {
                throw new HttpFhirException("Local system not registered with SDS.", OperationOutcomeFactory.CreateGenericError($"Unknown ASID {asid}"), HttpStatusCode.BadRequest);
            }

            if (provider == null)
            {
                throw new HttpFhirException("External system not registered with SDS.", OperationOutcomeFactory.CreateGenericError($"Unknown ODS code {providerOds}"), HttpStatusCode.BadRequest);
            }

            var command = new CommandRequest
            {
                BaseUrl          = $"{(_spineSettings.SspUseSecure ? _spineSettings.SspSecureServerUrl : _spineSettings.SspServerUrl)}",
                ResourceType     = ResourceType.Binary,
                Method           = HttpMethod.Get,
                UseSecure        = _spineSettings.SspUseSecure,
                ClientThumbprint = consumer?.Thumbprint,
                ServerThumbprint = _spineSettings.SspSslThumbprint,
                RegenerateUrl    = false
            };

            var jwt = JwtFactory.Generate(JwtScopes.Read, jwtOrgCode, "fakeRoleId", asid, command.FullUrl.AbsoluteUri, SystemUrlBase, "*");

            command.Headers.Add(HeaderNames.Authorization, $"Bearer {jwt}");
            command.Headers.Add(FhirConstants.HeaderSspFrom, consumer?.Asid); // GET consumer ASID
            command.Headers.Add(FhirConstants.HeaderSspTo, provider?.Asid);   // GET provider asid
            command.Headers.Add(FhirConstants.HeaderSspInterationId, FhirConstants.ReadBinaryInteractionId);
            command.Headers.Add(FhirConstants.HeaderSspTraceId, Guid.NewGuid().ToString());

            return(command);
        }
Ejemplo n.º 15
0
 public AuthController(UserManager <AppUser> userManager, JwtFactory jwtFactory, IOptions <JwtIssuerOptions> jwtOptions)
 {
     _userManager = userManager;
     _jwtFactory  = jwtFactory;
     _jwtOptions  = jwtOptions.Value;
 }
Ejemplo n.º 16
0
 public AuthService(ThreadContext context, IMapper mapper, JwtFactory jwtFactory) : base(context, mapper)
 {
     _jwtFactory = jwtFactory;
 }
Ejemplo n.º 17
0
        public async Task <PaymentConsentResponse> CreateAsync(DomesticPaymentConsent consent)
        {
            consent.ArgNotNull(nameof(consent));

            // Load relevant objects
            ApiProfile apiProfile = await _apiProfileRepo.GetAsync(consent.ApiProfileId)
                                    ?? throw new KeyNotFoundException("The API Profile does not exist.");

            BankClientProfile bankClientProfile = await _bankClientProfileRepo.GetAsync(apiProfile.BankClientProfileId)
                                                  ?? throw new KeyNotFoundException(
                                                            "The Bank Client Profile does not exist.");

            SoftwareStatementProfile softwareStatementProfile =
                _softwareStatementProfileService.GetSoftwareStatementProfile(
                    bankClientProfile.SoftwareStatementProfileId);

            // Get client credentials grant (we will not cache token for now but simply use to POST consent)
            TokenEndpointResponse tokenEndpointResponse =
                await PostClientCredentialsGrant(scope : "payments", client : bankClientProfile);

            // TODO: validate the response???

            // Create new Open Banking consent by posting JWT
            JwtFactory jwtFactory = new JwtFactory();
            OBWriteDomesticConsentResponse4 consentResponse;

            switch (apiProfile.ApiVersion)
            {
            case ApiVersion.V3P1P1:
                OBWriteDomesticConsent2 newDomesticConsent =
                    _mapper.Map <OBWriteDomesticConsent2>(consent.DomesticConsent);
                OBWriteDomesticConsentResponse2 rawConsentResponse = await
                                                                     PostDomesticConsent <OBWriteDomesticConsent2, OBWriteDomesticConsentResponse2>(
                    jwtFactory : jwtFactory,
                    softwareStatementProfile : softwareStatementProfile,
                    consent : newDomesticConsent,
                    apiProfile : apiProfile,
                    bankClientProfile : bankClientProfile,
                    tokenEndpointResponse : tokenEndpointResponse);

                consentResponse = _mapper.Map <OBWriteDomesticConsentResponse4>(rawConsentResponse);
                break;

            case ApiVersion.V3P1P2:
                throw new ArgumentOutOfRangeException();

            case ApiVersion.V3P1P4:
                consentResponse = await
                                  PostDomesticConsent <OBWriteDomesticConsent4, OBWriteDomesticConsentResponse4>(
                    jwtFactory : jwtFactory,
                    softwareStatementProfile : softwareStatementProfile,
                    consent : consent.DomesticConsent,
                    apiProfile : apiProfile,
                    bankClientProfile : bankClientProfile,
                    tokenEndpointResponse : tokenEndpointResponse);

                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            // Generate URL for user auth
            string consentId   = consentResponse.Data.ConsentId;
            string redirectUrl = softwareStatementProfile.DefaultFragmentRedirectUrl;

            if (redirectUrl == "")
            {
                redirectUrl = bankClientProfile.BankClientRegistrationClaims.RedirectUris[0];
            }

            OAuth2RequestObjectClaims oAuth2RequestObjectClaims = Factories.CreateOAuth2RequestObjectClaims(
                openBankingClient: bankClientProfile,
                redirectUrl: redirectUrl,
                scope: new[] { "openid", "payments" },
                intentId: consentId);
            string requestObjectJwt = jwtFactory.CreateJwt(
                profile: softwareStatementProfile,
                claims: oAuth2RequestObjectClaims,
                useOpenBankingJwtHeaders: false);
            Dictionary <string, string> keyValuePairs = new Dictionary <string, string>
            {
                { "response_type", oAuth2RequestObjectClaims.ResponseType },
                { "client_id", oAuth2RequestObjectClaims.ClientId },
                { "redirect_uri", oAuth2RequestObjectClaims.RedirectUri },
                { "scope", oAuth2RequestObjectClaims.Scope },
                { "request", requestObjectJwt },
                { "nonce", oAuth2RequestObjectClaims.Nonce },
                { "state", oAuth2RequestObjectClaims.State }
            };
            string queryString = keyValuePairs.ToUrlEncoded();
            string authUrl     = bankClientProfile.OpenIdConfiguration.AuthorizationEndpoint + "?" + queryString;

            // Create and store persistent object
            string          domesticConsentId = Guid.NewGuid().ToString();
            DomesticConsent value             = new DomesticConsent
            {
                State = oAuth2RequestObjectClaims.State,
                SoftwareStatementProfileId = bankClientProfile.SoftwareStatementProfileId,
                IssuerUrl              = bankClientProfile.IssuerUrl,
                ApiProfileId           = apiProfile.Id,
                ObWriteDomesticConsent = consent.DomesticConsent,
                TokenEndpointResponse  = null,
                Id     = domesticConsentId,
                BankId = consentId
            };
            await _domesticConsentRepo.UpsertAsync(value);

            await _dbMultiEntityMethods.SaveChangesAsync();

            return(new PaymentConsentResponse
            {
                AuthUrl = authUrl,
                ConsentId = domesticConsentId
            });
        }
        public NextLevelBJJQuery(IUserRepository userRepository, IPostRepository postRepository, ICompetitionRepository competitionRepository)
        {
            _mapper     = new Mapper();
            _jwtFactory = new JwtFactory();
            Name        = "Query";

            Field <JsonWebTokenType>(
                "getToken",
                description: "Get new token for provided carnetId",
                arguments: new QueryArguments(
                    new QueryArgument <NonNullGraphType <StringGraphType> > {
                Name = "carnetId", Description = "Your carnet Id"
            }
                    ),
                resolve: ctx =>
            {
                var carnetId = ctx.GetArgument <string>("carnetId");
                var token    = _jwtFactory.BuildToken(carnetId);

                return(new JsonWebToken {
                    Token = token
                });
            });

            Field <UserType>(
                "user",
                description: "Get student in the Next Level BJJ club by his guid",
                arguments: new QueryArguments(
                    new QueryArgument <NonNullGraphType <StringGraphType> > {
                Name = "userGuid", Description = "Guid of the user"
            }
                    ),
                resolve: ctx =>
            {
                var stringGuid = ctx.GetArgument <string>("userGuid");
                var user       = userRepository.GetUserByGuid(stringGuid);

                var mapped = _mapper.Map(user.Result);

                return(mapped);
            }
                );

            Field <PostType>(
                "post",
                description: "Get post by its guid",
                arguments: new QueryArguments(
                    new QueryArgument <NonNullGraphType <StringGraphType> > {
                Name = "postGuid", Description = "Guid of the post"
            }
                    ),
                resolve: ctx =>
            {
                var stringGuid = ctx.GetArgument <string>("postGuid");

                var post = postRepository.Get(stringGuid);

                var mapped = _mapper.Map(post.Result);

                return(mapped);
            }
                );

            Field <ListGraphType <PostType> >(
                "posts",
                description: "Get all posts",
                resolve: ctx =>
            {
                var posts = postRepository.GetAll();

                var mapped = _mapper.Map(posts.Result);

                return(mapped);
            });

            Field <ListGraphType <CompetitionType> >(
                "competitions",
                description: "Get all competitions",
                arguments: new QueryArguments(
                    new QueryArgument <OriginalDateGraphType>()
            {
                Name = "competitionDate", Description = "Starting date of the competition"
            }
                    ),
                resolve: ctx =>
            {
                Task <List <Core.Models.Competition> > competitions;
                var date = ctx.GetArgument <DateTime?>("competitionDate", null);

                if (date != null)
                {
                    competitions = competitionRepository.GetCompetitionsForDate(date);
                }
                else
                {
                    competitions = competitionRepository.GetAll();
                }

                var mapped = _mapper.Map(competitions.Result);

                return(mapped);
            });
        }
Ejemplo n.º 19
0
        private void TransformJwtFactory(SmartAppInfo manifest)
        {
            var template = new JwtFactory(manifest);

            _writingService.WriteFile(Path.Combine(_context.BasePath, template.OutputPath), template.TransformText());
        }
 public ExternalAuthController(IOptions <FacebookAuthSettings> fbAuthSettingsAccessor, UserManager <AppUser> userManager, AppUserContext appDbContext, JwtFactory jwtFactory, IOptions <JwtIssuerOptions> jwtOptions)
 {
     _fbAuthSettings = fbAuthSettingsAccessor.Value;
     _userManager    = userManager;
     _appDbContext   = appDbContext;
     _jwtFactory     = jwtFactory;
     _jwtOptions     = jwtOptions.Value;
 }
        public async Task <BankClientProfileResponse> CreateAsync(BankClientProfilePublic bankClientProfile)
        {
            bankClientProfile.ArgNotNull(nameof(bankClientProfile));

            // Load relevant objects
            SoftwareStatementProfile softwareStatementProfile =
                _softwareStatementProfileService.GetSoftwareStatementProfile(
                    bankClientProfile.SoftwareStatementProfileId);

            // STEP 1
            // Compute claims associated with Open Banking client

            // Get OpenID Connect configuration info
            OpenIdConfiguration openIdConfiguration =
                await GetOpenIdConfigurationAsync(bankClientProfile.IssuerUrl);

            new OpenBankingOpenIdConfigurationResponseValidator().Validate(openIdConfiguration)
            .RaiseErrorOnValidationError();

            // Create claims for client reg
            OpenBankingClientRegistrationClaims registrationClaims = Factories.CreateRegistrationClaims(
                issuerUrl: bankClientProfile.IssuerUrl,
                sProfile: softwareStatementProfile,
                concatScopes: false);
            BankClientRegistrationClaimsOverrides registrationClaimsOverrides =
                bankClientProfile.BankClientRegistrationClaimsOverrides;

            if (!(registrationClaimsOverrides is null))
            {
                if (!(registrationClaimsOverrides.RequestAudience is null))
                {
                    registrationClaims.Aud = registrationClaimsOverrides.RequestAudience;
                }
            }

            BankClientRegistrationClaims persistentRegistrationClaims =
                _mapper.Map <BankClientRegistrationClaims>(registrationClaims);

            // STEP 2
            // Check for existing Open Banking client for issuer URL
            // If we have an Open Banking client with the same issuer URL we will check if the claims match.
            // If they do, we will re-use this client.
            // Otherwise we will return an error as only support a single client per issuer URL at present.
            IQueryable <BankClientProfile> clientList = await _bankClientProfileRepo
                                                        .GetAsync(c => c.IssuerUrl == bankClientProfile.IssuerUrl);

            BankClientProfile existingClient = clientList
                                               .SingleOrDefault();

            if (existingClient is object)
            {
                if (existingClient.BankClientRegistrationClaims != persistentRegistrationClaims)
                {
                    throw new Exception(
                              "There is already a client for this issuer URL but it cannot be re-used because claims are different.");
                }
            }

            // STEP 3
            // Create new Open Banking client by posting JWT
            BankClientProfile client;

            if (existingClient is null)
            {
                JwtFactory jwtFactory = new JwtFactory();
                string     jwt        = jwtFactory.CreateJwt(
                    profile: softwareStatementProfile,
                    claims: registrationClaims,
                    useOpenBankingJwtHeaders: false);

                OpenBankingClientRegistrationResponse registrationResponse = await new HttpRequestBuilder()
                                                                             .SetMethod(HttpMethod.Post)
                                                                             .SetUri(openIdConfiguration.RegistrationEndpoint)
                                                                             .SetContent(jwt)
                                                                             .SetContentType("application/jwt")
                                                                             .Create()
                                                                             .RequestJsonAsync <OpenBankingClientRegistrationResponse>(
                    client: _apiClient,
                    requestContentIsJson: false);

                BankClientRegistrationData openBankingClientResponse = new BankClientRegistrationData
                {
                    ClientId              = registrationResponse.ClientId,
                    ClientIdIssuedAt      = registrationResponse.ClientIdIssuedAt,
                    ClientSecret          = registrationResponse.ClientSecret,
                    ClientSecretExpiresAt = registrationResponse.ClientSecretExpiresAt
                };

                // Create and store Open Banking client
                BankClientProfile newClient = _mapper.Map <BankClientProfile>(bankClientProfile);
                client = await PersistOpenBankingClient(
                    value : newClient,
                    openIdConfiguration : openIdConfiguration,
                    registrationClaims : registrationClaims,
                    openBankingRegistrationData : openBankingClientResponse);

                await _dbMultiEntityMethods.SaveChangesAsync();
            }
            else
            {
                client = existingClient;
            }

            // Return
            return(new BankClientProfileResponse(client));
        }
Ejemplo n.º 22
0
 public UserService(UserRepository repository, SignInManager <User> signInManager, UserManager <User> userManager, JwtFactory jwtFactory, UserConverter userConverter)
 {
     _repository    = repository;
     _signInManager = signInManager;
     _userManager   = userManager;
     _jwtFactory    = jwtFactory;
     _userConverter = userConverter;
 }
Ejemplo n.º 23
0
 public TokenTest()
 {
     factory   = new JwtFactory(new Base64URL(), new TestJsonSerialization(), new HMACSHA256Signaturer(key));
     testToken = factory.GetJwtObject(testHeader, testPayload);
 }
Ejemplo n.º 24
0
 public AuthController(UserManager <ApplicationUser> userManager, JwtFactory jwtFactory, IEmailSender emailSender)
 {
     authDAO = new AuthDAO(userManager, jwtFactory, emailSender);
 }
Ejemplo n.º 25
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IServiceProvider serviceProvider, ILogger logger, IHostApplicationLifetime lifetime)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                //app.UseDatabaseErrorPage();
            }
            else
            {
                app.ConfigureExceptionHandler(logger);
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseCors(options => options.AllowAnyOrigin().AllowAnyHeader());
            //app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseSerilogRequestLogging();

            app.UseAuthentication();
            app.UseRouting();

            app.Use(async(context, next) =>
            {
                // Do work that doesn't write to the Response.
                await next.Invoke();
                // Do logging or other work that doesn't write to the Response.
            });


            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
                endpoints.MapRazorPages();
            });

            // Check for lifetime shutdown working with WebSocket active
            lifetime.ApplicationStopping.Register(() =>
            {
                logger.Information("Wikibot is shutting down.");
            }, true);

            lifetime.ApplicationStopped.Register(() =>
            {
                logger.Information("Wikibot has stopped.");
            }, true);

            var configuration = app.ApplicationServices.GetRequiredService <IConfiguration>();
            var dashboardUrl  = configuration["DashboardURL"];

            app.Use(async(context, next) =>
            {
                var url = context.Request.Path.Value;

                // Redirect to an external URL
                if (url.Contains("/Dashboard") && (context.User.IsInRole("WikiMod") || context.User.IsInRole("BotAdmin")))
                {
                    var jwtOptions = app.ApplicationServices.GetRequiredService <IOptions <JwtIssuerOptions> >();
                    var factory    = new JwtFactory(jwtOptions);
                    var jwtToken   = await factory.GenerateEncodedToken(context.User.Identity.Name, context.User.Identities.First());
                    context.Response.Redirect($"{dashboardUrl}?auth_token= {jwtToken}"); //Update URL
                    return;                                                              // short circuit
                }

                await next();
            });

            // Enable middleware to serve generated Swagger as a JSON endpoint.
            app.UseSwagger();

            // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
            // specifying the Swagger JSON endpoint.
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
            });

            CreateUserRoles(serviceProvider, configuration).Wait();
        }
 private string GenerateToken(string userId, string email) =>
 JwtFactory.GenerateEncodedToken(userId, email, new List <Claim>());
Ejemplo n.º 27
0
 public AuthController(UserManager <KumblerUser> userManager, JwtFactory jwtFactory, IOptions <JwtOptions> jwtOptions)
 {
     this.userManager = userManager;
     this.jwtFactory  = jwtFactory;
     this.jwtOptions  = jwtOptions.Value;
 }
Ejemplo n.º 28
0
 public AuthController(IVeraDbRepository repo, ISmsSender smsSender, IOptions <AuthOptions> authOptions, JwtFactory jwtFactory,
                       ILogger <AuthController> logger, IConfiguration configuration)
 {
     _repo          = repo;
     _smsSender     = smsSender;
     _jwtFactory    = jwtFactory;
     _authOptions   = authOptions.Value;
     _logger        = logger;
     _configuration = configuration;
 }
Ejemplo n.º 29
0
 public AuthController(JwtFactory jwtFactory, IStringLocalizer <Errors> localizer = null)
 {
     _jwtFactory = jwtFactory;
     _localizer  = localizer;
 }
Ejemplo n.º 30
0
        public async Task <string> GenerateJwt(JwtFactory jwtFactory, AppUser user, JwtIssuerOptions jwtOptions, JsonSerializerSettings serializerSettings, List <string> roles)
        {
            var response = await jwtFactory.GenerateEncodedToken(user, roles);

            return(response);
        }