public async Task <IActionResult> OnPostAsync(string username, string password)
        {
            if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
            {
                ActiveDirectory       ad  = new ActiveDirectory();
                LoginResponseResource res = await ad.Authenticate(username, password);

                //if (username == password.Substring(3))
                //    res = new LoginResponseResource()
                //    {
                //        scopeLevel = new ScopeLevel
                //        { branchcode = password.Substring(0, 3) },
                //        Success = true,
                //        token = "",
                //        user = new User { sAMAccountName = username.Replace('.',' ') }
                //    };
                //else
                //    res = await ad.Authenticate(username, password);

                if (res.Success)
                {
                    var claims = new List <Claim> {
                        new Claim(ClaimTypes.Name, res.user.sAMAccountName),
                        new Claim("BranchCode", res.scopeLevel.branchcode)
                    };

                    var identity  = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
                    var principal = new ClaimsPrincipal(identity);

                    await HttpContext.SignInAsync(
                        CookieAuthenticationDefaults.AuthenticationScheme, principal,
                        new AuthenticationProperties
                    {
                        ExpiresUtc   = DateTime.UtcNow.AddMinutes(10),
                        IsPersistent = false
                    });

                    //await HttpContext.SignInAsync(
                    //    CookieAuthenticationDefaults.AuthenticationScheme, principal);

                    Log.Information($"{username} logged in");
                    return(LocalRedirect(Url.Content($"~/RequestStatus/{res.scopeLevel.branchcode}")));
                }
                else
                {
                    //Log.Information($"{username} failed authentication");
                    return(LocalRedirect(Url.Content("~/RequestStatus/Unauthorized")));
                }
            }
            else
            {
                return(LocalRedirect(Url.Content("~/RequestStatus/blank")));
            }
        }
예제 #2
0
        private async Task <LoginResponseResource> GerarJwt(string email)
        {
            var user = await _userManager.FindByEmailAsync(email);

            var claims = await _userManager.GetClaimsAsync(user);

            var userRoles = await _userManager.GetRolesAsync(user);

            claims.Add(new Claim(JwtRegisteredClaimNames.Sub, user.Id));
            claims.Add(new Claim(JwtRegisteredClaimNames.Email, user.Email));
            claims.Add(new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()));
            claims.Add(new Claim(JwtRegisteredClaimNames.Nbf, ToUnixEpochDate(DateTime.UtcNow).ToString()));
            claims.Add(new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(DateTime.UtcNow).ToString(), ClaimValueTypes.Integer64));

            foreach (var userRole in userRoles)
            {
                claims.Add(new Claim("role", userRole));
            }

            var identityClaims = new ClaimsIdentity();

            identityClaims.AddClaims(claims);


            var tokenHandler = new JwtSecurityTokenHandler();
            var key          = Encoding.ASCII.GetBytes(_appSettings.Secret);
            var credentials  = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature);
            var token        = tokenHandler.CreateToken(new SecurityTokenDescriptor
            {
                Issuer             = _appSettings.Emissor,
                Audience           = _appSettings.ValidoEm,
                Subject            = identityClaims,
                Expires            = DateTime.UtcNow.AddHours(_appSettings.ExpiracaoHoras),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            });

            var encodedToken = tokenHandler.WriteToken(token);

            var response = new LoginResponseResource
            {
                AccessToken = encodedToken,
                ExpiresIn   = TimeSpan.FromHours(_appSettings.ExpiracaoHoras).TotalSeconds,
                UserToken   = new UserTokenResource
                {
                    Id     = user.Id,
                    Email  = user.Email,
                    Claims = claims.Select(c => new ClaimResource {
                        Type = c.Type, Value = c.Value
                    })
                }
            };

            return(response);
        }
예제 #3
0
        public async Task <IActionResult> Login(LoginRequestResource loginReq)
        {
            var user = await userRepo.Authenticate(loginReq.UserName, loginReq.Password);

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

            var loginRes = new LoginResponseResource();

            loginRes.UserName = user.UserName;
            loginRes.Token    = CreateJWT(user);

            return(Ok(loginRes));
        }
예제 #4
0
        //private readonly IConfiguration _config;

        //public ActiveDirectory(IConfiguration config)
        //{
        //    _config = config;
        //}

        public async Task <LoginResponseResource> Authenticate(string _userName, string _password)
        {
            var stringPayload = await Task.Run(() => JsonConvert.SerializeObject(new { username = _userName, password = _password }));

            var httpContent = new StringContent(stringPayload, Encoding.UTF8, "application/json");

            try
            {
                responseMsg = await Http.PostAsync("http://iwema/api/v1/Users/Login", httpContent);

                if (responseMsg.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    if (responseMsg.Content != null)
                    {
                        var responseContent = await responseMsg.Content.ReadAsStringAsync();

                        response         = JsonConvert.DeserializeObject <LoginResponseResource>(responseContent);
                        response.Success = true;
                        return(response);
                    }
                }

                return(new LoginResponseResource {
                    Success = false
                });
            }
            catch (Exception e)
            {
                return(new LoginResponseResource {
                    Success = false
                });
                //return new LoginResponseResource
                //{
                //    Success = true,
                //    scopeLevel = new ScopeLevel { branchcode = "092" },
                //    user = new User { sAMAccountName = "Ubong.Nkana" }
                //};
            }
            finally
            {
            }
        }
예제 #5
0
        public async Task <IActionResult> Register(RegisterRequestResource registerReq)
        {
            if (await userRepo.UserAlreadyExists(registerReq.UserName))
            {
                return(BadRequest("User already exists, please try something else"));
            }

            userRepo.Register(registerReq);
            //await userRepo.SaveChanges();

            var user = await userRepo.Authenticate(registerReq.UserName, registerReq.Password);

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

            var loginRes = new LoginResponseResource();

            loginRes.UserName = registerReq.UserName;
            loginRes.Token    = CreateJWT(user);

            return(Ok(loginRes));//StatusCode(201);
        }