/// <summary> /// Generate Token from user information /// </summary> /// <param name="Id">User id</param> /// <param name="username">UserName</param> /// <returns>TokenResponse</returns> public TokenResponse GenerateUserToken(long Id, string username) { var now = DateTime.UtcNow; var claims = new Claim[] { new Claim("id", Id.ToString()), new Claim("name", username), new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(now).ToString(), ClaimValueTypes.Integer64) }; // Create the JWT and write it to a string var jwt = new JwtSecurityToken( issuer: this.options.Issuer, audience: this.options.Audience, claims: claims, notBefore: now, expires: now.Add(this.options.Expiration), signingCredentials: this.options.SigningCredentials ?? TokenProvider.DefaultSigningCredentials()); var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); return new TokenResponse { access_token = encodedJwt, expires_in = (ulong)this.options.Expiration.TotalSeconds }; }
private async Task GenerateToken(HttpContext context) { var username = context.Request.Form["username"]; var password = context.Request.Form["password"]; var identity = await GetIdentity(username, password); if (identity == null) { context.Response.StatusCode = 400; await context.Response.WriteAsync("Invalid username or password."); return; } var now = DateTime.UtcNow; // Specifically add the jti (random nonce), iat (issued timestamp), and sub (subject/user) claims. // You can add other claims here, if you want: var claims = new[] { new Claim(JwtRegisteredClaimNames.Sub, username), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(now).ToString(), ClaimValueTypes.Integer64), new Claim(JwtRegisteredClaimNames.Email, "*****@*****.**", ClaimValueTypes.String) }; // Create the JWT and write it to a string var jwt = new JwtSecurityToken( issuer: _options.Issuer, audience: _options.Audience, claims: claims, notBefore: now, expires: now.Add(_options.Expiration), signingCredentials: _options.SigningCredentials); var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); var response = new { access_token = encodedJwt, expires_in = (int) _options.Expiration.TotalSeconds }; // Serialize and return the response context.Response.ContentType = "application/json"; await context.Response.WriteAsync(JsonConvert.SerializeObject(response, new JsonSerializerSettings {Formatting = Formatting.Indented})); }
//[Authorize(Policy = "RefreshTokenPolicy")] Should probably make this work public async Task<IActionResult> PostRefreshAccessToken() { var userName = User.FindFirst(ClaimTypes.NameIdentifier).Value; _logger.LogInformation("Fetching new access token for " + userName); var identity = await GetClaimsIdentity(userName); var claims = await GetClaims(userName); var claimsForAccessToken = claims.ToList(); claimsForAccessToken.Add(identity.FindFirst("role")); // Create the JWT security token and encode it. var jwtAccessToken = new JwtSecurityToken( issuer: _jwtOptions.Issuer, audience: _jwtOptions.Audience, claims: claimsForAccessToken.ToArray(), notBefore: _jwtOptions.NotBefore, expires: DateTime.UtcNow.Add(_jwtOptions.ValidFor), signingCredentials: _jwtOptions.SigningCredentials); var encodedJwtAccess = new JwtSecurityTokenHandler().WriteToken(jwtAccessToken); // Serialize and return the response var response = new { access_token = encodedJwtAccess, expires_in = (int)_jwtOptions.ValidFor.TotalSeconds }; var json = JsonConvert.SerializeObject(response, _serializerSettings); return new OkObjectResult(json); }
public Auth0User(IDictionary<string, string> accountProperties) { this.Auth0AccessToken = accountProperties.ContainsKey("access_token") ? accountProperties["access_token"] : string.Empty; this.IdToken = accountProperties.ContainsKey("id_token") ? accountProperties["id_token"] : string.Empty; this.Profile = accountProperties.ContainsKey("profile") ? accountProperties["profile"].ToJson() : null; this.RefreshToken = accountProperties.ContainsKey("refresh_token") ? accountProperties["refresh_token"] : string.Empty; this.State = accountProperties.ContainsKey("state") ? accountProperties["state"] : null; if (this.Profile?["exp"] != null) { this.IdTokenExpiresAt = UnixTimeStampToDateTime(double.Parse(this.Profile["exp"].ToString())); } else { var token = new JwtSecurityToken(this.IdToken); this.IdTokenExpiresAt = token.ValidTo; } }
public async Task <Response <Login> > WxLogin([FromBody] dynamic request) { string wxcode = request.wxcode; Login resultData = new Login(); string appid = Configuration.GetValue <string>("AppSetting:WxAppid"); string secret = Configuration.GetValue <string>("AppSetting:WxSecret"); string uri = $"https://api.weixin.qq.com/sns/jscode2session?appid={appid}&secret={secret}&js_code={wxcode}&grant_type=authorization_code"; string response = await Task.Run(() => { return(HttpHelper.HttpJsonGetRequest(uri)); }); if (!string.IsNullOrEmpty(response)) { WxLoginInfo wxInfo = JsonConvert.DeserializeObject <WxLoginInfo>(response); if (wxInfo != null && !string.IsNullOrEmpty(wxInfo.openid)) { resultData.OpenId = wxInfo.openid; resultData.UnionId = wxInfo.unionid; var claims = new Claim[] { new Claim(ClaimTypes.Name, wxInfo.openid), //new Claim(JwtRegisteredClaimNames.NameId, wxInfo.openid), //new Claim(JwtRegisteredClaimNames.UniqueName,string.IsNullOrEmpty(wxInfo.unionid)?"":wxInfo.unionid) }; var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration.GetValue <string>("AppSetting:JwtSigningKey"))); var token = new JwtSecurityToken( issuer: Configuration.GetValue <string>("AppSetting:JwtIssuer"), audience: Configuration.GetValue <string>("AppSetting:JwtAudience"), claims: claims, notBefore: DateTime.Now, expires: DateTime.Now.AddDays(1), signingCredentials: new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256) ); resultData.JwtToken = new JwtSecurityTokenHandler().WriteToken(token); //获取对应的宾馆 //var hotel = Hander.GetHotelByOpenId(wxInfo.openid); var manager = await Task.Run(() => { return(Hander.Get(m => m.WxOpenId == wxInfo.openid && m.IsDel.HasValue && !m.IsDel.Value)); }); if (manager != null) { resultData.Role = manager.Role; var hotel = await Task.Run(() => { return(HotelHander.Get(h => h.Id == manager.HotelId)); }); resultData.Hotel = hotel; } else { resultData.Role = -1; } } else { throw new Exception("微信登录接口返回异常!" + response); } } else { throw new Exception("微信登录接口返回为空"); } return(new Response <Login>() { Status = StatusEnum.Success, Massage = "登录成功", Data = resultData }); }
public async Task <IActionResult> DoBadgeToken([FromBody] BadgeTokenModel model) { var user = await _userManager.FindByNameAsync(model.Username); if (user == null) { user = new APUser { UserName = model.Username, Email = model.Username + "@badge.local" }; await _userManager.CreateAsync(user, model.Password); var uobj = model.Username; var name = model.Username; var obj = new ASObject(); obj["type"].Add(new ASTerm("Person")); obj["preferredUsername"].Add(new ASTerm(name)); obj["name"].Add(new ASTerm(name)); var id = await _entityData.UriFor(_entityStore, obj); obj["id"].Add(new ASTerm(id)); var inbox = await _newCollection("inbox", id); var outbox = await _newCollection("outbox", id); var following = await _newCollection("following", id); var followers = await _newCollection("followers", id); var likes = await _newCollection("likes", id); var blocks = await _newCollection("blocks", id); var blocked = await _newCollection("blocked", id); var blocksData = blocks.Data; blocksData["_blocked"].Add(new ASTerm(blocked.Id)); blocks.Data = blocksData; obj["following"].Add(new ASTerm(following.Id)); obj["followers"].Add(new ASTerm(followers.Id)); obj["blocks"].Add(new ASTerm(blocks.Id)); obj["likes"].Add(new ASTerm(likes.Id)); obj["inbox"].Add(new ASTerm(inbox.Id)); obj["outbox"].Add(new ASTerm(outbox.Id)); var userEntity = await _entityStore.StoreEntity(APEntity.From(obj, true)); await _entityStore.CommitChanges(); _context.UserActorPermissions.Add(new UserActorPermission { UserId = user.Id, ActorId = userEntity.Id, IsAdmin = true }); await _context.SaveChangesAsync(); } var u = await _signInManager.PasswordSignInAsync(model.Username, model.Password, false, false); if (!u.Succeeded) { return(Unauthorized()); } var firstActor = await _context.UserActorPermissions.FirstOrDefaultAsync(a => a.User == user); var claims = new Claim[] { new Claim(JwtRegisteredClaimNames.Sub, user.Id), new Claim(JwtTokenSettings.ActorClaim, firstActor.ActorId) }; var jwt = new JwtSecurityToken( issuer: _tokenSettings.Issuer, audience: _tokenSettings.Audience, claims: claims, notBefore: DateTime.UtcNow, expires: DateTime.UtcNow.Add(TimeSpan.FromDays(7)), signingCredentials: _tokenSettings.Credentials ); var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); return(Json(new BadgeTokenResponse { Actor = firstActor.ActorId, Token = encodedJwt })); }
public ActionResult GetToken([FromBody] Model.Login login) { System.IdentityModel.Tokens.Jwt.JwtSecurityToken token; Model.appsettings.TokenSettings instance; List <System.Security.Claims.Claim> claims; Microsoft.IdentityModel.Tokens.SigningCredentials credentials; // Token şimdiden ne kadar zaman sonra geçerli olsun. Hemen geçerli olsun diye null. DateTime?notWorkBeforeDate = null; // Token'ın kullanım süresini belirler. Daima kullanılsın diye null set edilebilir. DateTime?expirationDate = DateTime.Now.AddDays(7); if (!login.UserName.Equals("petro") && !login.Password.Equals("net")) { return(this.BadRequest("Hatali kullanici bilgileri!")); } // appsettings.json 'dan ilgili ayarları çekelim instance = new TokenSettings(); this.config.Bind("JwtSettings", instance); // Oluşan token bilgisini HMAC-SHA256 ile şifreleyeceğiz credentials = new SigningCredentials(instance.IssuerSigningKey, "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256"); // Token ile göndereceğimiz bilgileri ayarlayalım claims = new List <Claim> { new Claim("http://schemas.microsoft.com/ws/2008/06/identity/claims/role", "Yönetici"), new Claim("http://schemas.microsoft.com/ws/2008/06/identity/claims/role", "Servis Görevlisi"), // Uygulamaya özgü bir özellik eklerken: new Claim("Yetkiler", "Servis:C,R,U,D;Dosya:C,R"), // ister "xml schema" bilgisiyle ister bu bilgiyle eşleşmi ClaimTypes.xxx tipinin statik özellikleriyle new Claim(ClaimTypes.Country, "Türkiye"), new Claim(ClaimTypes.GivenName, "Cem Topkaya") }; var tokenDescriptor = new SecurityTokenDescriptor { Audience = instance.Audience, Expires = expirationDate, IssuedAt = DateTime.Now, Issuer = instance.Issuer, NotBefore = null, // null verdiğimiz için DateTime.Now değerini yazacak SigningCredentials = credentials, Subject = new ClaimsIdentity(claims) }; var tokenHandler = new JwtSecurityTokenHandler(); token = tokenHandler.CreateJwtSecurityToken(tokenDescriptor); return(Ok(new { login, Token = tokenHandler.WriteToken(token) })); token = new JwtSecurityToken( instance.Issuer, instance.Audience, (IEnumerable <Claim>)claims, notWorkBeforeDate, expirationDate, credentials); return(this.Ok(new JwtSecurityTokenHandler().WriteToken(token))); }
public IActionResult Login([FromBody] User user) { if (user == null) { return(BadRequest("Invalid client request")); } if (user.UserName == "phil" && user.Password == "linhph") { var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("PhilliplovesNguyet")); var signinCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256); var claims = new List <Claim> { new Claim(ClaimTypes.Name, user.UserName), new Claim(ClaimTypes.Role, "Admin") }; var tokeOptions = new JwtSecurityToken( issuer: "https://localhost:5001", audience: "https://localhost:5001", claims: claims, expires: DateTime.Now.AddHours(1), signingCredentials: signinCredentials ); var tokenString = new JwtSecurityTokenHandler().WriteToken(tokeOptions); return(Ok(new { Token = tokenString })); } else if (user.UserName == "nguyet" && user.Password == "nguyet") { var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("NguyetlovesPhillip")); var signinCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256); var claims = new List <Claim> { new Claim(ClaimTypes.Name, user.UserName), new Claim(ClaimTypes.Role, "Manager") }; var tokeOptions = new JwtSecurityToken( issuer: "https://localhost:5001", audience: "https://localhost:5001", claims: claims, expires: DateTime.Now.AddMinutes(30), signingCredentials: signinCredentials ); var tokenString = new JwtSecurityTokenHandler().WriteToken(tokeOptions); return(Ok(new { Token = tokenString })); } else if (user.UserName != "phil" || user.UserName != "nguyet") { var loginUser = _userService.Authenticate(user.UserName, user.Password); if (loginUser == null) { return(NotFound("User is not found")); } var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("Thisisforuseronly")); var signinCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256); var claims = new List <Claim> { new Claim(ClaimTypes.Name, loginUser.UserName), new Claim(ClaimTypes.Role, "User") }; var tokeOptions = new JwtSecurityToken( issuer: "https://localhost:5001", audience: "https://localhost:5001", claims: claims, expires: DateTime.Now.AddMinutes(10), signingCredentials: signinCredentials ); var tokenString = new JwtSecurityTokenHandler().WriteToken(tokeOptions); return(Ok(new { Id = loginUser.Id, UserName = loginUser.UserName, FirstName = loginUser.FirstName, LastName = loginUser.LastName, Token = tokenString })); } return(Unauthorized(new { message = "Username/Password is incorrect. Please try again!" })); }
private string EncodeToken(JwtSecurityToken token) { return(new JwtSecurityTokenHandler().WriteToken(token)); }
protected virtual Task<string> SignAsync(JwtSecurityToken jwt) { var handler = new JwtSecurityTokenHandler(); return Task.FromResult(handler.WriteToken(jwt)); }
protected string JWTConstructAssertionOld() { byte[] randomNumber = new byte[64]; using (var rng = new RNGCryptoServiceProvider()) { rng.GetBytes(randomNumber); } var claims = new List<Claim> { new Claim("sub", _config.EntityId), new Claim("box_sub_type", _config.EntityType), new Claim("jti", Convert.ToBase64String(randomNumber)), }; var token = new JwtSecurityToken(issuer: _cpnfig.clientId, audience: _config.BoxApiDeveloperEditionTokenUri, claims: claims, expires: DateTime.UtcNow.AddSeconds(30), signingCredentials: this.credentials); var tokenHandler = new JwtSecurityTokenHandler(); return tokenHandler.WriteToken(token); }
public async Task<IActionResult> Post(string userName, string password, bool rememberMe) { //todo: Ensure that these input values are not logged. var identity = await GetClaimsIdentity(userName, password, rememberMe); if (identity == null) { _logger.LogInformation($"Invalid username ({userName}))"); return BadRequest("Invalid credentials"); } var claims = await GetClaims(userName); var claimsForAccessToken = claims.ToList(); claimsForAccessToken.Add(identity.FindFirst("role")); var claimsForRefreshToken = claims.ToList(); claimsForRefreshToken.Add(new Claim("RefreshToken", "RefreshToken")); // Create the JWT security token and encode it. var jwtAccessToken = new JwtSecurityToken( issuer: _jwtOptions.Issuer, audience: _jwtOptions.Audience, claims: claimsForAccessToken.ToArray(), notBefore: _jwtOptions.NotBefore, expires: DateTime.UtcNow.Add(_jwtOptions.ValidFor), signingCredentials: _jwtOptions.SigningCredentials); var jwtRefreshToken = new JwtSecurityToken( issuer: _jwtOptions.Issuer, audience: _jwtOptions.Audience, claims: claimsForRefreshToken.ToArray(), notBefore: _jwtOptions.NotBefore, expires: DateTime.UtcNow.AddMonths(3), signingCredentials: _jwtOptions.SigningCredentials); var encodedJwtAccess = new JwtSecurityTokenHandler().WriteToken(jwtAccessToken); var encodedJwtRefresh = new JwtSecurityTokenHandler().WriteToken(jwtRefreshToken); //todo: Save refresh-token i database. So that it can be revoked. // Serialize and return the response var response = new { access_token = encodedJwtAccess, refresh_token = encodedJwtRefresh, expires_in = (int)_jwtOptions.ValidFor.TotalSeconds }; var json = JsonConvert.SerializeObject(response, _serializerSettings); return new OkObjectResult(json); }
public async Task <ServiceResult <UserTokenDto> > login([FromBody] UserLoginDto userLoginDto) { string mobile = userLoginDto.mobile; var result = new ServiceResult <UserTokenDto>(); users usermodel = await this.iuser.GetUserAsync(mobile); if (usermodel == null) { result.IsFailed("手机号错误"); return(result); } else { // 修改一下,登录信息 await this.iuser.UpdateLoginInfoAsync(mobile, usermodel.logintimes + 1); } var _role = usermodel.rolename; // 验证通过了 var claims = new Claim[] { //这里演示:3种定义载荷的方式 //1.System.Security.Claims.ClaimTypes new Claim(System.Security.Claims.ClaimTypes.Name, mobile), //2.System.IdentityModel.Tokens.Jwt.JwtRegisteredClaimNames new Claim(System.IdentityModel.Tokens.Jwt.JwtRegisteredClaimNames.Email, usermodel.email), //3.自定义名称 new Claim("mobile", mobile), //其实没有啥用,先记录着吧 new Claim("avatar", usermodel.avatar), // 角色 new Claim(System.Security.Claims.ClaimTypes.Role, _role), }; //Key的长度至少是16位 (注意密钥最少16位) //var key = new SymmetricSecurityKey( Encoding.UTF8.GetBytes( "1234567890123456key" ) ); var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(this.tokenConfigData.key)); //issuer代表颁发Token的Web应用程序,audience是Token的受理者, 暂时用不到,随便指定 var token = new JwtSecurityToken( issuer: this.tokenConfigData.issuer, // "http://localhost:5000" , audience: this.tokenConfigData.audience, // "http://localhost:5001" , claims: claims, notBefore: DateTime.Now, // 过期时间 expires: DateTime.Now.AddMinutes(this.tokenConfigData.expiresminute), signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256) ); var jwtToken = new JwtSecurityTokenHandler().WriteToken(token); // 把自己的数据带回去 result.IsSuccess(new UserTokenDto() { token = jwtToken, //rolename = _role , mobile = mobile, }); return(result); }
public JwtSecurityToken CreateJwtSecurityToken(TokenOptions tokenOptions, User user, SigningCredentials signingCredentials, List <OperationClaim> operationClaims) { var jwt = new JwtSecurityToken(issuer: tokenOptions.Issuer, audience: tokenOptions.Audience, expires: _accessTokenExpiration, notBefore: DateTime.Now, claims: SetClaims(user, operationClaims), signingCredentials: signingCredentials); return(jwt); }
private async Task CreateToken(HttpContext httpContext) { try { // Retrieve the relevant FORM data string username = httpContext.Request.Form["username"]; string password = httpContext.Request.Form["password"]; // check if there's an user with the given username var user = await UserManager.FindByNameAsync(username); // Fallback to support email address instead of username if (user == null && username.Contains("@")) { user = await UserManager.FindByEmailAsync(username); } var success = user != null && await UserManager.CheckPasswordAsync(user, password); if (success) { DateTime now = DateTime.Now; // add the registered claims for JWT // For more info, see https:tools.ietf.org/html/rfc7519#section-4.1 var claims = new[] { new Claim(JwtRegisteredClaimNames.Iss, Issuer), new Claim(JwtRegisteredClaimNames.Sub, user.Id), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), new Claim(JwtRegisteredClaimNames.Iat, new DateTimeOffset(now).ToUnixTimeSeconds().ToString(), ClaimValueTypes.Integer64) }; // Create the JWT and write it to string var token = new JwtSecurityToken( claims: claims, notBefore: now, expires: now.Add(TokenExpiration), signingCredentials: SigningCredentials ); var encodedToken = new JwtSecurityTokenHandler().WriteToken(token); // build the json response var jwt = new { access_token = encodedToken, expiration = (int)TokenExpiration.TotalSeconds }; // Return the token httpContext.Response.ContentType = "appication/json"; await httpContext.Response.WriteAsync(JsonConvert.SerializeObject(jwt)); return; } } catch (Exception ex) { throw ex; } httpContext.Response.StatusCode = 400; await httpContext.Response.WriteAsync("Invalid username or password"); }
async Task <IActionResult> loginDetails(UserVM model) { try { string email = "", userId = "", firstName = "", lastName = ""; Result result = await _auth.Login(model); if (result != null) { if (result.IsSuccess && result.Data != null) { UserVM userData = (UserVM)result.Data; email = ((UserVM)result.Data).Email; userId = ((UserVM)result.Data).UserId.ToString(); firstName = ((UserVM)result.Data).FirstName; lastName = ((UserVM)result.Data).LastName; var claims = new[] { new Claim(ClaimTypes.NameIdentifier, userId), new Claim("USERID", !string.IsNullOrEmpty(userId) ? userId : ""), new Claim("EMAIL", !string.IsNullOrEmpty(email) ? email : "") }; string tokenValue = _config.GetSection("AppSettings:Token").Value; byte[] tokenByte = Encoding.UTF8.GetBytes(tokenValue); var key = new SymmetricSecurityKey(tokenByte); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature); var JWToken = new JwtSecurityToken( issuer: "https://localhost:44319/", audience: "https://localhost:44319/", claims: GetUserClaims(userData), notBefore: new DateTimeOffset(DateTime.Now).DateTime, expires: new DateTimeOffset(DateTime.Now.AddDays(1)).DateTime, signingCredentials: creds ); var tokenHandler = new JwtSecurityTokenHandler(); var token = new JwtSecurityTokenHandler().WriteToken(JWToken); HttpContext.Session.SetString("JWToken", token.ToString()); return(Ok(new { Message = "Login Successful", token = token, statusCode = StatusCode(201), userId = userId, firstName = firstName, lastName = lastName, email = email != null ? email : "", })); } else { return(Unauthorized("Invalid username or password")); } } else { return(Unauthorized("Invalid username or password")); } } catch (Exception ex) { ex.Message.ToString(); return(BadRequest()); } }
public static LoginResponseData Execute(ApplicationUser user, ApiDbContext db, RefreshToken refreshToken) { var options = GetOptions(); var now = DateTime.UtcNow; var claims = new List <Claim>() { new Claim(JwtRegisteredClaimNames.NameId, user.Id), //new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), new Claim(JwtRegisteredClaimNames.Jti, user.Id.ToString()), new Claim(JwtRegisteredClaimNames.Iat, new DateTimeOffset(now).ToUniversalTime().ToUnixTimeSeconds().ToString(), ClaimValueTypes.Integer64), new Claim(JwtRegisteredClaimNames.Sub, user.UserName), }; var userClaims = db.UserClaims.Where(i => i.UserId == user.Id); foreach (var userClaim in userClaims) { claims.Add(new Claim(userClaim.ClaimType, userClaim.ClaimValue)); } var userRoles = db.UserRoles.Where(i => i.UserId == user.Id); foreach (var userRole in userRoles) { var role = db.Roles.Single(i => i.Id == userRole.RoleId); claims.Add(new Claim(Extensions.RoleClaimType, role.Name)); } if (refreshToken == null) { refreshToken = new RefreshToken() { UserId = user.Id, Token = Guid.NewGuid().ToString("N"), }; db.InsertNew(refreshToken); } refreshToken.IssuedUtc = now; refreshToken.ExpiresUtc = now.Add(options.Expiration); db.SaveChanges(); var jwt = new JwtSecurityToken( issuer: options.Issuer, audience: options.Audience, claims: claims.ToArray(), notBefore: now, expires: now.Add(options.Expiration), signingCredentials: options.SigningCredentials); var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); var response = new LoginResponseData { access_token = encodedJwt, refresh_token = refreshToken.Token, expires_in = (int)options.Expiration.TotalSeconds, userName = user.UserName, firstName = user.FirstName, lastName = user.LastName, isAdmin = user.Claims.Any(i => i.ClaimType == Extensions.AdminClaim) }; return(response); }
private static bool AreJwtSecurityTokensEqual(JwtSecurityToken jwt1, JwtSecurityToken jwt2, CompareContext context) { if (!AreEqual <JwtHeader>(jwt1.Header, jwt2.Header, context, AreJwtHeadersEqual)) { return(false); } if (!AreEqual <JwtPayload>(jwt1.Payload, jwt2.Payload, context, AreJwtPayloadsEqual)) { return(false); } if (!AreEnumsEqual <Claim>(jwt1.Claims, jwt2.Claims, context, AreClaimsEqual)) { return(false); } if (!string.Equals(jwt1.Actor, jwt2.Actor, context.StringComparison)) { return(false); } if (!AreEnumsEqual <string>(jwt1.Audiences, jwt2.Audiences, context, AreStringsEqual)) { return(false); } if (!string.Equals(jwt1.Id, jwt2.Id, context.StringComparison)) { return(false); } if (!string.Equals(jwt1.Issuer, jwt2.Issuer, context.StringComparison)) { return(false); } if (context.ExpectRawData && !string.Equals(jwt1.RawData, jwt2.RawData, context.StringComparison)) { return(false); } if (!string.Equals(jwt1.SignatureAlgorithm, jwt2.SignatureAlgorithm, context.StringComparison)) { return(false); } if (jwt1.ValidFrom != jwt2.ValidFrom) { return(false); } if (jwt1.ValidTo != jwt2.ValidTo) { return(false); } if (!AreEnumsEqual <SecurityKey>(jwt1.SecurityKeys, jwt2.SecurityKeys, context, AreSecurityKeysEqual)) { return(false); } // no reason to check keys, as they are always empty for now. //ReadOnlyCollection<SecurityKey> keys = jwtWithEntity.SecurityKeys; return(true); }
public async Task InvokeAsync(HttpContext context, RequestDelegate next) { var authenticationCookieName = ".AspNetCore.Cookies"; var authenticationCookieName1 = ".Token.jwt"; var cookie = context.Request.Cookies[authenticationCookieName]; var cookie1 = context.Request.Cookies[authenticationCookieName1]; // var y = secureDataFormat; var services = context.RequestServices;//.GetRequiredService<IServiceScopeFactory>().CreateScope()) if (cookie != null) { //services.GetService<IConfigurationSection>(); //Microsoft.Extensions.Configuration.IConfigurationSection appSettingsSection = services.GetRequiredService<IConfigurationSection>().GetSection("AppSettings"); //var key = Encoding.ASCII.GetBytes(services.GetRequiredService<AppSettings>().Secret); var key = Encoding.ASCII.GetBytes("OfED+KgbZ44xtu4e4+JSQWdtSgTnsuNixKy1nMVAf4Ewws8QL3IN33XusJhrz9HXmIrdyX2F41xJHG4fuj5/2Dzv3xjYYvqxexmg3X3X5TOf3WoMs1VNloJ7UnbqUJOiEjgK8sRdJntgfomO4U8s67cpysk0h9rc0He4xRspEjOapFfDg+VG8igidcNgbNDSSaV4491Fo3sq2aGSCtYvekzs7JwXJnNAyvDSJjfK/7M8MpxSMnm1vMscBXyiYFXhGC4wqWlYBE828/5DNyw3QZW5EjD7hvDrY5OlYd4smCTa53helNnJz5NT9HQaDbE2sMwIDAQABAoIBAEs63TvT94njrPDP3A/sfCEXg1F2y0D/PjzUhM1aJGcRiOUXnGlYdViGhLnnJoNZTZm9qI1LT0NWcDA5NmBN6gcrk2EApyTt1D1i4AQ66rYoTF9iEC4Wye28v245BYESA6IIelgIxXGsVyllERsbTkaphzib44bYfHmvwMxkn135Zfzd/NOXl/O32vYIomzrNEP+tN2444WXhhG8c8+iZ8PErBV3CqrYogYy97d2CeQbXcpd5unPiU4TK0nnzeBAXdgeYuJHFC45YHl9UvShRoe6CHR47ceIGp6WMc5BTyyTkZpctuYJTwaChdj/QuRSkTYmn6jFL+MRfYQJ8VVwSVo5DbkECgYEA4/YIMKcwObYcSuHzgkMwH645CRDoy9M98eptAoNLdJBHYz23U5IbGL1+qHDDCPXx123Ks9ZG7EEqyWezq4qwe2eoFoebLA5O6/xrYXoaeIb0!@#$94dbCF4D932hAkgAaAZkZVsSiWDCjYSV+444JoWX4NVBcIL9yyHRhaaPVULsdfTRbPsZQWq9+hMCgYEA48j4RGO7CaVpgUVobYasJnkGSdhkSCd1VwgvHH3vtuk7/JGUBRaZc0WZGcXkAJXnLh7QnDHOzWASdaxVgnuviaDi4CIkmTCfRqPesgDR2Iu35iQsH7P2/o1pzhpXQS/Ct6J7/GwJTqcXCvp4tfZDbFxS8oewzp4RstILj+pDyWECgYByQAbOy5xB8GGxrhjrOl1OI3V2c8EZFqA/NKy5y6/vlbgRpwbQnbNy7NYj+Y/mV80tFYqldEzQsiQrlei78Uu5YruGgZogL3ccj+izUPMgmP4f6+9XnSuN9rQ3jhy4k4zQP1BXRcim2YJSxhnGV+1hReLknTX2IwmrQxXfUW4xfQKBgAHZW8qSVK5bXWPjQFnDQhp92QM4cnfzegxe0KMWkp+VfRsrw1vXNx"); var validationParams = new TokenValidationParameters { ClockSkew = TimeSpan.Zero, ValidateAudience = true, //ValidAudience = Configuration["Token:Audience"], ValidAudience = "http://localhost:44330/", ValidateIssuer = true, // ValidIssuer = Configuration["Token:Issuer"], ValidIssuer = "http://localhost:44330/", // IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Configuration["Token:SigningKey"])), IssuerSigningKey = new SymmetricSecurityKey(key), ValidateIssuerSigningKey = true, RequireExpirationTime = true, ValidateLifetime = true }; var hostingEnvironment = services.GetRequiredService <IHostingEnvironment>(); var ticket = new JwtAuthTicketFormat(validationParams, services.GetRequiredService <IDataSerializer <AuthenticationTicket> >(), services.GetDataProtector(new[] { $"{hostingEnvironment.ApplicationName}-Auth1" })); AuthenticationTicket t = ticket.Unprotect(cookie); if (t != null) { var dt = DateTime.Now; var jwtSecurityTokenHandler = new JwtSecurityTokenHandler(); var token = jwtSecurityTokenHandler.ReadJwtToken(t.Properties.Items[".Token.jwt"]); var to = token.Claims.ToList(); var mail = to.Find(x => x.Type == ClaimTypes.Name).Value; if ((token.ValidTo.AddHours(1) - dt).TotalSeconds > 0 && (token.ValidTo.AddHours(1) - dt).TotalSeconds < 300) { var accessTokenResult = tokenGenerator.GenerateAccessTokenWithClaimsPrincipal( mail, token.Claims); JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler(); JwtSecurityToken tt = handler.ReadToken(accessTokenResult.AccessToken) as JwtSecurityToken; await context.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); await context.SignInAsync(accessTokenResult.ClaimsPrincipal, accessTokenResult.AuthProperties); } //var yyyyyy = context.User?.FindFirst(ClaimTypes.GivenName).Value; } } if (true) { await next(context); return; } context.Response.StatusCode = (int)HttpStatusCode.Unauthorized; }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure( IApplicationBuilder app, IMergePolicyRunnerFactory runnerFactory, IAzureDevOpsClientFactory azDoClientFactory, ILogger<Startup> logger) { app.UseSerilogRequestLogging(); app.Use(ExceptionHandler); app.UseRouting(); app.UseCors(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapGet("/", Home); endpoints.MapPost("/jwt", JwtRoute); endpoints.MapPost("/webhook", Webhook).RequireAuthorization(); endpoints.MapDelete("/policies", ClearPolicies); }); async Task Home(HttpContext context) { await context.Response.WriteAsync("Merge-a-Bot"); } async Task JwtRoute(HttpContext context) { using var sr = new StreamReader(context.Request.Body); var pat = await sr.ReadToEndAsync(); if (string.IsNullOrEmpty(pat)) { context.Response.StatusCode = StatusCodes.Status400BadRequest; await context.Response.WriteAsync("Body did not contain Personal Access Token"); return; } var claims = new List<Claim> { new Claim(JwtRegisteredClaimNames.Sub, pat), }; var token = new JwtSecurityToken( issuer: JwtIssuer, audience: null, claims: claims, expires: DateTime.UtcNow.Date.AddYears(1), signingCredentials: new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(JwtSigningKey)), SecurityAlgorithms.HmacSha256) ); var tokenValue = new JwtSecurityTokenHandler().WriteToken(token); await context.Response.WriteAsync(tokenValue); } async Task Webhook(HttpContext context) { var request = context.Request; if (!HttpMethods.IsPost(request.Method)) return; if (request.ContentType == null || !request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase)) return; var payload = await WebhookDeserializer.DeserializeAsync(request.Body); var pat = context.User.FindFirstValue(ClaimTypes.NameIdentifier); if (payload != null) { var azDoClient = azDoClientFactory.Create(pat); var organization = payload.Resource.Repository.GetOrganization(); var factoryContext = new MergePolicyRunnerFactoryContext(azDoClient, payload.Resource.Repository.Id, organization); var runner = await runnerFactory.CreateAsync(factoryContext); await runner.RunAsync(azDoClient, payload); } } async Task ExceptionHandler(HttpContext context, Func<Task> next) { try { await next(); } catch (Exception ex) { logger.LogError(new EventId(1, "UnhandledError"), ex, "Unhandled error"); context.Response.StatusCode = 200; } } Task ClearPolicies(HttpContext context) { var org = context.Request.Query["organization"]; var repoId = context.Request.Query["repositoryId"]; if (string.IsNullOrEmpty(org) || string.IsNullOrEmpty(repoId)) { context.Response.StatusCode = (int)HttpStatusCode.BadRequest; return Task.CompletedTask; } runnerFactory.Clear(new MergePolicyRunnerFactoryContext(repoId, org)); return Task.CompletedTask; } }
private IList <Claim> ParseClaims(JwtSecurityToken tokenContent) { var claims = tokenContent.Claims.ToList(); return(claims); }
/// <summary> /// Processes the oidc authorization response. /// </summary> /// <param name="tenant"></param> /// <param name="code">The code.</param> /// <param name="authState">The authentication state.</param> /// <param name="requestBaseUrl">The request base url.</param> /// <param name="httpClient">The HTTP client.</param> /// <returns>Task.</returns> public async Task <OpenIdConnectRequestContextResult> ProcessOidcAuthorizationResponse(string tenant, string code, OpenIdConnectAuthorizationState authState, Uri requestBaseUrl, IHttpClient httpClient) { if (string.IsNullOrWhiteSpace(tenant)) { throw new ArgumentNullException(nameof(tenant)); } if (string.IsNullOrWhiteSpace(code)) { throw new ArgumentNullException(nameof(code)); } if (authState == null) { throw new ArgumentNullException(nameof(authState)); } if (requestBaseUrl == null) { throw new ArgumentNullException(nameof(requestBaseUrl)); } if (httpClient == null) { throw new ArgumentNullException(nameof(httpClient)); } ValidateAuthState(authState); long identityProviderId; string oidcClientId; Guid? oidcClientSecretSecureId; string oidcIdentityClaim; string oidcConfigurationUrl; using (new SecurityBypassContext()) using (new TenantAdministratorContext(authState.TenantId)) { var requestContext = RequestContext.GetContext(); if (string.Compare(requestContext.Tenant.Name, tenant, StringComparison.OrdinalIgnoreCase) != 0) { throw new AuthenticationException("The tenant is invalid."); } var oidcIdentityProvider = ReadiNow.Model.Entity.Get <OidcIdentityProvider>(authState.IdentityProviderId, GetOidcProviderFieldsToLoad()); if (oidcIdentityProvider == null) { throw new AuthenticationException("The identity provider does not exist."); } ValidateOidcProviderFields(oidcIdentityProvider); // Store any required entity model fields upfront. // Any code running after the await statement may run a different thread identityProviderId = oidcIdentityProvider.Id; oidcClientId = oidcIdentityProvider.OidcClientId; oidcClientSecretSecureId = oidcIdentityProvider.OidcClientSecretSecureId; oidcIdentityClaim = oidcIdentityProvider.OidcUserIdentityClaim; oidcConfigurationUrl = oidcIdentityProvider.OidcIdentityProviderConfigurationUrl; } OpenIdConnectConfiguration oidcConfig; try { oidcConfig = await _configurationManager.GetIdentityProviderConfigurationAsync(oidcConfigurationUrl); } catch (Exception ex) { throw new OidcProviderInvalidConfigurationException(ex); } JwtSecurityToken idToken = null; try { var authResponse = await GetAuthorizationTokens(tenant, code, oidcClientSecretSecureId, oidcClientId, requestBaseUrl, oidcConfig, httpClient); const int maxRetries = 2; int retryCount = 0; while (retryCount <= maxRetries) { try { if (retryCount > 0) { // Are retrying due to an error. // Remove the config from the cache and get a fresh copy _configurationManager.RemoveIdentityProviderConfiguration(oidcConfigurationUrl); oidcConfig = await _configurationManager.GetIdentityProviderConfigurationAsync(oidcConfigurationUrl); } idToken = ValidateIdentityToken(authResponse.IdToken, oidcClientId, authState.Nonce, oidcConfig); // Got the token, so break out of retry loop. break; } catch { retryCount++; if (retryCount >= maxRetries) { throw; } } } } catch { // Id provider may have cycled keys. Remove the configuration so that the next request gets updated config. _configurationManager.RemoveIdentityProviderConfiguration(oidcConfigurationUrl); throw; } return(GetRequestContextData(idToken, authState, identityProviderId, oidcIdentityClaim)); }
private async Task GenerateToken(HttpContext context) { var username = context.Request.Form["username"]; var password = context.Request.Form["password"]; var ipAddress = context.Features.Get <IHttpConnectionFeature>()?.RemoteIpAddress.ToString(); if (string.IsNullOrWhiteSpace(ipAddress)) { ipAddress = "Not Exists"; } var url = context.Request.Host.HasValue ? context.Request.Host.Value.ToString() : string.Empty; var identity = await GetIdentity(username, password, ipAddress); if (identity == null) { context.Response.StatusCode = 400; await context.Response.WriteAsync("Invalid username or password."); return; } var now = DateTime.UtcNow; string roleId = string.Empty; foreach (var claim in identity.Claims) { if (claim.Type == "RoleId") { roleId = claim.Value; } } // Specifically add the jti (random nonce), iat (issued timestamp), and sub (subject/user) claims. // You can add other claims here, if you want: var claims = new List <Claim> { new Claim(JwtRegisteredClaimNames.Sub, username), new Claim(JwtRegisteredClaimNames.Typ, roleId), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(now).ToString(), ClaimValueTypes.Integer64) }; foreach (var item in identity.Claims) { claims.Add(new Claim(item.Type, item.Value)); } // Create the JWT and write it to a string var jwt = new JwtSecurityToken( issuer: _options.Issuer, audience: _options.Audience, claims: claims, notBefore: now, expires: now.Add(_options.Expiration), signingCredentials: _options.SigningCredentials); var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); var response = new { access_token = encodedJwt, expires_in = (int)_options.Expiration.TotalSeconds }; // Serialize and return the response context.Response.ContentType = "application/json"; await context.Response.WriteAsync(JsonConvert.SerializeObject(response, new JsonSerializerSettings { Formatting = Formatting.Indented })); }
private string GetClientIdFromJwt(string token) { try { var jwt = new JwtSecurityToken(token); var clientId = jwt.Audiences.FirstOrDefault(); return clientId; } catch (Exception ex) { _logger.LogError("Malformed JWT token", ex); return null; } }
public HomePage(JwtSecurityToken token) { InitializeComponent(); //BindingContext = new HomeViewModel(); }
public async Task <IActionResult> LoginAsync(LoginViewModel model) { var user = await _dbContext.Users.FirstOrDefaultAsync(b => b.UserName == model.UserName || b.Email == model.UserName); if (user == null) { _logger.LogInformation($"未注册用户: {model.UserName},尝试登录!"); return(BadRequest(ApiResponse.Error("用户不存在"))); } var result = await _signInManager.CheckPasswordSignInAsync(user, model.Password, lockoutOnFailure : true); if (result.Succeeded) { //获取用户所有的claims var userclaims = await _userManager.GetClaimsAsync(user); var roleClaims = await _dbContext.UserRoles.Join(_dbContext.Roles, a => a.RoleId, b => b.Id, (a, b) => new { a, b }) .Join(_dbContext.RoleClaims, x => x.b.Id, c => c.RoleId, (x, c) => new { x, c }) .AsNoTracking().Where(b => b.x.a.UserId == user.Id) .Select(d => new Claim(d.c.ClaimType, d.c.ClaimValue)).ToListAsync(); var claims = roleClaims.Union(userclaims).Distinct().ToList(); claims.Add(new Claim("sub", user.Id.ToString())); claims.Add(new Claim("name", user.UserName)); claims.Add(new Claim("avatar", user.Avatar ?? "")); //获得 加密后的key var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSetting.SecretKey)); var cred = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); //使用加密后的key 创建 登录证书 //生产加密token var token = new JwtSecurityToken( _jwtSetting.Issuer, _jwtSetting.Audience, claims, DateTime.Now, DateTime.Now.AddHours(4), cred ); //返回token return(Ok(ApiResponse.Ok(new{ token = new JwtSecurityTokenHandler().WriteToken(token) }))); } if (result.IsNotAllowed) { var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); var callbackUrl = Url.Action( "ConfirmEmailAsync", "Account", new { code, userId = user.Id }, protocol: Request.Scheme); await _emailService.SendAsync(user.Email, "邮箱验证", $"请点击链接,已验证你的邮箱<a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>验证邮箱</a>.", true); return(BadRequest(ApiResponse.Error("邮箱未验证,请登录邮箱验证!"))); } //账号被锁定 if (result.IsLockedOut) { _logger.LogWarning($"账户被锁定: {model.UserName} "); return(BadRequest(ApiResponse.Error("账号被锁定,无法登录,请联系管理员!"))); } return(BadRequest(ApiResponse.Error("用户名密码不匹配"))); }
private static DateTime GetExpirationDateTimeUtcFromToken(string token) { var jwtSecurityToken = new JwtSecurityToken(token); return(jwtSecurityToken.ValidTo); }
private static void SetPrincipal(JwtSecurityToken token) { Thread.CurrentPrincipal = new ClaimsPrincipal(new ClaimsIdentity(token.Claims, "JWT")); }
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { if (!CanHandleAuthentication(request)) { return base.SendAsync(request, cancellationToken); } var tokenStringFromHeader = GetTokenStringFromHeader(request); var tokenStringFromCookie = GetTokenStringFromCookie(CookieNameToCheckForToken); var tokenString = tokenStringFromHeader ?? tokenStringFromCookie; if (string.IsNullOrEmpty(tokenString)) { return base.SendAsync(request, cancellationToken); } JwtSecurityToken token; try { token = new JwtSecurityToken(tokenString); } catch (Exception ex) { return base.SendAsync(request, cancellationToken); } //使用SymmetricKey生成用于验证Token的SigningToken //string SymmetricKey = "cXdlcnR5dWlvcGFzZGZnaGprbHp4Y3Zibm0xMjM0NTY="; //SigningToken = new BinarySecretSecurityToken(Convert.FromBase64String(SymmetricKey)); //GetSigningToken(request); SigningToken = jwtAuthorizationService.GetSigningToken(request); if (SigningToken != null && token.SignatureAlgorithm != null) { if (token.SignatureAlgorithm.StartsWith("RS") && !(SigningToken is X509SecurityToken)) { return base.SendAsync(request, cancellationToken); } if (token.SignatureAlgorithm.StartsWith("HS") && !(SigningToken is BinarySecretSecurityToken)) { return base.SendAsync(request, cancellationToken); } } var parameters = new TokenValidationParameters { ValidAudience = AllowedAudience, IssuerSigningToken = SigningToken, ValidIssuer = Issuer, ValidAudiences = AllowedAudiences, //ValidateLifetime = true }; try { IPrincipal principal = jwtAuthorizationService.TokenAuthorization(token, parameters); SetPrincipal(principal); //测试Principal中是否存在token中的Claim //ClaimsPrincipal cprincipal = principal as ClaimsPrincipal; //string Roles = cprincipal.Claims.FirstOrDefault(p => p.Type == "Roles").Value; } #region 异常处理 catch (SecurityTokenExpiredException e) { var response = new HttpResponseMessage((HttpStatusCode)440) { Content = new StringContent("Security token expired exception") }; var tsc = new TaskCompletionSource<HttpResponseMessage>(); tsc.SetResult(response); return tsc.Task; } catch (SecurityTokenSignatureKeyNotFoundException e) { var response = new HttpResponseMessage(HttpStatusCode.Unauthorized) { Content = new StringContent("Untrusted signing cert") }; var tsc = new TaskCompletionSource<HttpResponseMessage>(); tsc.SetResult(response); return tsc.Task; } catch (SecurityTokenInvalidAudienceException e) { var response = new HttpResponseMessage(HttpStatusCode.Unauthorized) { Content = new StringContent("Invalid token audience") }; var tsc = new TaskCompletionSource<HttpResponseMessage>(); tsc.SetResult(response); return tsc.Task; } catch (SecurityTokenValidationException e) { var response = new HttpResponseMessage(HttpStatusCode.Unauthorized) { Content = new StringContent("Invalid token") }; var tsc = new TaskCompletionSource<HttpResponseMessage>(); tsc.SetResult(response); return tsc.Task; } catch (SignatureVerificationFailedException e) { var response = new HttpResponseMessage(HttpStatusCode.Unauthorized) { Content = new StringContent("Invalid token signature") }; var tsc = new TaskCompletionSource<HttpResponseMessage>(); tsc.SetResult(response); return tsc.Task; } catch (Exception e) { throw; } #endregion return base.SendAsync(request, cancellationToken); }
public override void ValidateJwtSecutiryToken(JwtSecurityToken jwtSecurityToken) { if (string.IsNullOrEmpty(Configuration.JsonWebKeySetEndpoint)) { throw new InvalidOperationException("A configuração 'JsonWebKeySetEndpoint' não pode ser vazia."); } var keysResponse = HttpClientFactory.Instance.GetAsync(Configuration.JsonWebKeySetEndpoint).Result; if (!keysResponse.IsSuccessStatusCode) { throw new InvalidOperationException($"Falha ao recuperar JsonWebKeySet"); } var rawKeys = keysResponse.Content.ReadAsStringAsync().Result; if (string.IsNullOrEmpty(rawKeys)) { throw new InvalidOperationException($"JsonWebKeySet recebido está vazio"); } Microsoft.IdentityModel.Tokens.JsonWebKeySet jsonWebKeySet = JsonConvert.DeserializeObject <Microsoft.IdentityModel.Tokens.JsonWebKeySet>(rawKeys); if (jsonWebKeySet == null) { throw new InvalidOperationException($"JsonWebKeySet recebido está nulo"); } if (string.IsNullOrEmpty(Configuration.Issuer)) { throw new InvalidOperationException("A configuração 'Issuer' não pode ser vazia."); } if (string.IsNullOrEmpty(Configuration.ClientID)) { throw new InvalidOperationException("A configuração 'ClientID' não pode ser vazia."); } if (!_jwtSecurityTokenHandler.CanValidateToken) { throw new InvalidOperationException("SecurityTokenHandler não pode validar o token"); } var validationParameters = new TokenValidationParameters { ValidIssuer = Configuration.Issuer, ValidAudiences = new[] { Configuration.ClientID }, IssuerSigningKeys = jsonWebKeySet.GetSigningKeys(), ValidateIssuer = true, ValidateAudience = true, ValidateIssuerSigningKey = true, ValidateLifetime = true, }; var claimsPrincipal = _jwtSecurityTokenHandler.ValidateToken(jwtSecurityToken.RawData, validationParameters, out SecurityToken validatedToken); if (claimsPrincipal == null) { throw new InvalidOperationException("ClaimsPrincipal está nulo"); } if (!(validatedToken is JwtSecurityToken)) { throw new InvalidOperationException("ValidatedToken está nulo ou inválido"); } }
public bool GetHttpPost(string postData, string Path) { WebRequest request = WebRequest.Create(Path); byte[] byteArray = Encoding.UTF8.GetBytes(postData); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = byteArray.Length; try { Stream dataStream = request.GetRequestStream(); dataStream.Write(byteArray, 0, byteArray.Length); dataStream.Close(); WebResponse response = request.GetResponse(); dataStream = response.GetResponseStream(); StreamReader reader = new StreamReader(dataStream); string responseFromServer = reader.ReadToEnd(); reader.Close(); dataStream.Close(); response.Close(); var jss = new JavaScriptSerializer(); object data = jss.DeserializeObject(responseFromServer); var handler = new JwtSecurityTokenHandler(); foreach (var item in (IEnumerable <KeyValuePair <string, object> >)data) { if (item.Key.ToLower() == "refresh") { _tokenRefresh = (string)item.Value; } if (item.Key.ToLower() == "access") { _tokenAccess = (string)item.Value; TokenAccessKey = _tokenAccess; JwtSecurityToken jsonToken = (JwtSecurityToken)handler.ReadToken(_tokenRefresh); foreach (KeyValuePair <string, object> i in jsonToken.Payload) { if (i.Key.ToLower() == "user_id") { UserId = Convert.ToInt32(i.Value); } } } } ReturnMsg = _objMsg.GetSystemMsg(EnumMessage.LoginSuccess); return(true); } catch (WebException e) { using (WebResponse r = e.Response) { var httpResponse = (HttpWebResponse)r; if (httpResponse != null) { Debug.Print(httpResponse.StatusDescription); ValidateResponseErrorCode((int)httpResponse.StatusCode); } else { ValidateResponseErrorCode(0); } } return(false); } }
internal JwtToken(JwtSecurityToken token) { this.token = token; }
public string IntoString(JwtSecurityToken token) { return(new JwtSecurityTokenHandler().WriteToken(token)); }
public string WriteToken(JwtSecurityToken jwt) { return(_jwtSecurityTokenHandler.WriteToken(jwt)); }
public async Task <UserManagerResponse> LoginUserAsync(LoginViewModel model) { var user = await _userManager.FindByEmailAsync(model.Email); if (user == null) { return(new UserManagerResponse { Message = "Invalid email or password", IsSuccess = false, }); } var result = await _userManager.CheckPasswordAsync(user, model.Password); if (!result) { return new UserManagerResponse { Message = "Invalid email or password", IsSuccess = false, } } ; var role = await _userManager.GetRolesAsync(user); var claims = new[] { new Claim(ClaimTypes.Email, model.Email), new Claim(ClaimTypes.NameIdentifier, user.Id), new Claim(ClaimTypes.Role, role[0]) }; var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_iConfiguration["AuthSettings:Key"])); var token = new JwtSecurityToken( issuer: _iConfiguration["AuthSettings:Issuer"], audience: _iConfiguration["AuthSettings:Audience"], claims: claims, expires: DateTime.Now.AddDays(30), signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256)); var tokenAsString = new JwtSecurityTokenHandler().WriteToken(token); var userView = new AppUserViewModel { Email = user.Email, Firstname = user.FirstName, Lastname = user.LastName }; return(new UserManagerResponse { Token = tokenAsString, AppUser = userView, IsSuccess = true, TokenExpireDate = token.ValidTo }); } }
private async Task CreateToken(HttpContext httpContext) { try { //get form POST data string email = httpContext.Request.Form["email"]; string password = httpContext.Request.Form["password"]; ApplicationUser user = null; if (!string.IsNullOrEmpty(httpContext.Request.Form["name"])) { string name = httpContext.Request.Form["name"]; //create user user = new ApplicationUser() { UserName = name, Email = email }; if (await UserManager.FindByEmailAsync(email) == null) { try { await UserManager.CreateAsync(user, password); await UserManager.AddToRoleAsync(user, "Registered"); } catch (Exception) { await UserManager.DeleteAsync(user); throw; } } } else { //check email user = await UserManager.FindByEmailAsync(email); } var success = user != null && await UserManager.CheckPasswordAsync(user, password); if (success) { DateTime now = DateTime.UtcNow; //create the claims about the user for the token var claims = new List <Claim>() { new Claim(JwtRegisteredClaimNames.Iss, Issuer), new Claim(JwtRegisteredClaimNames.Sub, user.Id), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), new Claim(JwtRegisteredClaimNames.Iat, new DateTimeOffset(now) .ToUnixTimeSeconds() .ToString(), ClaimValueTypes.Integer64), new Claim(JwtRegisteredClaimNames.Email, user.Email), new Claim(JwtRegisteredClaimNames.GivenName, user.UserName) }; var roles = await UserManager.GetRolesAsync(user); foreach (var role in roles) { claims.Add(new Claim(ClaimTypes.Role, role)); } //create the actual token var token = new JwtSecurityToken( claims: claims, notBefore: now, expires: now.Add(TokenExpiration), signingCredentials: SigningCredentials); var encodedToken = new JwtSecurityTokenHandler().WriteToken(token); //create the response. This is an anonymous type; no need to create a special class to hold two props. var jwt = new { access_token = encodedToken, expiration = (int)TokenExpiration.TotalSeconds }; httpContext.Response.ContentType = "application/json"; // this should look familiar await httpContext.Response.WriteAsync(JsonConvert.SerializeObject(jwt)); return; } } catch (Exception) { throw; } //if we make it this far, we could not authenticate the user httpContext.Response.StatusCode = 400; await httpContext.Response.WriteAsync("Invalid username or password."); }
public async Task <IActionResult> Register([FromBody] Customer user) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var userIdentified = _context.Customers.FirstOrDefault(u => u.CustomerEmail == user.CustomerEmail); if (userIdentified != null) { return(Unauthorized("Username already exists")); } else { Customer cust = new Customer() { Username = user.Username, Password = user.Password, CustomerFirstName = user.CustomerFirstName, CustomerLastName = user.CustomerLastName, CustomerEmail = user.CustomerEmail, CustomerAddress = user.CustomerAddress, CustomerPhoneNumber = user.CustomerPhoneNumber, State = user.State, ZipCode = user.ZipCode }; _context.Customers.Add(cust); _context.SaveChanges(); user.CustomerID = _context.Customers.FirstOrDefault(u => u.CustomerEmail == user.CustomerEmail).CustomerID; //Add Claims var claims = new[] { new Claim(JwtRegisteredClaimNames.UniqueName, "data"), new Claim(JwtRegisteredClaimNames.Sub, "data"), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), }; var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("1234567890abcdef")); //Secret var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var token = new JwtSecurityToken("me", "you", claims, expires: DateTime.Now.AddMinutes(30), signingCredentials: creds); System.Diagnostics.Debug.WriteLine("TokenController TokenMethod3"); var accesstoken = new JwtSecurityTokenHandler().WriteToken(token); return(Ok(new { access_token = new JwtSecurityTokenHandler().WriteToken(token), expires_in = DateTime.Now.AddMinutes(30), token_type = "bearer", firstName = user.CustomerFirstName, lastName = user.CustomerLastName, customerID = user.CustomerID, email = user.CustomerEmail })); } }
// Login public async Task <BaseApiResponse> LoginAsync(UserForLoginDto userForLoginDto) { if (userForLoginDto == null) { return(BaseApiResponseHelper.GenerateApiResponse(false, "login", null, new List <string> { "Email or password is null." })); } var user = await _userManager.FindByEmailAsync(userForLoginDto.Email); if (user == null) { return(BaseApiResponseHelper.GenerateApiResponse(false, "login", null, new List <string> { "Could not find any accounts registered with this email." })); } // Checking user password if (await _userManager.CheckPasswordAsync(user, userForLoginDto.Password)) { JwtSecurityToken jwtSecurityToken = await CreateJwtToken(user); var roles = await _userManager.GetRolesAsync(user).ConfigureAwait(false); var refreshToken = string.Empty; var refreshTokenExpiration = new DateTime(); // Check if user has any active refreshToken then give them this refreshToken if (user.RefreshTokens.Any(token => token.IsActive)) { var activeRefreshToken = user.RefreshTokens.Where(token => token.IsActive == true).FirstOrDefault(); refreshToken = activeRefreshToken.Token; refreshTokenExpiration = activeRefreshToken.Expires; } else // Otherwise create new refreshToken then update it to the database { var newRefreshToken = CreateRefreshToken(); user.RefreshTokens.Add(newRefreshToken); refreshToken = newRefreshToken.Token; refreshTokenExpiration = newRefreshToken.Expires; _context.Update(user); _context.SaveChanges(); } var userForAuthenticationDto = new UserForAuthenticationDto() { FirstName = user.FirstName, LastName = user.LastName, Username = user.UserName, Email = user.Email, Roles = roles, AccessToken = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken), RefreshToken = refreshToken, RefreshTokenExpiration = refreshTokenExpiration }; return(BaseApiResponseHelper.GenerateApiResponse(true, "Logged in", new List <UserForAuthenticationDto> { userForAuthenticationDto }, null)); } return(BaseApiResponseHelper.GenerateApiResponse(false, "login", null, new List <string> { "Username or password is incorrect." })); }
public async Task<IActionResult> Login([FromBody] UserLoginModel user) { if (!ModelState.IsValid) { return BadRequest($"{this.GetModelStateAllErrors()}"); } string userId; try { userId = await GetUserIdByEmailAndPassword(user); if (userId == null) { return BadRequest("Invalid email address and/or password"); } } catch (Exception ex) { _logger.LogError(LoggingEvents.ACCOUNT_LOGIN, ex, $"Login exception for user with email - '{user.Email}'"); return this.InternalServerError(); } var claims = new[] { new Claim(JwtRegisteredClaimNames.Sub, userId), new Claim(JwtRegisteredClaimNames.Email, user.Email), new Claim(JwtRegisteredClaimNames.Jti, await _jwtOptions.JtiGenerator()), new Claim( JwtRegisteredClaimNames.Iat, ToUnixEpochDate(_jwtOptions.IssuedAt).ToString(), ClaimValueTypes.Integer64 ) }; // Create the JWT security token and encode it. var jwt = new JwtSecurityToken( issuer: _jwtOptions.Issuer, audience: _jwtOptions.Audience, claims: claims, notBefore: _jwtOptions.NotBefore, expires: _jwtOptions.Expiration, signingCredentials: _jwtOptions.SigningCredentials); try { var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); // Serialize and return the response var response = new { access_token = encodedJwt, expires_in = (int)_jwtOptions.ValidFor.TotalSeconds }; //var json = JsonConvert.SerializeObject(response, _serializerSettings); return Ok(response); } catch (Exception ex) { _logger.LogError(LoggingEvents.ACCOUNT_LOGIN ,ex, "Could not generate JWT Token"); return this.InternalServerError(); // TODO: add the following error message - "There was an issue with login. Please try again later!" } }
protected override Task<AuthenticationTicket> GetUserInformationAsync(OpenIdConnectMessage message, JwtSecurityToken jwt, AuthenticationTicket ticket) { var claimsIdentity = (ClaimsIdentity)ticket.Principal.Identity; if (claimsIdentity == null) { claimsIdentity = new ClaimsIdentity(); } claimsIdentity.AddClaim(new Claim("test claim", "test value")); return Task.FromResult(new AuthenticationTicket(new ClaimsPrincipal(claimsIdentity), ticket.Properties, ticket.AuthenticationScheme)); }