예제 #1
0
        /// <inheritdoc />
        public async Task <IUserActionResult> Create(T user, string password)
        {
            var identityResult = await _userManager.CreateAsync(user, password);

            if (identityResult.Errors.Any())
            {
                return(new DefaultUserActionResultBuilder()
                       .WithIdentityErrors(identityResult.Errors)
                       .Build());
            }

            //Generate tokens for the user
            var jwt          = _jwtHandler.Generate(DefaultJwtHandler.GetDefaultClaims(user.FirstName, user.Email));
            var refreshToken = _refreshTokenGenerator.Generate();

            //Add token to db and update user
            user.RefreshTokens.Add(refreshToken);
            await _userManager.UpdateAsync(user);

            return(new DefaultUserActionResultBuilder()
                   .Success()
                   .WithJwt(jwt)
                   .WithRefreshToken(refreshToken.Token)
                   .Build());
        }
예제 #2
0
        /// <inheritdoc />
        public async Task <IUserActionResult> Authenticate(T user, string password)
        {
            var identityResult = await _userManager.CheckPasswordAsync(user, password);

            if (!identityResult)
            {
                return(new DefaultUserActionResultBuilder()
                       .AddError("Invalid credentials supplied")
                       .Build());
            }

            //Generate tokens for the user
            var jwt          = _jwtHandler.Generate(DefaultJwtHandler.GetDefaultClaims(user.FirstName, user.Email));
            var refreshToken = _refreshTokenGenerator.Generate();

            //Add token to db and update user
            user.RefreshTokens.Add(refreshToken);
            await _userManager.UpdateAsync(user);

            return(new DefaultUserActionResultBuilder()
                   .Success()
                   .WithJwt(jwt)
                   .WithRefreshToken(refreshToken.Token)
                   .Build());
        }
예제 #3
0
        public DefaultJwtHandlerTest()
        {
            var mockConfig = new Mock <IConfiguration>();

            mockConfig.Setup(x => x["Jwt:key"]).Returns("key1234567891011");
            mockConfig.Setup(x => x["Jwt:Issuer"]).Returns("issuer");
            _defaultJwtHandler = new DefaultJwtHandler(mockConfig.Object);
        }
예제 #4
0
        public void TestGetPrincipalFromExpiredTokenCorrect()
        {
            //setup expected
            const string expectedFirstName = "test";
            const string expectedEmail     = "*****@*****.**";
            const string expectedIssAndAud = "issuer";

            //run method
            var token  = _defaultJwtHandler.Generate(DefaultJwtHandler.GetDefaultClaims(expectedFirstName, expectedEmail));
            var result = _defaultJwtHandler.GetPrincipalFromExpiredToken(token);

            Assert.Equal(expectedFirstName, result.FindFirstValue(ClaimTypes.Name));
            Assert.Equal(expectedEmail, result.FindFirstValue(ClaimTypes.Email));
            Assert.Equal(expectedIssAndAud, result.FindFirstValue(JwtRegisteredClaimNames.Iss));
            Assert.Equal(expectedIssAndAud, result.FindFirstValue(JwtRegisteredClaimNames.Aud));
        }
예제 #5
0
        /// <inheritdoc cref="IUserRepository{T}.RefreshToken"/>
        /// <exception cref="ArgumentNullException">if email claim is null.</exception>
        /// <exception cref="SecurityException">if jwt is null or empty</exception>
        public async Task <IUserActionResult> RefreshToken(string jwt, string refreshToken)
        {
            //get the principal
            var principal = _jwtHandler.GetPrincipalFromExpiredToken(jwt);

            if (principal == null)
            {
                return(_defaultTokenRefreshErrors);
            }

            //check if the email in the claim is null, if it is an error occurred.
            var email = principal.FindFirstValue(ClaimTypes.Email);

            if (email == null)
            {
                throw new NullReferenceException("Email was null");
            }

            //find the user by email and their refresh tokens
            var user = await FindByEmailIncludingRefreshTokens(email);

            var storedRefreshToken = user?.RefreshTokens.FirstOrDefault(c => c.Token == refreshToken);

            //if there is no valid RefreshToken return
            if (storedRefreshToken == null || storedRefreshToken.IsExpired())
            {
                return(_defaultTokenRefreshErrors);
            }

            var newJwt          = _jwtHandler.Generate(DefaultJwtHandler.GetDefaultClaims(user.FirstName, user.Email));
            var newRefreshToken = _refreshTokenGenerator.Generate();

            user.RefreshTokens.Remove(storedRefreshToken);
            user.RefreshTokens.Add(newRefreshToken);
            await _userManager.UpdateAsync(user);

            return(new DefaultUserActionResultBuilder()
                   .Success()
                   .WithJwt(newJwt)
                   .WithRefreshToken(newRefreshToken.Token)
                   .Build());
        }