/// <summary> /// Verify the signature of a JWT /// </summary> /// <param name="jwt">JWT</param> /// <param name="audience">The Client</param> /// <param name="secret">The secret Key</param> /// <returns></returns> public bool VerifyJWTSignature(string jwt) { bool valid = true; var secKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(Encoding.Default.GetBytes(_secret)); var validationParameters = new TokenValidationParameters() { ValidateAudience = true, ValidAudience = _audience, ValidateIssuer = true, ValidIssuer = _issuer, ValidateIssuerSigningKey = true, IssuerSigningKey = secKey, RequireExpirationTime = true, ValidateLifetime = true, ClockSkew = TimeSpan.Zero }; try { SecurityToken mytoken = new JwtSecurityToken(); var myTokenHandler = new JwtSecurityTokenHandler(); var myPrincipal = myTokenHandler.ValidateToken(jwt, validationParameters, out mytoken); } catch (Exception ex) { valid = false; } return(valid); }
private string GenerateJSONWebToken(Users userInfo) { var securityKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"])); var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256); List <Claim> claims = new List <Claim>() { new Claim(JwtRegisteredClaimNames.Sub, userInfo.Email), new Claim(ClaimTypes.NameIdentifier, userInfo.Email.ToString()), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()) }; if (userInfo.Email == "admin!@123") { claims.Add(new Claim(ClaimTypes.Role, "Admin")); } var token = new JwtSecurityToken(_config["Jwt:Issuer"], _config["Jwt:Issuer"], claims, expires: DateTime.Now.AddMinutes(30), signingCredentials: credentials); return(new JwtSecurityTokenHandler().WriteToken(token)); }
public string Protect(AuthenticationTicket data) { if (data == null) { throw new ArgumentNullException("data"); } string audienceId = ConfigurationManager.AppSettings["as:AudienceId"]; string symmetricKeyAsBase64 = ConfigurationManager.AppSettings["as:AudienceSecret"]; var keyByteArray = TextEncodings.Base64Url.Decode(symmetricKeyAsBase64); var securityKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(keyByteArray); var signingKey = new Microsoft.IdentityModel.Tokens.SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature); var issued = data.Properties.IssuedUtc; var expires = data.Properties.ExpiresUtc; var token = new JwtSecurityToken(_issuer, audienceId, data.Identity.Claims, issued.Value.UtcDateTime, expires.Value.UtcDateTime, signingKey); var handler = new JwtSecurityTokenHandler(); var jwt = handler.WriteToken(token); return(jwt); }
public string CreateToken(Dictionary <string, string> claims) { //Set issued at date DateTime issuedAt = DateTime.UtcNow; //set the time when it expires DateTime expires = DateTime.UtcNow.AddDays(7); //http://stackoverflow.com/questions/18223868/how-to-encrypt-jwt-security-token var tokenHandler = new JwtSecurityTokenHandler(); //create a identity and add claims to the user which we want to log in ClaimsIdentity claimsIdentity = new ClaimsIdentity( claims.Select(d => new Claim(d.Key, d.Value)) ); string sec = this.JwtKey; 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:80", audience: "http://localhost:80", subject: claimsIdentity, notBefore: issuedAt, expires: expires, signingCredentials: signingCredentials); var tokenString = tokenHandler.WriteToken(token); return(tokenString); }
private string createToken(TurfUser userInfo) { var tokenHandler = new JwtSecurityTokenHandler(); //create a identity and add claims to the user which we want to log in var claims = new[] { new Claim(JwtRegisteredClaimNames.Sub, userInfo.Username), new Claim(JwtRegisteredClaimNames.Email, userInfo.Email), new Claim("UserType", userInfo.UserType.ToString()), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()) }; const string sec = "401b09eab3c013d4ca54922bb802bec8fd5318192b0a75f201d8b3727429090fb337591abd3e44453b954555b7a0812e1081c39b740293f765eae731f5a65ed1"; 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); var token = new JwtSecurityToken(issuer: "http://localhost:50191", audience: "http://localhost:50191", claims, expires: DateTime.Now.AddMinutes(120), signingCredentials: signingCredentials); return(new JwtSecurityTokenHandler().WriteToken(token)); }
public IActionResult Logar(LoginViewModelInput loginViewModelInput) { var usuarioViewModelOutput = new UsuarioViewModelOutput { Login = "******", Email = "*****@*****.**", Codigo = 1 }; var secret = Encoding.ASCII.GetBytes("ePt(yaqbFNU4bHhF2Y*J&)32Pv^$1JhG*C_x33p4eVxIxLeW"); var symmetricSecureityKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(secret); var securityTokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.NameIdentifier, usuarioViewModelOutput.Codigo.ToString()), new Claim(ClaimTypes.Name, usuarioViewModelOutput.Login.ToString()), new Claim(ClaimTypes.Email, usuarioViewModelOutput.Email.ToString()) }), Expires = DateTime.UtcNow.AddDays(1), SigningCredentials = new SigningCredentials(symmetricSecureityKey, SecurityAlgorithms.HmacSha256Signature) }; var jwtSeceurityTokenHandler = new JwtSecurityTokenHandler(); var tokenGenerated = jwtSeceurityTokenHandler.CreateToken(securityTokenDescriptor); var token = jwtSeceurityTokenHandler.WriteToken(tokenGenerated); return(Ok(new { Token = token, Usuario = usuarioViewModelOutput.Login })); }
public static string GenerateToken(string userId, string username, string firstname, string lastname) { //Set issued at date DateTime issuedAt = DateTime.UtcNow; //set the time when it expires DateTime expires = DateTime.UtcNow.AddDays(7); //http://stackoverflow.com/questions/18223868/how-to-encrypt-jwt-security-token var tokenHandler = new JwtSecurityTokenHandler(); //create a identity and add claims to the user which we want to log in ClaimsIdentity claimsIdentity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, username), new Claim("userid", userId), new Claim("username", username), new Claim("firstname", firstname), new Claim("lastname", lastname), //TODO:add other claim }); 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: "AuthAPI", audience: "MvcWebClient", subject: claimsIdentity, notBefore: issuedAt, expires: expires, signingCredentials: signingCredentials); var tokenString = tokenHandler.WriteToken(token); return(tokenString); }
public JsonWebToken(Uri audience, string securityKey, string issuer, IEnumerable <Claim> claims, double lifetimeMinutes) { this.issuer = issuer; id = Guid.NewGuid().ToString(); created = DateTime.UtcNow; expires = created.AddMinutes(lifetimeMinutes); SigningKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(Convert.FromBase64String(securityKey)); JwtSecurityTokenHandler jwt = new JwtSecurityTokenHandler(); Microsoft.IdentityModel.Tokens.SecurityTokenDescriptor msstd = new Microsoft.IdentityModel.Tokens.SecurityTokenDescriptor() { Issuer = issuer, Subject = new ClaimsIdentity(claims), Expires = expires, IssuedAt = created, NotBefore = created, Audience = audience.ToString(), SigningCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(SigningKey, Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256Signature) }; JwtSecurityToken jwtToken = jwt.CreateJwtSecurityToken(msstd); tokenString = jwt.WriteToken(jwtToken); }
public static bool TokenValidation(string token) { try { //SystemIdentityModelToken.SecurityToken validatedToken; MicrosoftIdentityModelToken.SecurityToken validatedToken; var symmetricKey = GetBytes(communicationKey); var signingKey = new MicrosoftIdentityModelToken.SymmetricSecurityKey(Encoding.ASCII.GetBytes(communicationKey)); //var signingKey = new InMemorySymmetricSecurityKey(symmetricKey); MicrosoftIdentityModelToken.TokenValidationParameters validationParameters = new MicrosoftIdentityModelToken.TokenValidationParameters(); //SystemIdentityModelToken.TokenValidationParameters validationParameters = new SystemIdentityModelToken.TokenValidationParameters(); validationParameters.IssuerSigningKey = signingKey; validationParameters.AudienceValidator = AudienceValidator_; validationParameters.ValidateIssuer = false; var tokenC = new JwtSecurityTokenHandler().ValidateToken(token, validationParameters, out validatedToken); return(true); } catch (Exception ex) { Logger.WriteError(ex); return(false); } }
private void ConfigureOAuthTokenConsumption(IAppBuilder app) { var issuer = "http://localhost:57293"; string audienceId = ConfigurationManager.AppSettings["as:AudienceId"]; string audienceSecret = ConfigurationManager.AppSettings["as:AudienceSecret"]; const string sec = "401b09eab3c013d4ca54922bb802bec8fd5318192b0a75f201d8b3727429090fb337591abd3e44453b954555b7a0812e1081c39b740293f765eae731f5a65ed1"; var now = DateTime.UtcNow; var securityKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(System.Text.Encoding.Default.GetBytes(audienceSecret)); TokenValidationParameters validationParameters = new TokenValidationParameters() { ValidAudience = "http://localhost:57293", ValidIssuer = "http://localhost:57293", ValidateLifetime = true, ValidateIssuerSigningKey = true, LifetimeValidator = this.LifetimeValidator, IssuerSigningKey = securityKey }; JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler(); // Api controllers with an [Authorize] attribute will be validated with JWT app.UseJwtBearerAuthentication( new JwtBearerAuthenticationOptions { AuthenticationMode = AuthenticationMode.Active, AllowedAudiences = new[] { audienceId }, TokenValidationParameters = validationParameters, TokenHandler = handler }); }
public JsonWebToken(string securityKey, IEnumerable <Claim> claims, double?lifetimeMinutes, string issuer = null, string audience = null) { this.issuer = issuer; id = Guid.NewGuid().ToString(); created = DateTime.UtcNow; expires = created.AddMinutes(lifetimeMinutes.HasValue ? lifetimeMinutes.Value : 20); SigningKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(Convert.FromBase64String(securityKey)); JwtSecurityTokenHandler jwt = new JwtSecurityTokenHandler(); SecurityTokenDescriptor msstd = new Microsoft.IdentityModel.Tokens.SecurityTokenDescriptor() { Issuer = issuer, Subject = new ClaimsIdentity(claims), Expires = expires, IssuedAt = created, NotBefore = created, Audience = audience, SigningCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(SigningKey, Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256Signature) }; try { JwtSecurityToken jwtToken = jwt.CreateJwtSecurityToken(msstd); tokenString = jwt.WriteToken(jwtToken); } catch (Exception ex) { Console.WriteLine(ex.Message); } }
private async Task <JwtSecurityToken> TokenValidationAsync(string token, string validAudience, string validIssuer, bool validateLifetime, string issuerSigningKey = "") { TokenValidationParameters validationParameters = new TokenValidationParameters(); validationParameters.ValidateAudience = true; validationParameters.ValidAudience = validAudience; validationParameters.ValidateIssuer = true; validationParameters.ValidIssuer = validIssuer; validationParameters.ValidateIssuerSigningKey = true; validationParameters.ValidateLifetime = validateLifetime; if (string.IsNullOrEmpty(issuerSigningKey)) { string stsDiscoveryEndpoint = "https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration"; ConfigurationManager <OpenIdConnectConfiguration> configManager = new ConfigurationManager <OpenIdConnectConfiguration>(stsDiscoveryEndpoint, new OpenIdConnectConfigurationRetriever()); OpenIdConnectConfiguration config = await configManager.GetConfigurationAsync(); validationParameters.IssuerSigningKeys = config.SigningKeys; } else { var securityKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(System.Text.Encoding.Default.GetBytes(issuerSigningKey)); validationParameters.IssuerSigningKey = securityKey; } JwtSecurityTokenHandler tokendHandler = new JwtSecurityTokenHandler(); SecurityToken jwt; IdentityModelEventSource.ShowPII = false; ClaimsPrincipal claimsPrincipal = tokendHandler.ValidateToken(token, validationParameters, out jwt); return(jwt as JwtSecurityToken); }
/// <summary> /// اذا كان هناك اكسس توكن يقوم بفكة وملىئه واذا لم يكن سوف يكملة مسيرتة /// والدالة التى ذاهب اليها تحتاج الى مصادقة سوف يرجع بـ الخطاء المعتاد /// </summary> /// <param name="request"></param> /// <param name="cancellationToken"></param> /// <returns></returns> protected override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { HttpStatusCode statusCode; string token; HttpResponseMessage HTM = new HttpResponseMessage(); ResponseVM Res = new ResponseVM(); //determine whether a jwt exists or not if (!TryRetrieveToken(request, out token)) { //allow requests with no token - whether a action method needs an authentication can be set with the claimsauthorization attribute return(base.SendAsync(request, cancellationToken)); } try { const string sec = "401b09eab3c013d4ca54922bb802bec8fd5318192b0a75f201d8b3727429090fb337591abd3e44453b954555b7a0812e1081c39b740293f765eae731f5a65ed1"; //var now = DateTime.UtcNow; var securityKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(System.Text.Encoding.Default.GetBytes(sec)); SecurityToken securityToken; JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler(); /* * هذا الاوبجكت نتحقق هل الملعومات الذى بداخلة هى التى داخل الاكسس توكن * والتى سبق وانشئنها اثناء انشاء التوكن */ TokenValidationParameters validationParameters = new TokenValidationParameters() { ValidAudience = "Tageer", ValidIssuer = "Tageer", ValidateLifetime = true, ValidateIssuerSigningKey = true, LifetimeValidator = this.LifetimeValidator, IssuerSigningKey = securityKey }; //extract and assign the user of the jwt Thread.CurrentPrincipal = handler.ValidateToken(token, validationParameters, out securityToken); HttpContext.Current.User = handler.ValidateToken(token, validationParameters, out securityToken); return(base.SendAsync(request, cancellationToken)); } catch (SecurityTokenValidationException e) { statusCode = HttpStatusCode.Unauthorized; Res.Message = Token.AuthorizationRequired; } catch (Exception ex) { statusCode = HttpStatusCode.InternalServerError; Res.Message = Token.TokenNotValid; } Res.RequestType = RequestTypeEnumVM.Error; HTM.StatusCode = statusCode; HTM.Content = new StringContent(JsonConvert.SerializeObject(Res)); return(Task <HttpResponseMessage> .Factory.StartNew(() => HTM)); }
public string Protect(AuthenticationTicket data) { if (data == null) { throw new ArgumentNullException("data"); } string audienceId = ConfigurationManager.AppSettings["as:AudienceId"]; string symmetricKeyAsBase64 = ConfigurationManager.AppSettings["as:AudienceSecret"]; var keyByteArray = TextEncodings.Base64Url.Decode(symmetricKeyAsBase64); //var signingKey = new HmacSigningCredentials(keyByteArray); var securityKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(keyByteArray); var signingCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials( securityKey, SecurityAlgorithms.HmacSha256Signature); var issued = data.Properties.IssuedUtc; var expires = data.Properties.ExpiresUtc; var handler = new JwtSecurityTokenHandler { MapInboundClaims = false }; // we are clearing the map of the rename of the properties. see https://mderriey.com/2019/06/23/where-are-my-jwt-claims/ for details //handler.InboundClaimTypeMap.Clear(); var token = new JwtSecurityToken(_issuer, audienceId, data.Identity.Claims, issued.Value.UtcDateTime, expires.Value.UtcDateTime, signingCredentials); var jwt = handler.WriteToken(token); return(jwt); }
public void ConfigureJwtAuth(IApplicationBuilder app) { var audienceConfig = Configuration.GetSection("Audience"); var symmetricKeyAsBase64 = audienceConfig["Secret"]; var keyByteArray = Encoding.ASCII.GetBytes(symmetricKeyAsBase64); var signingKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(keyByteArray); var tokenValidationParameters = new TokenValidationParameters { // The signing key must match! ValidateIssuerSigningKey = true, IssuerSigningKey = signingKey, // Validate the JWT Issuer (iss) claim ValidateIssuer = true, ValidIssuer = "http://catcher1994.cnblogs.com/", // Validate the JWT Audience (aud) claim ValidateAudience = true, ValidAudience = "Catcher Wong", // Validate the token expiry ValidateLifetime = true, ClockSkew = TimeSpan.Zero }; app.UseJwtBearerAuthentication(new JwtBearerOptions { AutomaticAuthenticate = true, AutomaticChallenge = true, TokenValidationParameters = tokenValidationParameters, }); }
// The Method is used to generate token for user public static string GenerateTokenForUser(UserDetailsModel userDetailsModel) { var tokenHandler = new JwtSecurityTokenHandler(); var symmetricKey = GetBytes(communicationKey); var signingKey = new MicrosoftIdentityModelToken.SymmetricSecurityKey(Encoding.ASCII.GetBytes(communicationKey)); //var signingKey = new InMemorySymmetricSecurityKey(symmetricKey); //var tokenDescriptor = new SystemIdentityModelToken.SecurityTokenDescriptor var tokenDescriptor = new MicrosoftIdentityModelToken.SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim(SecurityConstants.SCB_JWTClaim_Id, GetStringOrEmpty(Convert.ToString(userDetailsModel.UserId))), new Claim(SecurityConstants.SCB_JWTClaim_UserName, GetStringOrEmpty(userDetailsModel.UserName)), new Claim(SecurityConstants.SCB_JWTClaim_RoleId, GetStringOrEmpty(Convert.ToString(userDetailsModel.RoleId))) }), //TokenIssuerName = tokenIssuer, //AppliesToAddress = appliesToAddress, //Lifetime = new Lifetime(DateTime.UtcNow, ExpiryTime), Expires = SecurityConstants.SCB_JWTExpiryTime, SigningCredentials = new MicrosoftIdentityModelToken.SigningCredentials(signingKey, signatureAlgo, digestAlgo) //SigningCredentials = new SystemIdentityModelToken.SigningCredentials(signingKey, signatureAlgo , digestAlgo) }; var token = tokenHandler.CreateToken(tokenDescriptor); var tokenString = tokenHandler.WriteToken(token); AddTokenToCookie(tokenString); //var claim = GetClaim(tokenString); return(tokenString); }
public string CriarToken(string nome, string email) { // Definindo uma Const Key que deve ser uma chave secreta privada armazenada em algum lugar seguro string key = "401b09eab3c013d4ca54922bb802bec8fd5318192b0a75f201d8b372742 9090fb337591abd3e44453b954555b7a0812e1081c39b740293f765eae731f5a65ed1"; // Criando a chave de segurança usando a chave privada acima: // não a versão mais recente do JWT usando o namespace Microsoft em vez do sistema var securityKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(Encoding.UTF8.GetBytes(key)); // Observe também que o comprimento da segurança deve ser > 256b // então você deve ter certeza de que sua chave privada tenha um comprimento adequado // var credentials = new Microsoft.IdentityModel.Tokens.SigningCredentials (securityKey, SecurityAlgorithms.HmacSha256Signature); // Finalmente criando um Token var header = new JwtHeader(credentials); // Alguns PayLoad que contêm informações sobre o usuário var payload = new JwtPayload { { "Nome ", nome }, { "Email", email }, }; // var secToken = new JwtSecurityToken(header, payload); var handler = new JwtSecurityTokenHandler(); // Token em String para que você possa usá-lo em seu usuário var tokenString = handler.WriteToken(secToken); // Retornando token return(tokenString); }
private string CreateToken(string username) { string sec = ConfigurationManager.AppSettings["jwtKey"]; //Set issued at date DateTime issuedAt = DateTime.UtcNow; //set the time when it expires DateTime expires = DateTime.UtcNow.AddDays(int.Parse(ConfigurationManager.AppSettings["jwtValidity"])); //http://stackoverflow.com/questions/18223868/how-to-encrypt-jwt-security-token var tokenHandler = new JwtSecurityTokenHandler(); //create a identity and add claims to the user which we want to log in ClaimsIdentity claimsIdentity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, username) }); 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 = (JwtSecurityToken) tokenHandler.CreateJwtSecurityToken(issuer: ConfigurationManager.AppSettings["jwtIssuer"], audience: ConfigurationManager.AppSettings["jwtIssuer"], subject: claimsIdentity, notBefore: issuedAt, expires: expires, signingCredentials: signingCredentials); var tokenString = tokenHandler.WriteToken(token); return(tokenString); }
/// <summary> /// 检测Token /// </summary> /// <param name="app"></param> /// <param name="configuration"></param> public static void ConfigureJwtAuth(this IApplicationBuilder app, IConfigurationRoot configuration) { var audience = configuration["Jwt:Audience:Name"]; var issuer = configuration["Jwt:Issuer"]; var symmetricKeyAsBase64 = configuration["Jwt:Audience:Secret"]; var keyByteArray = Encoding.ASCII.GetBytes(symmetricKeyAsBase64); var signingKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(keyByteArray); var tokenValidationParameters = new TokenValidationParameters { // The signing key must match! ValidateIssuerSigningKey = true, IssuerSigningKey = signingKey, // Validate the JWT Issuer (iss) claim ValidateIssuer = true, ValidIssuer = issuer, // Validate the JWT Audience (aud) claim ValidateAudience = true, ValidAudience = audience, // Validate the token expiry ValidateLifetime = true, ClockSkew = TimeSpan.Zero }; app.UseJwtBearerAuthentication(new JwtBearerOptions { AutomaticAuthenticate = true, AutomaticChallenge = true, TokenValidationParameters = tokenValidationParameters, }); }
public async Task <IActionResult> Login([FromBody] UserForLoginDto userForLoginDto) { var userFromRepo = await _repo.Login(userForLoginDto.Username.ToLower(), userForLoginDto.Password); if (userFromRepo == null) { return(Unauthorized()); } var claims = new[] { new Claim(ClaimTypes.NameIdentifier, userFromRepo.Id.ToString()), new Claim(ClaimTypes.Name, userFromRepo.Username) }; var key = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config.GetSection("AppSettings:Token").Value)); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(claims), Expires = DateTime.Now.AddDays(1), SigningCredentials = creds }; var tokenHandler = new JwtSecurityTokenHandler(); var token = tokenHandler.CreateToken(tokenDescriptor); return(Ok(new { token = tokenHandler.WriteToken(token) })); }
public ViewResult GenerateToken(string jsontext, string key, string algorithm) { try { jsontext = jsontext.Replace("\r", String.Empty); jsontext = jsontext.Replace("\n", String.Empty); var json = JsonConvert.DeserializeObject(jsontext); //KEY (your - 256 - bit - secret ) var verificarion = Encoding.UTF8.GetBytes(key); var sKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(Encoding.UTF8.GetBytes(key)); var signingcredential = new Microsoft.IdentityModel.Tokens.SigningCredentials(sKey, algorithm); //HEADER var header = new JwtHeader(signingcredential); //PAYLOAD var payload = new JwtPayload(); payload = JwtPayload.Deserialize(jsontext); var secToken = new JwtSecurityToken(header, payload); var handler = new JwtSecurityTokenHandler(); var tokenString = handler.WriteToken(secToken); AlgorithmModel model = new AlgorithmModel(); model.token = tokenString; return(View(model)); } catch { ViewBag.Message = "Please enter a valid key"; return(View(new AlgorithmModel())); } }
public static void AddGenericJwtAuthService(this IServiceCollection services) { //Add authentication before adding MVC services.AddAuthentication(sharedOptions => { sharedOptions.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(cfg => { var keyByteArray = Encoding.ASCII.GetBytes(JwtTokenConfigurations.IssuerSigningKey); var signingKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(keyByteArray); cfg.TokenValidationParameters = new TokenValidationParameters() { ValidateIssuerSigningKey = true, IssuerSigningKey = signingKey, ValidateAudience = true, ValidAudience = JwtTokenConfigurations.Audience, ValidateIssuer = true, ValidIssuer = JwtTokenConfigurations.Issuer, ClockSkew = TimeSpan.FromMinutes(0), CryptoProviderFactory = CryptoProviderFactory.Default }; }); services.AddAuthorization(auth => { var defaultPolicy = new AuthorizationPolicyBuilder(new string[] { JwtBearerDefaults.AuthenticationScheme }) .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme) .RequireAuthenticatedUser() .Build(); auth.AddPolicy("Bearer", defaultPolicy); auth.DefaultPolicy = defaultPolicy; }); }
public static string ZoomToken() { // Token will be good for 20 minutes DateTime Expiry = DateTime.UtcNow.AddMinutes(20); string ApiKey = "ApiKey"; string ApiSecret = "ApiSecret"; int ts = (int)(Expiry - new DateTime(1970, 1, 1)).TotalSeconds; // Create Security key using private key above: var securityKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(Encoding.UTF8.GetBytes(ApiSecret)); // length should be >256b var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256); //Finally create a Token var header = new JwtHeader(credentials); //Zoom Required Payload var payload = new JwtPayload { { "iss", ApiKey }, { "exp", ts }, }; var secToken = new JwtSecurityToken(header, payload); var handler = new JwtSecurityTokenHandler(); // Token to String so you can use it in your client var tokenString = handler.WriteToken(secToken); return(tokenString); }
private object GenerateTokenInfo(ApplicationUser user, LoginViewModel model) { // luon dam bao cookie & jwt login dong thoi // create the token var claims = new[] { new Claim(JwtRegisteredClaimNames.Sub, user.Email), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), new Claim(JwtRegisteredClaimNames.UniqueName, user.Email) }; var key = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(_config["Tokens:Key"])); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var token = new JwtSecurityToken( _config["Tokens:Issuer"], _config["Tokens:Audience"], claims, expires: DateTime.Now.AddMinutes(30), signingCredentials: creds); var results = new { token = new JwtSecurityTokenHandler().WriteToken(token), tokenExpiration = token.ValidTo, userName = user.UserName, email = user.Email, }; return(results); }
public static object GenerateToken(dynamic input) { var securityKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(Encoding.UTF8.GetBytes(key)); var credentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256); var header = new JwtHeader(credentials); var payload = new JwtPayload(); foreach (IDictionary <string, object> row in input) { foreach (var pair in row) { var num = pair.Key; var val = pair.Value; if (num == "ID" || num == "EMAIL") { payload.Add(num, val); } } } var secToken = new JwtSecurityToken(header, payload); var handler = new JwtSecurityTokenHandler(); var tokenString = handler.WriteToken(secToken); //Get_Id("eyJhbGciOiJodHRwOi8vd3d3LnczLm9yZy8yMDAxLzA0L3htbGRzaWctbW9yZSNobWFjLXNoYTI1NiIsInR5cCI6IkpXVCJ9.eyJJRCI6MzAwMy4wLCJFTUFJTCI6ImdhYnJpZWxtYXRlaTJAZ21haWwuY29tIn0.0YGk0PrCbkuhjdSHrG8YQ9oEpiNOh4YNxWqO36xMO28"); return(tokenString); }
private string createToken(string username) { //Set issued at date DateTime issuedAt = DateTime.UtcNow; //set the time when it expires DateTime expires = DateTime.UtcNow.AddDays(7); //http://stackoverflow.com/questions/18223868/how-to-encrypt-jwt-security-token var tokenHandler = new JwtSecurityTokenHandler(); //create a identity and add claims to the user which we want to log in ClaimsIdentity claimsIdentity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, username), //new Claim(ClaimTypes.Pol, username) }); const string sec = "401b09eab3c013d4ca54922bb802bec8fd5318192b0a75f201d8b3727429090fb337591abd3e44453b954555b7a0812e1081c39b740293f765eae731f5a65ed1"; 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 = (JwtSecurityToken) tokenHandler.CreateJwtSecurityToken(issuer: "http://localhost:50191", audience: "http://localhost:50191", subject: claimsIdentity, notBefore: issuedAt, expires: expires, signingCredentials: signingCredentials); var tokenString = tokenHandler.WriteToken(token); return(tokenString); }
public string ReturnJWT(DateTime expirationDate, int permissionId_i, int userId_i) { // Create Security key using private key above: // not that latest version of JWT using Microsoft namespace instead of System SymmetricSecurityKey securityKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(Encoding.UTF8.GetBytes(_key)); // Also note that securityKey length should be >256b // so you have to make sure that your private key has a proper length SigningCredentials credentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256); // Finally create a Token JwtHeader header = new JwtHeader(credentials); // Some PayLoad that contain information about the customer JwtPayload payload = new JwtPayload { { "expirationDate", expirationDate }, { "permissionId", permissionId_i }, { "userId", userId_i } }; JwtSecurityToken secToken = new JwtSecurityToken(header, payload); JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler(); // Token to String so you can use it in your client ErrInfLogger.LockInstance.InfoLog("Token created."); return(handler.WriteToken(secToken)); }
public void ValidateToken(string token) { const string sec = "401b09eab3c013d4ca54922bb802bec8fd5318192b0a75f201d8b3727429090fb337591abd3e44453b954555b7a0812e1081c39b740293f765eae731f5a65ed1"; var now = DateTime.UtcNow; var securityKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(System.Text.Encoding.Default.GetBytes(sec)); SecurityToken securityToken; JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler(); TokenValidationParameters validationParameters = new TokenValidationParameters() { ValidAudience = "http://localhost:50191", ValidIssuer = "http://localhost:50191", ValidateLifetime = true, ValidateIssuerSigningKey = true, LifetimeValidator = this.LifetimeValidator, IssuerSigningKey = securityKey }; //extract and assign the user of the jwt var claimsPrincipal = handler.ValidateToken(token, validationParameters, out securityToken); var httpContextUser = handler.ValidateToken(token, validationParameters, out securityToken); SetPrincipal(claimsPrincipal); }
protected override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { // TODO: this awful hack is to manually prevent checking login route, // this circumvents a swagger ui issue that i'm not investing more // time in where once you've entered a value into the Authorization // (api_key) field you effectively cannot clear it if (request.RequestUri.AbsoluteUri.Contains("api/login")) { return(base.SendAsync(request, cancellationToken)); } HttpStatusCode statusCode; string token; //determine whether a jwt exists or not if (!TryRetrieveToken(request, out token)) { statusCode = HttpStatusCode.Unauthorized; //allow requests with no token - whether a action method needs an authentication can be set with the claimsauthorization attribute return(base.SendAsync(request, cancellationToken)); } try { //"401b09eab3c013d4ca54922bb802bec8fd5318192b0a75f201d8b3727429090fb337591abd3e44453b954555b7a0812e1081c39b740293f765eae731f5a65ed1"; string secret = ConfigurationManager.AppSettings.Get("jwtSecret"); var now = DateTime.UtcNow; var securityKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(System.Text.Encoding.Default.GetBytes(secret)); SecurityToken securityToken; JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler(); Uri uri = HttpContext.Current.Request.Url; String host = uri.Scheme + Uri.SchemeDelimiter + uri.Host + ":" + uri.Port; TokenValidationParameters validationParameters = new TokenValidationParameters() { ValidAudience = host, ValidIssuer = host, ValidateLifetime = true, ValidateIssuerSigningKey = true, LifetimeValidator = this.LifetimeValidator, IssuerSigningKey = securityKey }; //extract and assign the user of the jwt Thread.CurrentPrincipal = handler.ValidateToken(token, validationParameters, out securityToken); HttpContext.Current.User = handler.ValidateToken(token, validationParameters, out securityToken); return(base.SendAsync(request, cancellationToken)); } catch (SecurityTokenValidationException) { statusCode = HttpStatusCode.Unauthorized; HttpContext.Current.Response.Write("invalid authorization token"); } catch (Exception otherException) { statusCode = HttpStatusCode.InternalServerError; HttpContext.Current.Response.Write(string.Format( "authorization validation error: {0}", otherException.Message )); } return(Task <HttpResponseMessage> .Factory.StartNew(() => new HttpResponseMessage(statusCode) { })); }
public void DiscordJwtTest() { // Arrange ulong discordUserId = 123; string discordUsername = "******"; // This is a completely arbitrary string and can be safely committed string sharedSecret = "5g35gq3095gq3598jgq30598jgq3950gjh48079ghq30954yhgq349875hgq9754hqg78946qgh45gqjn4rjigerg89w5w9845ug89w45g9w45gw"; var jwtString = JwtBuilder.BuildDiscordJwt(sharedSecret, discordUserId.ToString(), discordUsername); var securityKey = new Microsoft .IdentityModel.Tokens.SymmetricSecurityKey(Encoding.UTF8.GetBytes(sharedSecret)); var handler = new JwtSecurityTokenHandler(); handler.ValidateToken(jwtString, new TokenValidationParameters() { ValidIssuer = "Synthbot.DiscordBot", ValidAudience = "Synthbot.WebApp", ValidateIssuer = true, ValidateAudience = true, RequireSignedTokens = true, IssuerSigningKey = securityKey }, out SecurityToken validatedToken); var validatedJwtToken = (JwtSecurityToken)validatedToken; Assert.Equal(discordUserId.ToString(), validatedJwtToken.Claims.FirstOrDefault(c => c.Type == SynthbotClaimTypes.DiscordUserId)?.Value); }