public (UserDBModel, string) AuthenticateLogin(string username, string password)
 {
     if (_userAuthenticate.Authenticate(username, password))
     {
         var User = _context.userDBModels.FirstOrDefault(q => q.Name == username);
         _userAuthenticate.RemoveRefreshTokens(User.ID);
         string jwt = _userAuthenticate.GenerateToken(username, User.ID);
         return(User, jwt);
     }
     return(null, null);
 }
Пример #2
0
        public async Task <ActionResult> Authenticate([FromBody] UserDto userDto)
        {
            if (string.IsNullOrEmpty(userDto.Username) || string.IsNullOrEmpty(userDto.Password))
            {
                return(BadRequest("Username and password is required"));
            }

            var user = await _userAuthenticate.Authenticate(userDto.Username, userDto.Password);

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

            return(Ok());
        }
        protected override async Task <AuthenticateResult> HandleAuthenticateAsync()
        {
            if (!Request.Headers.ContainsKey("Authorization"))
            {
                return(AuthenticateResult.Fail("Missing Authorization Header"));
            }

            UserDto userDto;

            try
            {
                var authHeader      = AuthenticationHeaderValue.Parse(Request.Headers["Authorization"]);
                var credentialBytes = Convert.FromBase64String(authHeader.Parameter);
                var credentials     = Encoding.UTF8.GetString(credentialBytes).Split(':');
                var username        = credentials[0];
                var password        = credentials[1];
                userDto = await _userAuthenticate.Authenticate(username, password);
            }
            catch
            {
                return(AuthenticateResult.Fail("Invalid Authorization Header"));
            }

            if (userDto == null)
            {
                return(AuthenticateResult.Fail("Invalid Username or Password"));
            }

            var claims = new List <Claim>
            {
                new Claim(ClaimTypes.NameIdentifier, userDto.Id),
                new Claim(ClaimTypes.Name, userDto.Username)
            };

            userDto.Roles.ForEach(r => claims.Add(new Claim(ClaimTypes.Role, r.ToString())));


            var identity  = new ClaimsIdentity(claims, Scheme.Name);
            var principal = new ClaimsPrincipal(identity);
            var ticket    = new AuthenticationTicket(principal, Scheme.Name);

            return(AuthenticateResult.Success(ticket));
        }