コード例 #1
0
        public override async Task <UserTokenResponseDTO> Handle(RegisterUserCommand command, CancellationToken token)
        {
            await Task.CompletedTask;

            _logger.LogInformation("Registering new user: "******"user");

            _users.Create(new User(command.username, command.password, command.email));

            var user = _users.GetById(command.username);

            if (user == null)
            {
                _logger.LogInformation("Could not register user: "******"Could not create user");
            }

            user.AddDomainEvent(new UserCreatedDomainEvent()
            {
                Username = command.username
            });

            _users.Update(user);

            return(new UserTokenResponseDTO()
            {
                token = jwt
            });
        }
コード例 #2
0
ファイル: JwtGeneratorTests.cs プロジェクト: arborQ/Alpaki
        public void JwtGenerator_Generate_ReturnsToken(long userId, UserRoleEnum role)
        {
            // Arrange
            var tokenHandler = new JwtSecurityTokenHandler();
            var hmac         = new HMACSHA256();
            var key          = Convert.ToBase64String(hmac.Key);

            var configuration = Substitute.For <IOptions <JwtConfig> >();

            configuration.Value.Returns(new JwtConfig {
                SeacretKey = key
            });

            var sut = new JwtGenerator(configuration, _systemClock);

            // Act
            var token = sut.Generate(new User {
                UserId = userId, Role = role
            });

            // Assert
            Assert.NotNull(token);
            var securityToken = tokenHandler.ReadJwtToken(token);

            Assert.Contains(securityToken.Claims, c => c.Type == "unique_name" && c.Value == userId.ToString());
            Assert.Contains(securityToken.Claims, c => c.Type == "role" && c.Value == ((int)role).ToString());
            //Assert.DoesNotContain(securityToken.Claims, c => c.Type == "exp");
        }
コード例 #3
0
        public static ClientAssertion CreateWithEnterpriseCertificate(string clientId, string tokenEndpointUrl, string thumbprint)
        {
            var certificate = CertificateStore.GetCertificateByThumbprint(thumbprint);
            var securityKey = new X509SecurityKey(certificate);
            var assertion   = JwtGenerator.Generate(clientId, tokenEndpointUrl, JwtGenerator.SigningMethod.X509EnterpriseSecurityKey, securityKey, SecurityAlgorithms.RsaSha512);

            return(new ClientAssertion {
                client_assertion = assertion
            });
        }
コード例 #4
0
        public static ClientAssertion CreateWithRsaKeys(string clientId, string tokenEndpointUrl)
        {
            var rsa         = RSAKeyGenerator.GetRsaParameters();
            var securityKey = new RsaSecurityKey(rsa);
            var assertion   = JwtGenerator.Generate(clientId, tokenEndpointUrl, JwtGenerator.SigningMethod.RsaSecurityKey, securityKey, SecurityAlgorithms.RsaSha512);

            return(new ClientAssertion {
                client_assertion = assertion
            });
        }
コード例 #5
0
        public async Task <ActionResult> Register(UserRegistrationDTO request)
        {
            var user = new IdentityUser()
            {
                UserName       = request.Email,
                Email          = request.Email,
                EmailConfirmed = true
            };

            var result = await _userManager.CreateAsync(user, request.Password);

            if (!result.Succeeded)
            {
                return(BadRequest(result.Errors));
            }
            await _signInManager.SignInAsync(user, false);

            return(Ok(await _jwt.Generate(user.Email)));
        }
コード例 #6
0
        public async Task <ActionResult> Register()
        {
            var accessTokenResult = _jwtGenerator.Generate(
                "0",
                "test",
                "*****@*****.**",
                new[] { "Admin" }
                );
            await HttpContext.SignInAsync(accessTokenResult.ClaimsPrincipal,
                                          accessTokenResult.AuthProperties);

            return(RedirectToAction(nameof(HomeController.Index), "Home"));
            // return Ok();
        }
コード例 #7
0
        private string CreateClientAssertion()
        {
            var tokenEndpoint = _settings.Authority + "connect/token";

            var certificate = CertificateStore.GetCertificateByThumbprint(_settings.Thumbprint);

            var securityKey = new X509SecurityKey(certificate);
            var extraClaims = new Dictionary <string, string>();

            extraClaims.Add("helseid://client/claims/orgnr_child_description", "a child description");

            var assertion = JwtGenerator.Generate(
                _settings.ClientIdActorClient,
                tokenEndpoint,
                extraClaims,
                new TimeSpan(0, 1, 0),
                JwtGenerator.SigningMethod.X509EnterpriseSecurityKey,
                securityKey,
                SecurityAlgorithms.RsaSha512);

            return(assertion);
        }
コード例 #8
0
        public override async Task <UserTokenResponseDTO> Handle(LoginUserCommand command, CancellationToken token)
        {
            await Task.CompletedTask;

            _logger.LogInformation("Logging in user: "******"Incorrect password for user: "******"Incorrect username or password");
            }
            else
            {
                var jwt = _jwtGenerator.Generate(command.username, "user");

                return(new UserTokenResponseDTO()
                {
                    token = jwt
                });
            }
        }
コード例 #9
0
        public DifferencesQuery(
            IUserService userService,
            IQuestionService questionService,
            ILikeRecordService likeRecordService,
            IOptions <JwtConfig> options)
        {
            Name = "DifferencesQuery";

            #region User
            FieldAsync <ListGraphType <UserType> >(
                "topUsers",
                resolve: context => userService.GetTopReputationUsers(1));

            FieldAsync <AuthResponseType>(
                "auth",
                arguments: new QueryArguments(
                    new QueryArgument <NonNullGraphType <StringGraphType> > {
                Name = "type"
            },
                    new QueryArgument <NonNullGraphType <StringGraphType> > {
                Name = "code"
            }),
                resolve: context =>
            {
                try
                {
                    var type = context.GetArgument <string>("type");
                    var code = context.GetArgument <string>("code");
                    var user = userService.GetUser(type, code);
                    return(new UserWithTokenModel
                    {
                        User = user,
                        AccessToken = JwtGenerator.Generate(options.Value, user)
                    });
                }
                catch (DefinedException ex)
                {
                    context.Errors.Add(ex);
                    return(null);
                }
            });
            #endregion

            #region Question
            FieldAsync <ListGraphType <QuestionType> >(
                "questions",
                arguments: new QueryArguments(
                    new QueryArgument <NonNullGraphType <CriteriaInputType> > {
                Name = "criteria"
            }
                    ),
                resolve: context =>
            {
                var criteria = context.GetArgument <CriteriaModel>("criteria");
                return(questionService.GetQuestionsByCriteria(criteria));
            });

            FieldAsync <IntGraphType>(
                "questionCount",
                arguments: new QueryArguments(new QueryArgument <NonNullGraphType <CriteriaInputType> > {
                Name = "criteria"
            }),
                resolve: context =>
            {
                var criteria = context.GetArgument <CriteriaModel>("criteria");
                return(questionService.GetQuestionCountByCriteria(criteria));
            });

            FieldAsync <QuestionType>(
                "question",
                arguments: new QueryArguments(
                    new QueryArgument <NonNullGraphType <IntGraphType> > {
                Name = "id"
            }
                    ),
                resolve: context =>
            {
                var questionId = context.GetArgument <int>("id");
                return(questionService.GetQuestion(questionId));
            });

            FieldAsync <ListGraphType <AnswerType> >(
                "questionAnswers",
                arguments: new QueryArguments(
                    new QueryArgument <NonNullGraphType <IntGraphType> > {
                Name = "questionId"
            }
                    ),
                resolve: context =>
            {
                var questionId = context.GetArgument <int>("questionId");
                return(questionService.GetAnswersByQuestionId(questionId));
            });

            FieldAsync <ListGraphType <AnswerLikeType> >(
                "answerLikedByQuestion",
                arguments: new QueryArguments(
                    new QueryArgument <NonNullGraphType <IntGraphType> > {
                Name = "questionId"
            }
                    ),
                resolve: context =>
            {
                var questionId = context.GetArgument <int>("questionId");
                return(likeRecordService.GetRecordsByQuestion(questionId));
            });

            FieldAsync <AnswerLikeType>(
                "answerLikedByAnswer",
                arguments: new QueryArguments(
                    new QueryArgument <NonNullGraphType <IntGraphType> > {
                Name = "answerId"
            }
                    ),
                resolve: context =>
            {
                var answerId = context.GetArgument <int>("answerId");
                return(likeRecordService.GetRecordByAnswer(answerId));
            });
            #endregion

            FieldAsync <ListGraphType <CategoryGroupType> >(
                "categoryDefinition",
                resolve: context => CategoryDefinition.CategoryGroups);
        }