public LoginSuccessModel Login(LoginModel model) { LoginSuccessModel retModel = new LoginSuccessModel(); try { var data = _unitOfWork.AspNetRepository.GetSingle(s => s.UserName == model.username); if (data != null) { bool status = VerifyPassword(model.password, data.PasswordHash, data.PasswordSalt); if (status) { var rolemap = _unitOfWork.aspRoleMappingRepository.GetMany(s => s.UserId == data.Id); retModel.Rolenames = _unitOfWork.aspnetRolesRepository.GetAll().Where(item1 => rolemap.Any(item2 => item2.RoleId == item1.Id)).Select(s => s.Name).ToList(); retModel.userId = data.Id; retModel.userName = data.UserName; } return(retModel); } else { throw new Exception("Invalid Username or Password!!!"); } } catch (Exception ex) { throw ex; } }
private string CreateToken(LoginSuccessModel model) { DateTime issuedAt = DateTime.UtcNow; //set the time when it expires DateTime expires = DateTime.UtcNow.AddDays(1); var tokenHandler = new JwtSecurityTokenHandler(); ClaimsIdentity claims = new ClaimsIdentity(); claims.AddClaim(new Claim(ClaimTypes.NameIdentifier, model.userId)); foreach (var item in model.Rolenames) { var roleclaims = new Claim(ClaimTypes.Role, item); claims.AddClaim(roleclaims); } //ClaimsIdentity claimsIdentity = new ClaimsIdentity(new[] //{ // new Claim(ClaimTypes.NameIdentifier, model.userId) //}); const string sec = "P6CZQPptm7y535swXauhWQga9JuC2KZGpRWmFXpcNLJfMwELBezkvtYpHERVfmtFf7RZjVqqJvSbQLsHJ8ddJ3NCAd5ueCsCySYZPvdGDkveV92qn2S2WZCMHFRPQ7tb"; var now = DateTime.UtcNow; var securityKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(System.Text.Encoding.Default.GetBytes(sec)); var signingCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(securityKey, Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256Signature); //create the jwt var token = tokenHandler.CreateJwtSecurityToken(issuer: "http://localhost:53060", audience: "http://localhost:53060", subject: claims, notBefore: issuedAt, expires: expires, signingCredentials: signingCredentials); var tokenString = tokenHandler.WriteToken(token); return(tokenString); }
public IActionResult Post([FromBody] LoginModel model) { if (!ModelState.IsValid) { return(BadRequest("Некорректные данные в запросе")); } var userId = repo.CheckWebPassword(model); var identity = _authHandler.GetIdentity(model.UserName, userId, "customer"); if (identity == null) { return(NotFound(new { result = false, message = "Не верный логин и пароль" })); } var now = DateTime.UtcNow; var custInfo = repo.GetCustomerFIO(Convert.ToInt32(identity.Claims.ElementAt(2).Value)); if (custInfo == null) { return(NotFound(new { result = false, message = "Не верный логин и пароль" })); } string fio = null; if (custInfo != null) { fio = custInfo.FIO; } var jwt = new JwtSecurityToken( issuer: _options.Value.Issuer, audience: GetAUDIENCE(), notBefore: now, claims: identity.Claims, expires: now.AddMonths(1), signingCredentials: new SigningCredentials(AuthOptions.GetSymmetricSecurityKey(_options), SecurityAlgorithms.HmacSha256)); var endcodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); var response = new LoginSuccessModel { AccessToken = endcodedJwt, UserName = identity.Name, FIO = fio, Phone = custInfo.Phone, Email = custInfo.E_mail, Skype = custInfo.Skype, WhatsApp = custInfo.Whatsapp, Role = identity.Claims.ElementAt(1).Value, UserId = identity.Claims.ElementAt(2).Value, }; var mainImage = service.GetMainImage(); response.MainImage = mainImage; return(Ok(response)); }
public HttpResponseMessage Login(HttpRequestMessage request, LoginModel model) { HttpResponseMessage response = null; try { LoginSuccessModel data = _accountService.Login(model); if (data != null) { string token = CreateToken(data); response = request.CreateResponse(HttpStatusCode.OK, token); } else { response = request.CreateResponse(HttpStatusCode.Unauthorized); } } catch (Exception ex) { response = request.CreateResponse(HttpStatusCode.OK, ex.Message); } return(response); }
private async Task <LoginSuccessModel> CreateLoginResponse(User user) { var profile = mapper.Map <UserProfileResponse>(user); profile.AvatarFullUrl = fileService.ToFullUrl(user.AvatarUrl); var roles = await roleService.GetByUser(user.Id); if (roles != null) { profile.Roles = roles.Select(x => x.Name); } profile.Permissions = await roleService.GetPermissionsByUser(user.Id); var result = new LoginSuccessModel { AccessToken = await GenerateJwtToken(user), TokenType = "Bearer", ExpiresIn = tokenExpiredInDay * 24 * 60 * 60, UserProfile = profile }; return(result); }