public UserLoginDTO Login(UserLoginDTO userLoginDTO) { User user = _usersRepo.GetByUsername(userLoginDTO.UserName); if (user == null || user.PasswordHash != EncryptionHelper.Encrypt(userLoginDTO.Password, secretKey)) { return(null); } if (!user.IsActive) { throw new ApplicationException("User is not active"); } return(new UserLoginDTO { UserName = user.UserName, Email = user.Email, Token = JwtHelper.CreateToken( secretKey, hoursForTokenToExpire, user.Id, user.UserRoleRelations.Select(ur => ur.Role.Description) ) }); }
public async Task <string> Handle(AuthUserQuery request, CancellationToken cancellationToken) { var id = await _userRepository.GetUserByUsernameAndPassword(request.Username, request.Password); return(id == Guid.Empty ? string.Empty : JwtHelper.CreateToken(id, _configuration["Jwt:Issuer"], _configuration["Jwt:Audience"], _configuration["Jwt:Key"])); }
public JsonResult LoginInfo() { ResultUser resultUser = new ResultUser(); UserBLL ub = new UserBLL(); InvitationBLL ib = new InvitationBLL(); try { string username = Request["username"].ToString(); string password = Request["password"].ToString(); User user = new User(); user.LoginID = username; var data = ub.GetUser(user); if (data != null) { if (data.LoginID.Equals(username) && data.PassWord.Equals(MD5Helper.MD5Encrypt32(password))) { resultUser.res = 200; resultUser.msg = "用户是登录的私密聊天"; DateTime time = DateTime.Now; resultUser.data = JwtHelper.CreateToken(user, time); } else { resultUser.res = 500; resultUser.msg = "密码错误,请重新输入"; } } } catch { } return(Json(resultUser)); }
public AjaxResult Jwtoken(LoginDto dto) { Check.NotNull(dto, nameof(dto)); if (!ModelState.IsValid) { return(new AjaxResult("提交信息验证失败", AjaxResultType.Error)); } var user = _userLoginContract.GetFirst(m => m.UserName == dto.UserName && m.Password == dto.Password); if (user == null) { return(new AjaxResult("账户或密码错误", AjaxResultType.Error)); } //生成Token,这里只包含最基本信息,其他信息从在线用户缓存中获取 Claim[] claims = { new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()), new Claim(ClaimTypes.Name, user.UserName) }; TomNetOptions options = HttpContext.RequestServices.GetTomNetOptions(); string token = JwtHelper.CreateToken(claims, options); return(new AjaxResult("登录成功", AjaxResultType.Success, token)); }
public static HttpClient DefaultAuthorizationBearer( this HttpClient client, string email, string userName) { client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue( "Bearer", JwtHelper.CreateToken(email, userName)); return(client); }
public async Task <ActionResult> AnonymusRegister(UserForRegisterDto userForRegisterDto) { var cozen = HttpContext.Session.GetString("uuid"); if (userForRegisterDto.Email == null || userForRegisterDto.KullaniciAdi == null || userForRegisterDto.ad == null || userForRegisterDto.soyad == null) { ModelState.AddModelError("kullanicihata", "Lütfen Heryeri Doldurunuz"); return(RedirectToAction("Index", "Register")); } var hasKullaniciAdi = _context.Users.Where(u => u.KullaniciAdi == userForRegisterDto.KullaniciAdi); if (hasKullaniciAdi.Count() != 0) { ModelState.AddModelError("kullanicihata", "Kullanıcı Adı Bulunmaktadır"); return(RedirectToAction("Index", "Register")); } byte[] passwordSalt, passworHash; HashingHelper.CreatePasswordHash(userForRegisterDto.password, out passworHash, out passwordSalt); var user = new UserdbModel { KullaniciAdi = userForRegisterDto.KullaniciAdi, Email = userForRegisterDto.Email, Ad = userForRegisterDto.ad, Soyad = userForRegisterDto.soyad, SifreHash = passworHash, SifreSalt = passwordSalt, Status = true }; _context.Users.Add(user); _context.SaveChanges(); var current = _context.Users.Where(u => u.KullaniciAdi == userForRegisterDto.KullaniciAdi).FirstOrDefault(); UserOperationClaim userOperation = new UserOperationClaim { UserId = current.ID, OperationClaimId = 2 }; _context.UserOperationClaims.Add(userOperation); _context.SaveChanges(); var result = _context.Users.Where(u => u.KullaniciAdi == user.KullaniciAdi) as UserdbModel; HttpContext.Session.SetString("username", user.KullaniciAdi); _jwtHelper = new JwtHelper(Configuration); var claims = _efUser.GetClaims(user); var token = _jwtHelper.CreateToken(user, claims); HttpContext.Session.SetString("JWToken", token.Token); _context.CozulenTest.Where(c => c.cozen == cozen).FirstOrDefault().cozen = user.KullaniciAdi; _context.Istatistik.Where(c => c.cozen == cozen).FirstOrDefault().cozen = user.KullaniciAdi; _context.SaveChanges(); HttpContext.Session.Remove("uuid"); return(RedirectToAction("GetTest", "Test")); }
private RegisterResponse GenerateRegisterResponse(User user) { var token = JwtHelper.CreateToken(user.UserName, user.Id, user.FullName, _userRoleService.GetUserRoles(user.Id)); return(new RegisterResponse() { Profile = GenerateUserProfileResponse(user) }); }
private static Passport CreatePassport(User user) { var userOutput = Mapper.Map <UserOutputDto>(user); var token = JwtHelper.CreateToken(userOutput); return(new Passport { Token = token.AccessToken, Profile = userOutput }); }
private RegisterResponse GenerateRegisterResponse(User user) { var token = JwtHelper.CreateToken(user.Id, user.DisplayName); return(new RegisterResponse() { Token = token, Profile = GenerateUserProfileResponse(user) }); }
public async Task <IActionResult> DemoLogin() { var tokenLifeTimeSeconds = Convert.ToInt32(_appSettings["TokenLifeTime"]); int demoUserCount = await _authRepo.CountDemoUsers(); demoUserCount++; var newUser = new User() { UserName = $"demo{demoUserCount}", DisplayName = "Demo Benutzer", Email = "*****@*****.**", AccountExpireDate = DateTime.Now.AddSeconds(tokenLifeTimeSeconds) }; IdentityResult creationResult = await _userManager.CreateAsync(newUser, "P@ssw0rd"); if (!creationResult.Succeeded) { BadRequest(creationResult.Errors); } IdentityResult addRoleResult = await _userManager.AddToRolesAsync(newUser, new[] { RoleNames.Member, RoleNames.Demo }); if (!addRoleResult.Succeeded) { return(BadRequest(addRoleResult.Errors)); } newUser = await _authRepo.CreateDemoData(newUser); if (newUser == null) { throw new Exception("Error creating environment/demo data"); } List <Claim> identityClaims = await BuildIdentityClaims(newUser); Permission defaultPermissions = await _authRepo.GetDefaultPermissions(newUser.Id); List <Claim> permissionClaims = BuildPermissionClaims(defaultPermissions); SettingsDto settings = await GetSettings(newUser.Id, new List <CameraDto>()); _permissionsCache.AddEntriesForUser(newUser.Id, await _authRepo.GetAllUserPermissions(newUser.Id)); var mappedUser = _mapper.Map <UserForTokenDto>(newUser); return(Ok(new { identityToken = JwtHelper.CreateToken(identityClaims.ToArray(), _tokenSecretKey, DateTime.Now.AddSeconds(tokenLifeTimeSeconds)), permissionsToken = JwtHelper.CreateToken(permissionClaims.ToArray(), _tokenSecretKey, DateTime.Now.AddSeconds(tokenLifeTimeSeconds)), mappedUser, settings })); }
public void Method() { Claim[] claims = { new Claim(ClaimTypes.NameIdentifier, Guid.NewGuid().ToString()), new Claim(ClaimTypes.Name, "zhangsan") }; var token = JwtHelper.CreateToken(claims); Console.WriteLine(token); }
/// <summary> /// 生成Jwt的Token /// </summary> /// <param name="user"></param> /// <returns></returns> private string CreateJwtToken(WxUser user) { Claim[] claims = { new Claim(ClaimTypes.NameIdentifier, user.ID.ToString()), new Claim(ClaimTypes.Name, user.NickName) }; var token = JwtHelper.CreateToken(claims, _jwtSettings); return(token); }
private string BuildPermissionToken(Permission permission, TimeSpan tokenLifeSpan) { var permissionClaims = new List <Claim> { new Claim(ClaimTypes.NameIdentifier, permission.UserId.ToString()), new Claim(BeepClaimTypes.Permissions, permission.ToBits()), new Claim(BeepClaimTypes.PermissionsSerial, permission.Serial), new Claim(BeepClaimTypes.EnvironmentId, permission.EnvironmentId.ToString()) }; return(JwtHelper.CreateToken(permissionClaims.ToArray(), _tokenSecretKey, DateTime.Now.Add(tokenLifeSpan))); }
/// <summary> /// 生成Jwt的Token /// </summary> /// <param name="user"></param> /// <returns></returns> private string CreateJwtToken(IdentityUser user) { Claim[] claims = { new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()), new Claim(ClaimTypes.Name, user.UserName), new Claim("NickName", user.NickName) }; var token = JwtHelper.CreateToken(claims, _option); return(token); }
private LoginResponse GenerateLoginResponse(User user) { var token = JwtHelper.CreateToken(user.Id, user.DisplayName); var response = new LoginResponse { TokenType = token.Type, Token = token.AccessToken, ExpiresIn = token.Expires, }; return(response); }
public async Task <AjaxResult> Jwtoken([FromBody] LoginDto dto) { Check.NotNull(dto, nameof(dto)); if (!ModelState.IsValid) { return(new AjaxResult("提交信息验证失败", AjaxResultType.Error)); } dto.Ip = HttpContext.GetClientIp(); dto.UserAgent = Request.Headers["User-Agent"].FirstOrDefault(); OperationResult <User> result = await _identityContract.Login(dto); IUnitOfWork unitOfWork = ServiceLocator.Instance.GetService <IUnitOfWork>(); unitOfWork.Commit(); if (!result.Successed) { return(result.ToAjaxResult()); } User user = result.Data; bool isAdmin = _identityContract.Roles.Any(m => m.IsAdmin && _identityContract.UserRoles.Where(n => n.UserId == user.Id).Select(n => n.RoleId).Contains(m.Id)); IList <string> roles = await _userManager.GetRolesAsync(user); //生成Token Claim[] claims = { new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()), new Claim(ClaimTypes.Name, user.UserName), new Claim(ClaimTypes.GivenName, user.NickName ?? user.UserName), new Claim(ClaimTypes.Email, user.Email), new Claim(JwtClaimTypes.HeadImage, user.HeadImg ?? ""), new Claim(JwtClaimTypes.IsAdmin, isAdmin.ToLower()), new Claim(ClaimTypes.Role, roles.ExpandAndToString()) }; string token = JwtHelper.CreateToken(claims); //在线用户缓存 IOnlineUserCache onlineUserCache = ServiceLocator.Instance.GetService <IOnlineUserCache>(); if (onlineUserCache != null) { await onlineUserCache.GetOrRefreshAsync(user.UserName); } return(new AjaxResult("登录成功", AjaxResultType.Success, token)); }
private LoginResponse GenerateLoginResponse(User user) { var token = JwtHelper.CreateToken(user.UserName, user.Id, user.FullName, _userRoleService.GetUserRoles(user.Id)); var response = new LoginResponse { Profile = GenerateUserProfileResponse(user), RefreshToken = token.RefreshToke, TokenType = token.Type, Token = token.AccessToken, ExpiresIn = token.Expires }; return(response); }
public ActionResult <dynamic> GetToken() { Dictionary <string, object> payLoad = new Dictionary <string, object>(); payLoad.Add("sub", "rober"); payLoad.Add("jti", Guid.NewGuid().ToString()); payLoad.Add("nbf", null); payLoad.Add("exp", null); payLoad.Add("iss", "roberIssuer"); payLoad.Add("aud", "roberAudience"); payLoad.Add("age", 30); var encodeJwt = JwtHelper.CreateToken(payLoad, 30); return(new { token = encodeJwt, code = 200, message = "获取成功" }); }
public async Task <IActionResult> AuthenticateUser([FromBody] AuthenticateModel model) { try { var user = await _authService.Authenticate(model); var tokenString = JwtHelper.CreateToken(user, _appSettings); return(Ok(new { Id = user.Id, Username = user.UserName, token = tokenString })); } catch (Exception ex) { return(BadRequest(new { message = ex.Message })); } }
public async Task <AjaxResult> Jwtoken(LoginDto dto) { Check.NotNull(dto, nameof(dto)); if (!ModelState.IsValid) { return(new AjaxResult("提交信息验证失败", AjaxResultType.Error)); } dto.Ip = HttpContext.GetClientIp(); dto.UserAgent = Request.Headers["User-Agent"].FirstOrDefault(); OperationResult <User> result = await _identityContract.Login(dto); IUnitOfWork unitOfWork = HttpContext.RequestServices.GetUnitOfWork <User, int>(); unitOfWork.Commit(); if (!result.Successed) { return(result.ToAjaxResult()); } User user = result.Data; //生成Token,这里只包含最基本信息,其他信息从在线用户缓存中获取 Claim[] claims = { new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()), new Claim(ClaimTypes.Name, user.UserName) }; OSharpOptions options = HttpContext.RequestServices.GetService <IOptions <OSharpOptions> >().Value; string token = JwtHelper.CreateToken(claims, options); //在线用户缓存 IOnlineUserCache onlineUserCache = HttpContext.RequestServices.GetService <IOnlineUserCache>(); if (onlineUserCache != null) { await onlineUserCache.GetOrRefreshAsync(user.UserName); } return(new AjaxResult("登录成功", AjaxResultType.Success, token)); }
public async Task <IActionResult> Login(UserForLoginDto user) { User userFromRepo = await _userManager.FindByNameAsync(user.Username); if (userFromRepo == null) { return(Unauthorized()); } SignInResult signInResult = await _signInManager.CheckPasswordSignInAsync(userFromRepo, user.Password, false); if (!signInResult.Succeeded) { return(Unauthorized(new { signInResult.IsLockedOut, signInResult.IsNotAllowed })); } var mappedUser = _mapper.Map <UserForTokenDto>(userFromRepo); var identityClaims = new List <Claim>() { new Claim(ClaimTypes.NameIdentifier, userFromRepo.Id.ToString()), new Claim(ClaimTypes.Name, userFromRepo.UserName) }; IList <string> roles = await _userManager.GetRolesAsync(userFromRepo); identityClaims.AddRange(roles.Select(r => new Claim(ClaimTypes.Role, r))); var defaultPermission = await _authRepo.GetDefaultPermissions(userFromRepo.Id); List <Claim> permissionClaims = BuildPermissionClaims(defaultPermission); var settings = await GetSettings(userFromRepo.Id, user.Cameras); _permissionsCache.AddEntriesForUser(userFromRepo.Id, await _authRepo.GetAllUserPermissions(userFromRepo.Id)); return(Ok(new { identityToken = JwtHelper.CreateToken(identityClaims.ToArray(), _tokenSecretKey, DateTime.Now.AddSeconds(_tokenLifeTimeSeconds)), permissionsToken = JwtHelper.CreateToken(permissionClaims.ToArray(), _tokenSecretKey, DateTime.Now.AddSeconds(_tokenLifeTimeSeconds)), mappedUser, settings })); }
public void CreateToken() { var jwtHelper = new JwtHelper(); //create token var token = jwtHelper.CreateToken("pujan"); var user = jwtHelper.GetUserIdentifier(token); Assert.AreEqual("pujan", user); // var token = jwtHelper.CreateToken("pujan"); ////verify // var r = jwtHelper.ValidateToken(token); // var t = "e30.eyJ1cm9sZSI6InJvbGUxLHJvbGUyIiwidXNlciI6InB1amFuIn0."; // var r1 = jwtHelper.ValidateToken(t); // var r2 = jwtHelper.ValidateToken("e30.ey11cm9sZSI6InJvbGUxLHJvbGUyIiwidXNlciI6InB1amFuIn0."); // var p = 0; }
private async Task <string> CreateJwtToken(User user) { //在线用户缓存 IOnlineUserCache onlineUserCache = HttpContext.RequestServices.GetService <IOnlineUserCache>(); if (onlineUserCache != null) { await onlineUserCache.GetOrRefreshAsync(user.UserName); } //生成Token,这里只包含最基本信息,其他信息从在线用户缓存中获取 Claim[] claims = { new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()), new Claim(ClaimTypes.Name, user.UserName) }; OsharpOptions options = HttpContext.RequestServices.GetService <IOptions <OsharpOptions> >().Value; string token = JwtHelper.CreateToken(claims, options); return(token); }
public async Task <IActionResult> UpdatePermissionClaims(int userId, int environmentId) { var tokenLifeTimeSeconds = Convert.ToInt32(_appSettings["TokenLifeTime"]); if (!this.VerifyUser(userId)) { return(Unauthorized()); } Permission permissions = await _authRepo.GetUserPermissionForEnvironment(userId, environmentId); if (permissions == null) { return(Unauthorized()); } var newClaims = BuildPermissionClaims(permissions); string newJwtToken = JwtHelper.CreateToken(newClaims.ToArray(), _tokenSecretKey, DateTime.Now.AddSeconds(tokenLifeTimeSeconds)); return(Ok(new { permissionsToken = newJwtToken })); }
public ActionResult <ResponseModel> PostLogin(LoginUserModel loginUser) { ResponseModel responseModel = null; try { string userName = loginUser.userName; var authModel = _authService.Autheticate(loginUser.userName, loginUser.password); if (authModel != null) { var ContactId = authModel.ContactId.ToGuid(); var unit = _faciTechDbContext.UnitContact .Include(e => e.Unit) .Where(e => e.ContactId == ContactId) .Select(e => e.Unit) .FirstOrDefault(); Guid communityId = Guid.Empty; Guid unitId = Guid.Empty; if (unit != null) { communityId = unit.CommunityId; unitId = unit.Id; } //Token to be sent back to Client string token = JwtHelper.CreateToken(authModel, communityId, unitId, _configuration.GetJwtTokenKey()); responseModel = new ResponseModel(ResponseStatus.Success, "", new { auth = authModel, token = token }); } else { responseModel = new ResponseModel(ResponseStatus.Error, "Invalid Username or Password"); } } catch (Exception ex) { responseModel = new ResponseModel(ResponseStatus.Error, "Unknow error while autheticating"); } return(responseModel); }
public BaseResponse <Token> Login(AuthDto authDto) { var user = Include(u => u.UserRoles).ThenInclude(ur => ur.Role) .FirstOrDefault(u => u.IsActivated() && u.Email.Equals(authDto.Email, StringComparison.InvariantCultureIgnoreCase) ); if (user == null) { throw new DataNotFoundException("Tài khoản không tồn tại"); } var hash = PasswordHelper.ComputeHash(authDto.Password, user.PasswordSalt); if (!user.PasswordHash.SequenceEqual(hash)) { throw new BadRequestException("Mật khẩu không chính xác."); } var token = JwtHelper.CreateToken(Mapper.Map <UserOutputDto>(user)); return(new BaseResponse <Token>(HttpStatusCode.OK, data: token)); }
public async Task <AuthenticationResponse> Handle(AuthUserQuery request, CancellationToken cancellationToken) { var userId = await _userRepository.GetUserByUsernameAndPassword( request.Username, Utils.Helpers.PasswordHelper.Encrypt(request.Password)); if (userId == Guid.Empty) { return(new AuthenticationResponse(new List <string> { "Usuário ou senha inválidos" })); } var accountId = await GetAccount(userId); var claims = new Dictionary <string, Guid> { { "user", userId }, { "account", accountId } }; var token = JwtHelper.CreateToken(claims, _configuration["Jwt:Issuer"], _configuration["Jwt:Audience"], _configuration["Jwt:Key"]); return(new AuthenticationResponse(token)); }
public async Task <IActionResult> Login(UserForLoginDto user) { var tokenLifeTimeSeconds = Convert.ToInt32(_appSettings["TokenLifeTime"]); User userFromRepo = await _userManager.FindByNameAsync(user.Username); if (userFromRepo == null) { return(Unauthorized()); } SignInResult signInResult = await _signInManager.CheckPasswordSignInAsync(userFromRepo, user.Password, false); if (!signInResult.Succeeded) { return(Unauthorized(new { signInResult.IsLockedOut, signInResult.IsNotAllowed })); } var mappedUser = _mapper.Map <UserForTokenDto>(userFromRepo); List <Claim> identityClaims = await BuildIdentityClaims(userFromRepo); var defaultPermission = await _authRepo.GetDefaultPermissions(userFromRepo.Id); List <Claim> permissionClaims = BuildPermissionClaims(defaultPermission); var settings = await GetSettings(userFromRepo.Id, user.Cameras); _permissionsCache.AddEntriesForUser(userFromRepo.Id, await _authRepo.GetAllUserPermissions(userFromRepo.Id)); return(Ok(new { identityToken = JwtHelper.CreateToken(identityClaims.ToArray(), _tokenSecretKey, DateTime.Now.AddSeconds(tokenLifeTimeSeconds)), permissionsToken = JwtHelper.CreateToken(permissionClaims.ToArray(), _tokenSecretKey, DateTime.Now.AddSeconds(tokenLifeTimeSeconds)), mappedUser, settings })); }
public ApiResponseModel Login(User user) { try { User objUser = new UserService().GetByEmail(user.email); if (!PasswordHelper.VerifyHashedPassword(objUser.password, user.password)) { return(apiResponse.Failed("Wrong password!")); } else { objUser.appToken = JwtHelper.CreateToken(new Claim[] { new Claim(ClaimTypes.Name, objUser.email), new Claim(ClaimTypes.Role, objUser.idRole.ToString()), }, DateTime.UtcNow.AddDays(7)); new UserService().Update(objUser); return(apiResponse.Success(new UserService().Login(user.email))); } } catch (Exception e) { return(apiResponse.Failed(e.Message)); } }
public async Task <OperationResult <string> > JwtLogin(LoginDto dto) { OperationResult <User> result = await _Login(dto); if (!result.Successed) { return(new OperationResult <string>(OperationResultType.Error, result.Message)); } User user = result.Data; //生成Token,这里只包含最基本信息,其他信息从在线用户缓存中获取 Claim[] claims = { new Claim(ClaimTypes.NameIdentifier, user.ID.ToString()), new Claim(ClaimTypes.Name, user.UserName) }; string token = JwtHelper.CreateToken(claims); //TODO 在线用户缓存 var returnResult = new OperationResult <string>(OperationResultType.Success, "登录成功", token); return(await Task.FromResult(returnResult)); }