Exemple #1
0
        public async Task When_Passing_Null_Parameters_To_GenerateAccessToken_Then_Exception_Is_Thrown()
        {
            // ARRANGE
            InitializeMockObjects();

            // ACT & ASSERT
            await Assert.ThrowsAsync <ArgumentNullException>(() => _jwtGenerator.GenerateAccessToken(new Client(), null, null));
        }
Exemple #2
0
        public async Task <GrantedToken> GenerateTokenAsync(Client client, string scope, JwsPayload userInformationPayload = null, JwsPayload idTokenPayload = null)
        {
            if (client == null)
            {
                throw new ArgumentNullException(nameof(client));
            }

            if (string.IsNullOrWhiteSpace(scope))
            {
                throw new ArgumentNullException(nameof(scope));
            }

            var expiresIn = (int)await _configurationService.GetTokenValidityPeriodInSecondsAsync(); // 1. Retrieve the expiration time of the granted token.

            var jwsPayload = await _jwtGenerator.GenerateAccessToken(client, scope.Split(' '));      // 2. Construct the JWT token (client).

            var accessToken = await _clientHelper.GenerateIdTokenAsync(client, jwsPayload);

            var refreshTokenId = Encoding.UTF8.GetBytes(Guid.NewGuid().ToString()); // 3. Construct the refresh token.

            return(new GrantedToken
            {
                AccessToken = accessToken,
                RefreshToken = Convert.ToBase64String(refreshTokenId),
                ExpiresIn = expiresIn,
                TokenType = Constants.StandardTokenTypes.Bearer,
                CreateDateTime = DateTime.UtcNow,
                // IDS
                Scope = scope,
                UserInfoPayLoad = userInformationPayload,
                IdTokenPayLoad = idTokenPayload,
                ClientId = client.ClientId
            });
        }
        public async Task <UserDto> Handle(CurrentUserCommand request, CancellationToken cancellationToken)
        {
            var token        = AppContext.Current.Request.Headers[HeaderNames.Authorization].ToString().Replace("Bearer ", "");
            var refreshToken = AppContext.Current.Request.Cookies[Constants.RefreshToken];

            var principal = _jwtGenerator.GetPrincipalFromExpiredToken(token);

            var username = principal.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier)?.Value;

            var user = await _context.Users
                       .Where(x => x.UserName == username)
                       .Include(x => x.RefreshTokens)
                       .SingleOrDefaultAsync(x => x.RefreshTokens.Any(y => y.Token == refreshToken),
                                             cancellationToken);

            if (user == null)
            {
                ThrowUnauthorized();
            }

            var oldToken = user !.RefreshTokens.SingleOrDefault(x => x.Token == refreshToken);

            if (oldToken != null && !oldToken.IsActive)
            {
                ThrowUnauthorized();
            }

            if (oldToken != null)
            {
                oldToken.Revoked = DateTime.UtcNow;
            }

            var newRefreshToken = _jwtGenerator.GenerateRefreshToken(user);

            await _context.RefreshTokens.AddAsync(newRefreshToken, cancellationToken);

            var revokedTokens = user.RefreshTokens.Where(x => x.IsExpired);

            _context.RefreshTokens.RemoveRange(revokedTokens);

            var success = await _context.SaveChangesAsync(cancellationToken) > 0;

            if (success)
            {
                _cookieService.SetTokenCookie(newRefreshToken.Token);

                return(new UserDto
                {
                    UserName = user.UserName,
                    Token = _jwtGenerator.GenerateAccessToken(user),
                    RefreshToken = newRefreshToken.Token
                });
            }

            throw new Exception(Constants.ServerSavingError);
        }
        public async Task <IActionResult> Authenticate(AuthenticationModel authenticationData)
        {
            var user = await _userService.Authenticate(authenticationData);

            if (user == null)
            {
                return(NotFound());
            }
            var token = _jwtGenerator.GenerateAccessToken(user);

            return(Ok(new { token }));
        }
        public async Task <IActionResult> Authenticate([FromBody] LoginModel user)
        {
            var loggedUser = await _accountService.Authenticate(user.Email, user.Password);

            if (loggedUser == null)
            {
                return(BadRequest());
            }
            else
            {
                var token = _jwtGenerator.GenerateAccessToken(loggedUser);
                return(Ok(new { token }));
            }
        }
        public async Task <GrantedToken> GenerateTokenAsync(IEnumerable <string> audiences, IEnumerable <TicketLine> ticketLines, string scope, string issuerName)
        {
            if (audiences == null)
            {
                throw new ArgumentNullException(nameof(audiences));
            }

            if (ticketLines == null)
            {
                throw new ArgumentNullException(nameof(ticketLines));
            }

            if (string.IsNullOrWhiteSpace(scope))
            {
                throw new ArgumentNullException(nameof(scope));
            }

            var expiresIn = await _configurationService.GetRptLifeTime().ConfigureAwait(false);                                      // 1. Retrieve the expiration time of the granted token.

            var jwsPayload = await _jwtGenerator.GenerateAccessToken(audiences, scope.Split(' '), issuerName).ConfigureAwait(false); // 2. Construct the JWT token (client).

            var jArr = new JArray();

            foreach (var ticketLine in ticketLines)
            {
                var jObj = new JObject();
                jObj.Add(Constants.RptClaims.ResourceSetId, ticketLine.ResourceSetId);
                jObj.Add(Constants.RptClaims.Scopes, string.Join(" ", ticketLine.Scopes));
                jArr.Add(jObj);
            }

            jwsPayload.Add(Constants.RptClaims.Ticket, jArr);
            var clientId    = audiences.First();
            var accessToken = await _clientHelper.GenerateIdTokenAsync(clientId, jwsPayload).ConfigureAwait(false);

            var refreshTokenId = Encoding.UTF8.GetBytes(Guid.NewGuid().ToString()); // 3. Construct the refresh token.

            return(new GrantedToken
            {
                AccessToken = accessToken,
                RefreshToken = Convert.ToBase64String(refreshTokenId),
                ExpiresIn = expiresIn,
                TokenType = SimpleIdServer.Core.Constants.StandardTokenTypes.Bearer,
                CreateDateTime = DateTime.UtcNow,
                Scope = scope,
                ClientId = clientId
            });
        }
Exemple #7
0
        public async Task <UserDto> Handle(LoginUserQuery request, CancellationToken cancellationToken)
        {
            var user = await _userManager.FindByEmailAsync(request.Email);

            if (user == null)
            {
                throw new RestException(HttpStatusCode.Unauthorized,
                                        new { Error = "Incorrect email address or password, please try again." });
            }

            if (!await _userManager.IsEmailConfirmedAsync(user))
            {
                throw new RestException(HttpStatusCode.Unauthorized,
                                        new { Error = "You must have a confirmed email to log in." });
            }

            var signInResult = await _signInManager.CheckPasswordSignInAsync(user, request.Password, false);

            if (signInResult.Succeeded)
            {
                var refreshToken = _jwtGenerator.GenerateRefreshToken(user);

                await _context.RefreshTokens.AddAsync(refreshToken, cancellationToken);

                var success = await _context.SaveChangesAsync(cancellationToken) > 0;

                if (success)
                {
                    _cookieService.SetTokenCookie(refreshToken.Token);

                    return(new UserDto
                    {
                        UserName = user.UserName,
                        Token = _jwtGenerator.GenerateAccessToken(user),
                        RefreshToken = refreshToken.Token
                    });
                }

                throw new Exception(Constants.ServerSavingError);
            }

            throw new RestException(HttpStatusCode.Unauthorized,
                                    new { Error = "Incorrect email address or password." });
        }