public async Task <UserDto> LoginUser(UserDto user) { var dbUser = _userManager.Users.FirstOrDefault(usr => string.Equals(user.Email, usr.Email, StringComparison.CurrentCultureIgnoreCase)); if (dbUser == null) { throw new Exception("Non existent user"); } if (!dbUser.EmailConfirmed) { throw new Exception("User non verified email"); } var userSigninResult = await _signInManager.PasswordSignInAsync(dbUser, user.Password, true, false); if (!userSigninResult.Succeeded) { throw new Exception("Invalid password"); } var userRoles = await _userManager.GetRolesAsync(dbUser); var identityRoles = await _userManager.GetClaimsAsync(dbUser); var userRole = userRoles.First(); var token = _jwtHelper.GenerateJwtToken(dbUser, userRole, identityRoles); return(dbUser.ProjectUserToDtoUser(token, userRole)); }
public async Task <TwoFactorAuthenticationDto> Handle(AnswerTwoFactorAuthenticatonCommand request, CancellationToken cancellationToken) { var tfaDto = await _tfaService.ValidateTwoFactorAuthentication(request.OneTimePassword, request.AuthenticationId, request.UserId); if (tfaDto == null) { throw new NotFoundException("No se ha encontrado", request.AuthenticationId); } if (!tfaDto.Validated) { return(tfaDto); } var user = await _userService.GetUserById(tfaDto.UserId); var tokenHelper = new JwtHelper(_conf); var userRol = await _userRolService.GetRolByUserId(user.Id); tfaDto.Token = tokenHelper.GenerateJwtToken(user, new Rol { RolName = userRol.RolName }); return(tfaDto); }
public async Task <object> Register([FromBody] RegisterDto model) { var user = new AuthUser { UserName = model.Email, Email = model.Email, Address = model.Address }; try { var result = await _userManager.CreateAsync(user, model.Password); //var roleId = await _roleManager.GetRoleIdAsync(new IdentityRole(model.Role)); result = await _userManager.AddToRoleAsync(user, model.Role); if (result.Succeeded) { await _signInManager.SignInAsync(user, false); var appUserRoles = await _userManager.GetRolesAsync(user); return(await JwtHelper.GenerateJwtToken(model.Email, user, _configuration, appUserRoles[0])); } return(new { code = "00008", message = "Operation errors", error = "An operation error happened." }); } catch (Exception) { return(new { code = "00007", message = "System errors", error = "An system error happened." }); } }
public async Task <object> Register([FromBody] RegisterDto model) { var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; try { var result = await _userManager.CreateAsync(user, model.Password); if (result.Succeeded) { await _signInManager.SignInAsync(user, false); return(await JwtHelper.GenerateJwtToken(model.Email, user, _configuration)); } return(new { code = "00008", message = "Operation errors", error = "An operation error happened." }); } catch (Exception e) { return(new { code = "00007", message = "System errors", error = "An system error happened." }); } }
public IActionResult Login(LoginInputDto input) { if (!CheckPwd(input)) { return(Json(new ResultDto() { Message = "invalid username or password" })); } var token = JwtHelper.GenerateJwtToken(options.Secret, new Dictionary <string, string> { { "username", input.UserName }, { "logintime", DateTime.Now.ToString() } }); ResponseCookie.Add(new HttpCookie { Name = "authorization", Value = token }); return(Json(new ResultDto() { Success = true })); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseRouting(); app.UseGrpcWeb(); app.UseCors(c => { c .AllowAnyOrigin() .AllowAnyHeader() .AllowAnyMethod(); }); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapGrpcService <MovieService>().EnableGrpcWeb(); endpoints.MapGet("/", async context => { await context.Response.WriteAsync("Communication with gRPC endpoints must be made through a gRPC client. To learn how to create a client, visit: https://go.microsoft.com/fwlink/?linkid=2086909"); }); endpoints.MapGet("/generateJwtToken", context => context.Response.WriteAsync(JwtHelper.GenerateJwtToken(context.Request.Query["name"])) ); }); }
public IActionResult Authenticate() { var user = WindowsIdentity.GetCurrent(); var token = _jwtHelper.GenerateJwtToken(user); return(Json(token)); }
public override Task <SignInResponse> SignIn(SignInRequest request, ServerCallContext context) { if (request.Password != "secret") { throw new RpcException(new Status(StatusCode.Unauthenticated, "Login incorrect")); } var token = JwtHelper.GenerateJwtToken(request.UserName); return(Task.FromResult(new SignInResponse { Token = token })); }
public async Task <object> Login([FromBody] LoginModel model) { var user = await _userManager.FindByEmailAsync(model.Email); if (user != null) { var result = await _signInManager.PasswordSignInAsync(user, model.Password, true, false); if (result.Succeeded) { _logger.LogLoginInfo($"{user.UserName} 用户登录", nameof(Login), nameof(AccountController), null, user.UserName, user.Id.ToString()); var userrole = await _userManager.GetRolesAsync(user); string roles = ""; foreach (var r in userrole) { roles += r + ","; } return(_JwtHelper.GenerateJwtToken(roles.TrimEnd(','), user)); } } throw new ApplicationException("INVALID_LOGIN_ATTEMPT"); }
public async Task <ResponseModel> Handle(UserLoginRequest request, CancellationToken cancellationToken) { var user = await _userManager.FindByEmailAsync(request.Email) ?? await _userManager.FindByNameAsync(request.Email); var passwordIsCorrect = await _userManager.CheckPasswordAsync(user, request.Password); if (passwordIsCorrect) { var roles = await _userManager.GetRolesAsync(user); var claims = new List <Claim> { new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()) }; claims.AddRange(JwtHelper.GenerateClaims(ClaimTypes.Role, roles.ToList())); var claimsPrincipal = await _signInManager.CreateUserPrincipalAsync(user); if (claims != null && claimsPrincipal?.Identity is ClaimsIdentity claimsIdentity) { claimsIdentity.AddClaims(claims); await _signInManager.SignInWithClaimsAsync(user, true, claimsIdentity.Claims); } return(new ResponseModel { StatusCode = HttpStatusCode.OK, Data = new { access_token = JwtHelper.GenerateJwtToken(claims, _configuration), role = roles.ToList() } }); } else { return(new ResponseModel { StatusCode = HttpStatusCode.BadRequest, Message = "User or Password is invalid" }); } }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapGrpcService <PortfolioService>(); endpoints.MapGet("/generateJwtToken", context => context.Response.WriteAsync(JwtHelper.GenerateJwtToken(context.Request.Query["name"]))); }); }
public async Task <object> Login([FromBody] LoginDto model) { try { var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, false, false); if (result.Succeeded) { var appUser = _userManager.Users.SingleOrDefault(r => r.Email == model.Email); return(await JwtHelper.GenerateJwtToken(model.Email, appUser, _configuration)); } return(new { code = "00008", message = "Operation errors", error = "An operation error happened." }); } catch (Exception) { return(new { code = "00007", message = "System errors", error = "An system error happened." }); } }
public async Task <string> LogIn(LogInDto logInDto) { var user = await _userRepo.GetAsync(logInDto.Email); // TODO if (user == null) { throw new ApplicationException(); } var password = new PasswordHelper(user.Password, logInDto.Password); var isPasswordValid = password.VerifyPassword(); if (!isPasswordValid) { throw new ApplicationException(); } var token = JwtHelper.GenerateJwtToken(user); return(token); }
public async Task <string> Register(RegisterDto registerDto) { var isUserExists = _userRepo.IsExists(x => x.Email == registerDto.Email); // TODO if (isUserExists) { throw new ApplicationException(); } var password = new PasswordHelper(registerDto.Password); password.HashPassword(); var user = Person.Create(registerDto.FullName, registerDto.Phone, registerDto.Email, password.PasswordHash); var token = JwtHelper.GenerateJwtToken(user); await _userRepo.AddAsync(user); await _userRepo.SaveChangesAsync(); return(token); }