Exemple #1
0
        public AccountResponse EditUserName(AccountUserNameEditDto model)
        {
            Dictionary <string, string[]> errors = new Dictionary <string, string[]>();

            UserAccount user = _context.UserAccounts.AsNoTracking().FirstOrDefault(u => u.UserName == _userName);

            if (user == null)
            {
                errors.Add("User", new[] { "Podane konto nie istnieje" });
                return(new AccountResponse(errors));
            }
            user.UserName           = model.UserName;
            user.NormalizedUserName = model.UserName.ToUpper();

            try
            {
                _context.UserAccounts.Update(user);
                _context.SaveChanges();
            }
            catch (Exception ex)
            {
                errors.Add("Wystąpił nieoczekiwany błąd", new[] { ex.Message });
                return(new AccountResponse(errors));
            }

            var response = new JwtTokenDto
            {
                Token = GenerateJwtToken(user.Email, user)
            };

            return(new AccountResponse(response));
        }
        public async Task SignInAsync(JwtTokenDto tokenDto)
        {
            _userContext.SignedInUser = new SignedInUser(tokenDto.Token);
            await _tokenManager.SaveTokenAsync(tokenDto);

            AuthenticationStateUpdated?.Invoke(null, EventArgs.Empty);
        }
Exemple #3
0
        public static dynamic BuildJwtToken(List <Claim> claims, PermissionRequirement permissionRequirement)
        {
            var now = DateTime.Now;
            // 实例化JwtSecurityToken
            var jwt = new JwtSecurityToken(
                issuer: permissionRequirement.Issuer,
                audience: permissionRequirement.Audience,
                claims: claims,
                notBefore: now,
                expires: now.Add(permissionRequirement.Expiration),
                signingCredentials: permissionRequirement.SigningCredentials
                );
            // 生成 Token
            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

            //打包返回前台
            var responseJson = new JwtTokenDto
            {
                token      = encodedJwt,
                expires_in = permissionRequirement.Expiration.TotalSeconds,
                token_type = "Bearer"
            };

            return(responseJson);
        }
Exemple #4
0
        public JwtTokenDto ExtractToken(ExtractTokenDto tokenInfo)
        {
            Logger.LogInformation("Try to extract token");

            Validate(tokenInfo);

            var toReturn = new JwtTokenDto()
            {
                Token   = tokenInfo.Token,
                IsValid = false
            };

            if (string.IsNullOrEmpty(tokenInfo.Token))
            {
                return(toReturn);
            }

            var handler = new JwtSecurityTokenHandler();
            var validationParameters = new TokenValidationParameters
            {
                ValidIssuer       = Configuration.Issuer,
                ValidAudience     = Configuration.Audience,
                IssuerSigningKeys = new List <SecurityKey>()
                {
                    new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration.SecurityKey))
                }
            };

            ClaimsPrincipal pClaim;

            try
            {
                pClaim = handler.ValidateToken(tokenInfo.Token, validationParameters, out var validatedToken);
            }
            catch (Exception ex)
            {
                toReturn.InvalidationCause = ex.Message;
                return(toReturn);
            }

            if (!long.TryParse(GetValueFromClaim(pClaim.Claims, ClaimName.Expire), out var expire))
            {
                return(toReturn);
            }

            toReturn.Expire = expire;

            if (expire < DateTimeOffset.Now.ToUnixTimeSeconds() || GetValueFromClaim(pClaim.Claims, ClaimName.TokenName) != tokenInfo.TokenName)
            {
                return(toReturn);
            }

            toReturn.Scope    = GetValueFromClaim(pClaim.Claims, ClaimName.Scope);
            toReturn.ClientId = GetValueFromClaim(pClaim.Claims, ClaimName.ClientId);
            toReturn.UserName = GetValueFromClaim(pClaim.Claims, ClaimName.Name);
            toReturn.IsValid  = true;

            return(toReturn);
        }
Exemple #5
0
        public async Task <AccountResponse> RegisterModAccountAsync(RegisterAccountDto model)
        {
            Dictionary <string, string[]> errors = new Dictionary <string, string[]>();
            UserAccount UserAdmin = _context.Users.FirstOrDefault(e => e.Email == _userName || e.UserName == _userName);
            UserAccount userr     = _context.Users.FirstOrDefault(e => e.Email == model.Email || e.UserName == model.UserName);

            if (UserAdmin.Rola != "admin" && UserAdmin.Rola != "moderator")
            {
                errors.Add("Rola", new[] { "NIe masz tutaj dostępu" });
                return(new AccountResponse(errors));
            }
            if (userr != null)
            {
                errors.Add("Emial", new[] { "Email jets juz zajety" });
                return(new AccountResponse(errors));
            }

            userr = _context.Users.FirstOrDefault(e => e.NormalizedUserName == model.UserName.ToUpper());
            if (userr != null)
            {
                errors.Add("Useranme", new[] { "Nazwa uzytkoniwka jest juz zajeta" });
                return(new AccountResponse(errors));
            }

            UserAccount user = _mapper.Map <RegisterAccountDto, UserAccount>(model);

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

            string rola = "moderator";

            user.Rola = rola;
            if (!result.Succeeded)
            {
                foreach (var error in result.Errors)
                {
                    errors.Add(error.Code, new[] { error.Description });
                }

                return(new AccountResponse(errors));
            }

            _context.SaveChanges();

            UserAccount appUser  = _userManager.Users.SingleOrDefault(r => r.Email == model.Email);
            JwtTokenDto response = new JwtTokenDto
            {
                Token = GenerateJwtToken(model.Email, appUser)
            };

            return(new AccountResponse(response));
        }
Exemple #6
0
        private bool CheckIfTokenIsValid(JwtTokenDto tokenDetail, IContext context)
        {
            if (!tokenDetail.IsValid)
            {
                return(false);
            }

            var clientUserRepo = RepositoriesFactory.GetUserClientRepository(context);
            var client         = clientUserRepo.GetUserClientByClientPublicIdAndUserName(tokenDetail.ClientId, tokenDetail.UserName);

            return(client == null || !client.IsActif
                ? false
                : client.RefreshToken != null && client.RefreshToken.Equals(tokenDetail.Token, StringComparison.Ordinal));
        }
Exemple #7
0
        public async Task <AccountResponse> EditEmail(AccountEditEmailDto emailDto)
        {
            Dictionary <string, string[]> errors = new Dictionary <string, string[]>();


            UserAccount user = _context.UserAccounts.AsNoTracking().FirstOrDefault(u => u.UserName == _userName);

            if (user == null)
            {
                errors.Add("User", new[] { "Podane konto nie istnieje" });
                return(new AccountResponse(errors));
            }

            var result = await _signInManager.CheckPasswordSignInAsync(user, emailDto.Password, false);

            if (!result.Succeeded)
            {
                errors.Add("Hasło", new[] { "Podałeś zle haslo" });
                return(new AccountResponse(errors));
            }

            UserAccount doExistEmail = await _context.UserAccounts.AsNoTracking().FirstOrDefaultAsync(u => u.Email == emailDto.Email);

            if (doExistEmail != null)
            {
                errors.Add("Email", new[] { "Podałeś zajety Email" });
                return(new AccountResponse(errors));
            }

            try
            {
                user.Email           = emailDto.Email;
                user.NormalizedEmail = emailDto.Email.ToUpper();
                _context.UserAccounts.Update(user);
                _context.SaveChanges();
            }
            catch (Exception ex)
            {
                errors.Add("Wystąpił nieoczekiwany błąd", new[] { ex.Message });
                return(new AccountResponse(errors));
            }

            JwtTokenDto response = new JwtTokenDto
            {
                Token = GenerateJwtToken(user.Email, user)
            };

            return(new AccountResponse(response));
        }
        private async Task <HttpResponseMessage> SendIntrospectRequest(JwtTokenDto jwtTokenDto)
        {
            var formContent = new MultipartFormDataContent()
            {
                { new StringContent(jwtTokenDto.Token), "token" }
            };

            _client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            _client.DefaultRequestHeaders.Authorization = BuildAuthenticationHeaderValue(_sammyRessourceServerLogin, _sammyRessourceServerPassword);

            var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/introspect");

            request.Content = formContent;

            return(await _client.SendAsync(request));
        }
Exemple #9
0
        public AccountResponse EditNameSurname(AccountEditNameSurnameDto model)
        {
            Dictionary <string, string[]> errors = new Dictionary <string, string[]>();

            UserAccount user = _context.UserAccounts.AsNoTracking().FirstOrDefault(u => u.UserName == _userName || u.Email == _userName);

            if (user == null)
            {
                errors.Add("User", new[] { "Podane konto nie istnieje" });
                return(new AccountResponse(errors));
            }
            if (model.Name != null)
            {
                user.Name = model.Name;
            }
            else
            {
                model.Name = user.Name;
            }

            if (model.Surname != null)
            {
                user.Surname = model.Surname;
            }
            else
            {
                model.Surname = user.Surname;
            }

            try
            {
                _context.UserAccounts.Update(user);
                _context.SaveChanges();
            }
            catch (Exception ex)
            {
                errors.Add("Wystąpił nieoczekiwany błąd", new[] { ex.Message });
                return(new AccountResponse(errors));
            }

            JwtTokenDto response = new JwtTokenDto
            {
                Token = GenerateJwtToken(user.Email, user)
            };

            return(new AccountResponse(response));
        }
Exemple #10
0
        public async Task <AccountResponse> LoginAccountAsync(LoginAccountDto model)
        {
            Dictionary <string, string[]> errors = new Dictionary <string, string[]>();

            var result = await _signInManager.PasswordSignInAsync(model.UserName, model.Password, false, false);

            if (!result.Succeeded)
            {
                errors.Add("Konto", new[] { "Nie udalo sie zalogowac" });
                return(new AccountResponse(errors));
            }

            UserAccount appUser  = _userManager.Users.SingleOrDefault(r => r.UserName == model.UserName);
            JwtTokenDto response = new JwtTokenDto
            {
                Token = GenerateJwtToken(model.UserName, appUser)
            };

            return(new AccountResponse(response));
        }
Exemple #11
0
        public async Task SignInAsync_Always_SignsIn()
        {
            //Arrange
            var sut      = CreateSut();
            var response = new Mock <IHttpResponse <JwtTokenDto> >();
            var token    = new JwtTokenDto(Token, "refresh");

            Mocker.GetMock <IHttpClient>()
            .Setup(o => o.PostAsync <SignInDto, JwtTokenDto>(AuthenticationUrls.SignIn,
                                                             It.Is <SignInDto>(dto => dto.Email == Email && dto.Password == Password)))
            .ReturnsAsync(response.Object);

            Mocker.GetMock <IProxyHelper>()
            .Setup(o => o.ProcessResponseAsync(response.Object, sut))
            .ReturnsAsync(token);

            //Act
            var result = await sut.SignInAsync(Email, Password);

            //Assert
            result.ShouldBe(token);
        }
Exemple #12
0
        public JwtTokenDto GenerateToken(CreateTokenDto value)
        {
            Logger.LogInformation($"Try to generate token for user {value.UserName}");

            Validate(value);

            var utcNow = DateTimeOffset.UtcNow;

            var claims = new List <Claim>();

            claims.Add(new Claim(ClaimName.ClientId, value.ClientPublicId));
            claims.Add(new Claim(ClaimName.TokenName, value.TokenName));
            claims.Add(new Claim(ClaimName.Issued, utcNow.ToUnixTimeSeconds().ToString(CultureInfo.InvariantCulture)));
            claims.Add(new Claim(ClaimName.Name, !String.IsNullOrEmpty(value.UserName) ? value.UserName : String.Empty));
            claims.Add(new Claim(ClaimName.Scope, !String.IsNullOrEmpty(value.Scope) ? value.Scope : String.Empty));

            var key         = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration.SecurityKey));
            var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var token = new JwtSecurityToken(
                issuer: Configuration.Issuer,
                audience: Configuration.Audience,
                claims: claims,
                signingCredentials: credentials,
                expires: utcNow.AddSeconds(value.SecondsLifeTime).UtcDateTime);

            var toReturn = new JwtTokenDto()
            {
                ClientId = value.ClientPublicId,
                Expire   = utcNow.AddSeconds(value.SecondsLifeTime).ToUnixTimeSeconds(),
                IsValid  = true,
                Scope    = value.Scope,
                Token    = new JwtSecurityTokenHandler().WriteToken(token),
                UserName = value.UserName
            };

            return(toReturn);
        }
Exemple #13
0
        public async Task RefreshAsync_Always_RefreshesToken()
        {
            //Arrange
            var sut      = CreateSut();
            var response = new Mock <IHttpResponse <JwtTokenDto> >();
            var tokenDto = new JwtTokenDto(Token, "");

            Mocker.GetMock <IHttpClient>()
            .Setup(o => o.
                   GetAsync <JwtTokenDto>(AuthenticationUrls.Refresh(Token, Email)))
            .ReturnsAsync(response.Object);

            Mocker.GetMock <IProxyHelper>()
            .Setup(o => o.ProcessResponseAsync(response.Object, sut))
            .ReturnsAsync(tokenDto);

            //Act
            await sut.RefreshAsync(Token, Email);

            //Assert
            Mocker.GetMock <IProxyHelper>()
            .Verify(o => o.ProcessResponseAsync(response.Object, sut));
        }
Exemple #14
0
        public async Task <AccountResponse> ChangePassword(AccountEditPasswordDto passwordDto)
        {
            Dictionary <string, string[]> errors = new Dictionary <string, string[]>();

            UserAccount user = _context.UserAccounts.AsNoTracking().FirstOrDefault(u => u.UserName == _userName || u.Email == _userName);

            if (user == null)
            {
                errors.Add("User", new[] { "Podane konto nie istnieje" });
                return(new AccountResponse(errors));
            }

            var signInResult = await _signInManager.CheckPasswordSignInAsync(user, passwordDto.OldPassword, false);

            if (!signInResult.Succeeded)
            {
                errors.Add("Hasło", new[] { "Podałeś zle haslo" });
                return(new AccountResponse(errors));
            }

            var changeResult = await _userManager.ChangePasswordAsync(await _userManager.FindByIdAsync(user.Id),
                                                                      passwordDto.OldPassword, passwordDto.NewPassword);

            if (!changeResult.Succeeded)
            {
                errors.Add("Hasło", new[] { changeResult.ToString() });
                return(new AccountResponse(errors));
            }

            JwtTokenDto response = new JwtTokenDto
            {
                Token = GenerateJwtToken(user.Email, user)
            };

            return(new AccountResponse(response));
        }
Exemple #15
0
 private AccountResponse(bool success, Dictionary <string, string[]> message, JwtTokenDto token)
     : base(success, message)
 {
     Token = token;
 }
Exemple #16
0
 public UpdatingUserEmailProcess(Logger logger, HttpClient httpClient, JwtTokenDto jwtTokenDto)
 {
     _logger             = logger;
     _httpClient         = httpClient;
     _httpRequestFactory = new HttpRequestFactory(jwtTokenDto);
 }
Exemple #17
0
        public async Task SaveTokenAsync(JwtTokenDto tokenDto)
        {
            var data = await _json.SerializeAsync(tokenDto);

            await _localStorageManager.Set(TokenStorageKey, data);
        }
Exemple #18
0
 public HttpRequestFactory(JwtTokenDto jwtTokenDto) => _jwtTokenDto = jwtTokenDto;
Exemple #19
0
 public AccountResponse(JwtTokenDto token)
     : this(true, new Dictionary <string, string[]>(), token)
 {
 }
Exemple #20
0
 public FakeJwtService(JwtTokenDto token)
 {
     _token = token;
 }
 public static void SetToken(this IMemoryCache memoryCache, Guid tokenId, JwtTokenDto jwtToken)
 {
     memoryCache.Set <JwtTokenDto>(tokenId, jwtToken);
 }