예제 #1
0
        public void ValidateClaimsTest()
        {
            // Arrange.
            var expires      = DateTime.UtcNow.AddHours(3);
            var tokenBuilder = new TokenBuilder()
                               .AddIssuer(TestIssuer)
                               .AddAudience(TestAudience)
                               .AddClaims(_claimCollection)
                               .AddSecret(TestSecret)
                               .Expires(expires);

            // Act.
            var token      = tokenBuilder.Build();
            var validToken = token.Validate(TestIssuer, TestAudience, TestSecret);
            var claims1    = token.Claims;
            var claims2    = validToken.Claims;

            // Assert.
            claims1.ForEach((x, i) =>
            {
                var(key, value) = x;
                Assert.Equal(key, claims2.ElementAt(i).Key);
                Assert.Equal(value, claims2.ElementAt(i).Value);
            });

            Assert.Equal("Batman", validToken.Claims.Single(x => x.Key == ClaimTypes.Name).Value);
        }
예제 #2
0
        public IActionResult Authenticate([FromBody] AuthRequest authRequest)
        {
            var user = _userService.FindUserByUsernameAndPassword(authRequest.userName, authRequest.passWord);

            if (user == null)
            {
                return(Unauthorized());
            }
            var token = TokenBuilder.Build(user);

            return(new JsonResult(new AuthResponse(user.id.ToString(), token)));
        }
        public IActionResult Authenticate([FromBody] AuthRequest authRequest)
        {
            var user = _userService.FindUserByUsernameAndPassword(authRequest.Username, authRequest.Password);

            // if (user == null) return Unauthorized();
            if (user == null)
            {
                return(new UnauthorizedResult());              // TODO fixit Unauthorized()
            }
            var token = TokenBuilder.Build(user);

            return(new JsonResult(new AuthResponse(user.Id.ToString(), token)));
        }
예제 #4
0
        public void BuildTokenTest()
        {
            var expires      = DateTime.UtcNow.AddHours(3);
            var tokenBuilder = new TokenBuilder()
                               .AddIssuer(TestIssuer)
                               .AddAudience(TestAudience)
                               .AddClaims(_claimCollection)
                               .Expires(expires);

            var token = tokenBuilder.Build();

            Assert.NotNull(token);
            Assert.Equal(TestIssuer, token.Issuer);
            Assert.Equal(expires.TruncateMilliseconds(), token.Expires);
        }
예제 #5
0
        /// <summary>
        /// Mails the body.
        /// </summary>
        /// <param name="email">The email.</param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public string MailBody(string email)
        {
            try
            {
                TokenBuilder tokenBuilder = new TokenBuilder();

                var user  = this.m_AccountRepository.Query <User>().Where(a => a.Email == email).FirstOrDefault();
                var token = tokenBuilder.Build(user, DateTime.Now.AddDays(1));
                return("Please reset your password here" + System.Environment.NewLine + URL + token);
            }
            catch (Exception ex)
            {
                var message = string.Format("{0} {1} {2}", ex.InnerException == null ? ex.Message : ex.InnerException.Message, Environment.NewLine, ex.StackTrace);
                throw new Exception(message);
            }
        }
예제 #6
0
        /// <summary>
        /// Edge Auth token generator CLI.
        /// </summary>
        /// <param name="args">Args the CLI arguments</param>
        static void Main(string[] args)
        {
            try
            {
                Arguments.Populate();
                IEnumerable <ArgumentInfo> arguments = Arguments.GetArgumentInfo();
                CheckArguments(args, arguments);

                if (Help != null)
                {
                    PrintHelp(arguments);
                    return;
                }

                if (string.IsNullOrEmpty(ApplicationId) || string.IsNullOrEmpty(Secret))
                {
                    Console.WriteLine("You must provide both \"applicationId\" and \"secret\"");
                    return;
                }

                TokenBuilder tokenBuilder = new TokenBuilder().WithApplicationId(ApplicationId)
                                            .WithSecret(Secret);

                BuildToken(tokenBuilder);

                try
                {
                    string tokenObjectJson = tokenBuilder.GetValue();
                    Console.WriteLine(tokenObjectJson);

                    string token = tokenBuilder.Build();
                    Console.WriteLine(token);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                    return;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
예제 #7
0
        private string GenerateToken(string name)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new InvalidOperationException("Name is not specified.");
            }

            var claims = new ClaimCollection
            {
                { ClaimTypes.Name, name }
            };

            var tokenBuilder = new TokenBuilder()
                               .AddClaims(claims)
                               .AddSecret(_appSettings.Secret)
                               .Expires(DateTime.Now.AddMinutes(60));

            return(tokenBuilder.Build().ToString());
        }
예제 #8
0
        public void ValidateTokenTest()
        {
            // Arrange.
            var expires      = DateTime.UtcNow.AddHours(3);
            var tokenBuilder = new TokenBuilder()
                               .AddIssuer(TestIssuer)
                               .AddAudience(TestAudience)
                               .AddClaims(_claimCollection)
                               .AddSecret(TestSecret)
                               .Expires(expires);

            // Act.
            var token      = tokenBuilder.Build();
            var validToken = token.Validate(TestIssuer, TestAudience, TestSecret);

            // Assert.
            Assert.Equal(token.Issuer, validToken.Issuer);
            Assert.Equal(token.Expires, validToken.Expires);
        }
예제 #9
0
        public void ValidateTokenResponseTest()
        {
            // Arrange.
            var expires      = DateTime.UtcNow.AddHours(3);
            var tokenBuilder = new TokenBuilder()
                               .AddIssuer(TestIssuer)
                               .AddAudience(TestAudience)
                               .AddClaims(_claimCollection)
                               .AddSecret(TestSecret)
                               .Expires(expires);

            // Act.
            var token  = tokenBuilder.Build();
            var result = token.TryValidate(TestIssuer, TestAudience, TestSecret, out var response);

            // Assert.
            Assert.True(result);
            Assert.NotNull(response.Token);
            Assert.Equal(token.Issuer, response.Token.Issuer);
            Assert.Equal(token.Expires, response.Token.Expires);
        }
예제 #10
0
        /// <summary>
        /// Gets a uthenticate.
        /// </summary>
        /// <param name="entity">The entity.</param>
        /// <returns></returns>
        /// <exception cref="BadRequestException">
        /// username/password aren't right
        /// or
        /// username/password aren't right
        /// or
        /// </exception>
        public UserWithTokenModel GetAUthenticate(LoginModel entity)
        {
            try
            {
                TokenBuilder m_tokenBuilder = new TokenBuilder();

                var user = (from u in m_ILoginRepository.Query <User>()
                            where u.Email == entity.Email && !u.IsDeleted
                            select u)
                           .Include(x => x.Roles)
                           .ThenInclude(x => x.Role)
                           .FirstOrDefault();

                if (user == null)
                {
                    throw new BadRequestException("username/password aren't right");
                }

                if (string.IsNullOrWhiteSpace(entity.Password) || user.Password.Decrypt() != entity.Password)
                {
                    throw new BadRequestException("username/password aren't right");
                }

                var expiresIn = DateTime.Now + TokenAuthOption.ExpiresSpan;
                var token     = m_tokenBuilder.Build(user, expiresIn);

                return(new UserWithTokenModel
                {
                    ExpiresAt = expiresIn,
                    Token = token,
                    User = this.MapUser(user)
                });
            }
            catch (Exception ex)
            {
                var message = string.Format("{0} {1} {2}", ex.InnerException == null ? ex.Message : ex.InnerException.Message, Environment.NewLine, ex.StackTrace);
                throw new Exception(message);
            }
        }