public Token GetToken(User user) { var now = DateTime.Now; var expires = now.Add(TimeSpan.FromMinutes(tokenConfig.ExpiresMinutes)); var claims = new Claim[] { new Claim(ClaimTypes.NameIdentifier, user.Code), new Claim(ClaimTypes.Name, user.Name), }; if (user.Code == "001") { claims = claims.Append(new Claim(ClaimTypes.Role, "TestPutBookRole")).ToArray(); } SymmetricSecurityKey securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tokenConfig.SecurityKey)); SigningCredentials signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256); JwtSecurityToken token = new JwtSecurityToken(tokenConfig.Issuer, tokenConfig.Audience, claims, now, expires, signingCredentials); var tokenContent = new JwtSecurityTokenHandler().WriteToken(token); return(new Token { AccessToken = tokenContent }); }
public ComplexToken CreateToken(User user) { Claim[] claims = new Claim[] { new Claim(ClaimTypes.NameIdentifier, user.Code), new Claim(ClaimTypes.Name, user.Name) }; //下面对code为001的张三添加了一个Claim,用于测试在Token中存储用户的角色信息,对应测试在FlyLolo.JWT.API的BookController的Put方法,若用不到可删除 if (user.Code.Equals("001")) { claims = claims.Append(new Claim(ClaimTypes.Role, "TestPutBookRole")).ToArray(); } return(CreateToken(claims)); }
public async Task Invoke(HttpContext context, DatabaseContext database) { Company company = null; User user = null; string token = context.Request.Headers["Token"]; string companyID = context.Request.Headers["CompanyID"]; if (token != null) { user = await database.Users.Where(a => a.Token.Equals(token)).FirstOrDefaultAsync(); if (user != null) { company = await database.Companies.Where(a => a.ID.Equals(companyID)).FirstOrDefaultAsync(); if (company != null) { // This process is working with lazy loading. List <Privilege> privileges = user.Roles.Where(a => a.CompanyID.Equals(company.ID)).SelectMany(a => a.Role.Privileges.Select(b => b.Privilege)).Distinct().ToList(); // Step 4 Claim[] claims = new Claim[] { new Claim(ClaimTypes.NameIdentifier, user.ID.ToString()), new Claim("CompanyID", company.ID.ToString()), }; if (privileges != null && privileges.Count > 0) { privileges.ForEach(privilege => claims.Append(new Claim(ClaimTypes.UserData, privilege.Key))); } context.User.AddIdentity(new ClaimsIdentity(claims)); await this.request.Invoke(context); } } /* // Step 5 * else { * market.dto.BaseResponse bResponse = new dto.BaseResponse(); * bResponse.Result.Message = "Authorization failed."; * * await context.Response.WriteAsync(Newtonsoft.Json.JsonConvert.SerializeObject(bResponse)); * return; * }*/ } await this.request.Invoke(context); }
public Modeli.Korisnik Authenticate(string email, string password) { var user = _context.Korisnici.Include("KorisnikUloga.Uloga").FirstOrDefault(x => x.Email == email); // return null ako korisnik nije pronađen if (user == null) { return(null); } var newHash = GenerateHash(user.LozinkaSalt, password); if (newHash == user.LozinkaHash) { var claims = new Claim[] { new Claim(ClaimTypes.Name, user.KorisnikId.ToString()), new Claim(ClaimTypes.Email, user.Email) }; foreach (var role in user.KorisnikUloga) { claims.Append(new Claim(ClaimTypes.Role, role.Uloga.Naziv)); } var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(_appSettings.Secret); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(claims), Expires = DateTime.UtcNow.AddDays(7), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); var tokenString = tokenHandler.WriteToken(token); var korisnik = _mapper.Map <Modeli.Korisnik>(user); korisnik.Token = tokenString; korisnik.Token_Expiration_Time = token.ValidTo; return(korisnik); } return(null); }
public async Task <string> GetTokenAsync(IdentityUser user, DateTime authTime, DateTime expiresAt) { var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.UTF8.GetBytes(_settings.Secret); var claims = new Claim[] { new Claim(nameof(IdentityUser), user.ToJson()), new Claim(JwtClaimTypes.Audience, _settings.Aud), new Claim(JwtClaimTypes.Issuer, _settings.Iss), new Claim(JwtClaimTypes.Id, user.Id), new Claim(ClaimTypes.Sid, httpContextAccessor.HttpContext.Session.Id), new Claim(JwtClaimTypes.Name, user.UserName), new Claim(ClaimTypes.Name, user.UserName), }; var role = await userManager.GetRolesAsync(user); if (role != null) { string sub = ""; foreach (var item in role) { sub += item + ","; } if (user.Email.IsNotNullOrEmpty()) { claims.Append(new Claim(JwtClaimTypes.Email, user.Email)); claims.Append(new Claim(ClaimTypes.Email, user.Email)); } if (user.PhoneNumber.IsNotNullOrEmpty()) { claims.Append(new Claim(JwtClaimTypes.PhoneNumber, user.PhoneNumber)); claims.Append(new Claim(ClaimTypes.HomePhone, user.PhoneNumber)); } if (sub.IsNullOrEmpty()) { claims.Append(new Claim(JwtClaimTypes.Role, sub)); claims.Append(new Claim(ClaimTypes.Role, sub)); } } var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(claims), Expires = expiresAt, SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256) }; var token = tokenHandler.CreateToken(tokenDescriptor); return(tokenHandler.WriteToken(token)); }