コード例 #1
0
        public async Task <AuthenticateResponse> GetTokenAsync(AuthenticateRequest request)
        {
            var userData = await _user.GetUserByLogin(request.Username, request.Password);

            var claims = new List <Claim>()
            {
                new Claim(ClaimTypes.Sid, userData.UserId),
                new Claim(ClaimTypes.Role, userData.Role)
            };
            var claimIdentity = new ClaimsIdentity(claims);
            var token         = _jwtManager.GenerateToken(claimIdentity, _options.JwtOptions);

            if (string.IsNullOrEmpty(token))
            {
                throw new Exception("Something went wrong in get token.");
            }

            return(new AuthenticateResponse()
            {
                Email = userData.Email,
                FirstName = userData.FirstName,
                LastName = userData.LastName,
                Token = token
            });
        }
コード例 #2
0
        public IActionResult GenToken()
        {
            var claims = new List <Claim> {
                new Claim(ClaimTypes.NameIdentifier, "username"),
                new Claim(ClaimTypes.Role, "admin"),
                new Claim(ClaimTypes.Country, "United States"),
            };

            return(Ok(jwtManager.GenerateToken(claims)));
        }
コード例 #3
0
        public async Task <AuthResult <Token> > Login(LoginDTO loginDto)
        {
            if (loginDto == null || string.IsNullOrEmpty(loginDto.Username) || string.IsNullOrEmpty(loginDto.Password))
            {
                return(AuthResult <Token> .UnvalidatedResult);
            }

            var user = await userManager.FindByNameAsync(loginDto.Username);

            if (user != null && user.Id > 0 && !user.IsDeleted)
            {
                if (await userManager.CheckPasswordAsync(user, loginDto.Password))
                {
                    var token = jwtManager.GenerateToken(user);
                    return(AuthResult <Token> .TokenResult(token));
                }
            }

            return(AuthResult <Token> .UnauthorizedResult);
        }
コード例 #4
0
ファイル: UsersDomain.cs プロジェクト: aronyanez/SampleAPI
        public async Task <JsonWebToken> SignIn(SignInModel signInModel)
        {
            var userSearch = await usersRepository.Get(u => u.Email == signInModel.Email);

            if (userSearch == null || userSearch.Count == 0)
            {
                throw ErrorStatusCode.UserNotFound;
            }
            User user = userSearch[0];

            var(Verified, NeedsUpgrade) = passwordHasher.Check(user.Password, signInModel.Password);
            if (!Verified)
            {
                throw ErrorStatusCode.WrongPassword;
            }
            return(await jwtManager.GenerateToken(new JwtUser {
                Name = user.Name,
                Email = user.Email,
                Id = user.Id
            }));
        }
コード例 #5
0
ファイル: AuthController.cs プロジェクト: vipinhe/cpnucleo
        public IActionResult Index(string user, string pass)
        {
            string token;

            if (user == userT && pass == passT)
            {
                token = _jwtManager.GenerateToken(user, 60);
            }
            else
            {
                return(BadRequest());
            }

            return(Ok(token));
        }
コード例 #6
0
ファイル: UserService.cs プロジェクト: marcinstelmach/Actio
        public async Task <JsonWebToken> Login(string email, string password)
        {
            var user = await userRepository.GetAsync(email, false);

            if (user == null)
            {
                throw new ActioException(ErrorCode.InvalidUsernameOrPassword);
            }

            if (!user.ValidatePassword(password, encrypter))
            {
                throw new ActioException(ErrorCode.InvalidUsernameOrPassword);
            }

            return(jwtManager.GenerateToken(user.Id));
        }
コード例 #7
0
ファイル: AuthService.cs プロジェクト: MigueArcos/SampleAPI
        private async Task <JsonWebToken> CreateUserJwt(long userId, string email, string name)
        {
            var userJwt = jwtManager.GenerateToken(new JwtUser {
                Name  = name,
                Email = email,
                Id    = userId
            });
            await tokensRepository.Post(new UserToken {
                UserId      = userJwt.UserId,
                Token       = userJwt.RefreshToken,
                TokenTypeId = (long)Data.Enums.TokenType.RefreshToken,
                ExpiryTime  = DateTime.Now.AddSeconds(jwtManager.RefreshTokenTTLSeconds)
            });

            return(userJwt);
        }
コード例 #8
0
ファイル: UsersController.cs プロジェクト: KThaulow/WebShop
        public ActionResult <ClientUser> Authenticate([FromBody] Login login)
        {
            var user   = m_userManager.FindByNameAsync(login.Username).GetAwaiter().GetResult();
            var result = m_signInManager.CheckPasswordSignInAsync(user, login.Password, false).GetAwaiter().GetResult();

            if (result.Succeeded)
            {
                var token = m_jwtManager.GenerateToken(user.UserName);
                return(new ClientUser()
                {
                    FirstName = user.FirstName, LastName = user.LastName, Username = user.UserName, Token = token
                });
            }

            return(Unauthorized("Username or password is incorrect"));
        }
コード例 #9
0
 public override async Task <ActionResult <LoginResource> > Create(LoginAlterResource resource)
 {
     if (resource.Email == AppSettings.AdminUserName &&
         resource.Password == AppSettings.AdminUserPassword)
     {
         var adminUser = new UserResource()
         {
             Email = AppSettings.AdminUserName
         };
         return(new LoginResource()
         {
             Token = JwtManager.GenerateToken(adminUser, AppSettings.Secret),
             User = adminUser
         });
     }
     return(await base.Create(resource));
 }
コード例 #10
0
        // AuthenticationFailed, try again using the refreshToken
        public override async Task AuthenticationFailed(AuthenticationFailedContext context)
        {
            try {
                GetTokensFromRequestContext(context.HttpContext.Request, out string token, out string refreshToken);
                if (!string.IsNullOrEmpty(token) && !string.IsNullOrEmpty(refreshToken))
                {
                    // validate refreshToken in DB
                    var refreshTokenSearch = await tokensRepository.Get(t => t.Token == refreshToken);

                    if (refreshTokenSearch == null || refreshTokenSearch.Count == 0)
                    {
                        WriteExceptionToHttpResponse(context.HttpContext.Response, ErrorStatusCode.RefreshTokenExpired);
                        throw ErrorStatusCode.RefreshTokenExpired;
                    }
                    var(claims, jwtUser) = jwtManager.ReadToken(token, false);
                    var newToken = jwtManager.GenerateToken(jwtUser);
                    // Delete previous token from database
                    await tokensRepository.DeleteById(refreshTokenSearch[0].Id);

                    // Create a new token in Database
                    await tokensRepository.Post(new UserToken {
                        UserId      = newToken.UserId,
                        Token       = newToken.RefreshToken,
                        TokenTypeId = (long)Data.Enums.TokenType.RefreshToken,
                        ExpiryTime  = DateTime.Now.AddSeconds(jwtManager.RefreshTokenTTLSeconds)
                    });

                    context.Principal = claims;
                    // if there was a cookie, then set again the cookie with the new value
                    if (!string.IsNullOrEmpty(context.HttpContext.Request.Cookies[AppConstants.SessionCookie]))
                    {
                        context.HttpContext.SetCookie(AppConstants.SessionCookie, Newtonsoft.Json.JsonConvert.SerializeObject(new Dictionary <string, string> {
                            [AppConstants.Token]        = newToken.Token,
                            [AppConstants.RefreshToken] = newToken.RefreshToken
                        }));
                    }
                    // If everything goes ok set request principal (In this point authentication is done and ok)
                    context.Success();
                }
            }
            catch {
                return;
            }
            return;
        }
コード例 #11
0
        public ActionResult <RecursoViewModel> Autenticar([FromQuery] string login, [FromQuery] string senha)
        {
            RecursoViewModel recurso = _recursoAppService.Autenticar(login, senha, out bool valido);

            if (recurso == null)
            {
                return(NotFound());
            }

            if (!valido)
            {
                return(NotFound());
            }
            else
            {
                recurso.Token = _jwtManager.GenerateToken(recurso.Id.ToString(), _systemConfiguration.JwtExpirationDate);

                return(Ok(recurso));
            }
        }
コード例 #12
0
        public string CheckLogin(string email, string password)
        {
            var user = _userService.GetByEmail(email);

            if (user == null)
            {
                throw new Exception("User is not found!");
            }
            // Verify Password
            if (!string.Equals(user.Password, password, StringComparison.InvariantCulture))
            {
                throw new Exception("Invalid password!");
            }

            // Here email & password is valid then we can issue a JWT token
            // Information need to put into JWT token (Claim), this info may be use to identify user (eg: Id or email)
            var claims = new Claim[]
            {
                new Claim(ClaimTypes.Name, $"{user.FirstName} ${user.LastName}"),
                new Claim(ClaimTypes.Email, user.Email),
                new Claim(ClaimTypes.NameIdentifier, user.Id.ToString())
            };

            //-----------------------------
            // Simple version
            //-----------------------------
            //var now = DateTime.UtcNow;
            //var jwtToken = new JwtSecurityToken(
            //    issuer: "giant.store.dev",
            //    audience: "giant.store.dev",
            //    claims: claims,
            //    notBefore: now,
            //    expires: now.AddMinutes(30),
            //    signingCredentials: new SigningCredentials(new SymmetricSecurityKey(_secret), SecurityAlgorithms.HmacSha256Signature));
            //var token = new JwtSecurityTokenHandler().WriteToken(jwtToken);

            // Generate JWT token
            var token = _jwtManager.GenerateToken(claims, DateTime.UtcNow);

            return(token);
        }
コード例 #13
0
        public async Task <IActionResult> Login(BaseUserDto model)
        {
            var user = await _userService.GetUserByLogin(model);

            if (user == null)
            {
                return(Ok(new LoginResultModel
                {
                    Success = false,
                    Message = Constants.Users.LoginAccountFail
                }));
            }

            var tokenString = _jwtManager.GenerateToken();

            return(Ok(new LoginResultModel
            {
                Success = true,
                Message = Constants.Users.LoginAccountSuccess,
                Token = tokenString
            }));
        }
コード例 #14
0
ファイル: AuthService.cs プロジェクト: bonhchi/loginbackend
        public string CheckLogin(string email, string password)
        {
            var user = _userService.GetByEmail(email);

            if (user == null)
            {
                throw new Exception("User is not found");
            }
            if (!string.Equals(user.Password, password, StringComparison.InvariantCultureIgnoreCase))
            {
                throw new Exception("Invalid password");
            }

            var claims = new Claim[]
            {
                new Claim(ClaimTypes.Name, $"{user.FirstName} ${user.LastName}"),
                new Claim(ClaimTypes.Email, user.Email),
                new Claim(ClaimTypes.NameIdentifier, user.Id.ToString())
            };

            var token = _jwtManager.GenerateToken(claims, DateTime.UtcNow);

            return(token);
        }
コード例 #15
0
        public string Post()
        {
            return(_jwtManager.GenerateToken(User.Identity.Name));

            throw new HttpResponseException(HttpStatusCode.Unauthorized);
        }
コード例 #16
0
 private string GetToken(UserResource userResource)
 {
     return(JwtManager.GenerateToken(userResource, AppSettings.Secret));
 }
コード例 #17
0
        public async Task <AuthenticationResponseModel> RegisterAsync(RegisterRequestModel registerRequestModel)
        {
            if (registerRequestModel == null)
            {
                throw new EShopperException("Please provide required information!");
            }

            EShopperUser isEmailExist = await _eShopperUserManager.FindByEmailAsync(registerRequestModel.Email);

            if (isEmailExist != null)
            {
                throw new EShopperException("Email address already exist!");
            }

            EShopperUser eShopperIdentity = new EShopperUser
            {
                Email    = registerRequestModel.Email,
                UserName = registerRequestModel.Username
            };

            // Begin Transaction...
            using (var transaction = _unitOfWork.EShopperDbContext.Database.BeginTransaction())
            {
                try
                {
                    IdentityResult registerEShopperUserResult = await _eShopperUserManager.CreateAsync(eShopperIdentity, registerRequestModel.Password);

                    if (registerEShopperUserResult.Succeeded)
                    {
                        UserDetails usersDetail = new UserDetails
                        {
                            User         = eShopperIdentity,
                            Fullname     = registerRequestModel.Fullname,
                            RegisterDate = DateTime.UtcNow
                        };


                        IdentityResult addToRoleResult = await _eShopperUserManager.AddToRoleAsync(eShopperIdentity, "USER");

                        if (!addToRoleResult.Succeeded)
                        {
                            throw new EShopperException();
                        }

                        _unitOfWork.UsersDetail.Add(usersDetail);
                        _unitOfWork.Complete();

                        transaction.Commit();

                        JwtManagerResponse jwtResponse = await _jwtManager.GenerateToken(eShopperIdentity);

                        EShopperUser getUserDetails = _eShopperUserManager.GetUserWithUserDetailsByEmail(registerRequestModel.Email);

                        EShopperUserDto mappedUserDetails = _mapper.Map <EShopperUserDto>(getUserDetails);

                        _logger.LogInformation($"{getUserDetails.Email} - Registered with EShopperAuthentication");

                        return(new AuthenticationResponseModel
                        {
                            AccessToken = jwtResponse.AccessToken,
                            RefreshToken = jwtResponse.RefreshToken,
                            EShopperUser = mappedUserDetails
                        });
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex.Message);
                    throw new EShopperException();
                }
                finally
                {
                    transaction.Dispose();
                }
            }

            throw new EShopperException();
        }