public string GetJwtToken() { AppConfig config = configurationRepository.GetAppConfig(); DownloadPfxCertificateEntity certEntity = certificateManagementLogic.GetPfxCertificateContent(config.JwtCertificateId); string password = certificateManagementLogic.GetCertificatePassword(config.JwtCertificateId, LocalIdentityProviderLogic.GetSystemIdentity()).DecryptedPassword; X509Certificate2 cert = new X509Certificate2(certEntity.Content, password); X509SecurityKey securityKey = new X509SecurityKey(cert); JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler(); //signingCredentials: new SigningCredentials(new RsaSecurityKey(publicAndPrivate), SecurityAlgorithms.RsaSha256Signature), var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(), Issuer = config.LocalIdpIdentifier, IssuedAt = DateTime.Now, Audience = config.LocalIdpIdentifier, NotBefore = DateTime.Now, Expires = DateTime.Now.AddMinutes(config.JwtValidityPeriod), SigningCredentials = new SigningCredentials( securityKey, SecurityAlgorithms.RsaSha256Signature) }; var token = handler.CreateToken(tokenDescriptor); return(token.ToString()); }
public string GetJwtAssertion() { var dateTimeOffset = new DateTimeOffset(DateTime.UtcNow); var cert = GetCertificateFromKeyStore(_certificateThumbPrint, StoreName.My, StoreLocation.LocalMachine); var securityKey = new X509SecurityKey(cert); var header = new JwtHeader(new SigningCredentials(securityKey, SecurityAlgorithms.RsaSha256)) { { "x5c", new List <string>() { Convert.ToBase64String(cert.GetRawCertData()) } } }; header.Remove("typ"); header.Remove("kid"); var payload = new JwtPayload { { "aud", _audience }, { "resource", _resource }, { "scope", _scopes }, { "iss", _issuer }, { "exp", dateTimeOffset.ToUnixTimeSeconds() + _tokenTtl }, { "iat", dateTimeOffset.ToUnixTimeSeconds() }, { "jti", Guid.NewGuid().ToString() }, }; var securityToken = new JwtSecurityToken(header, payload); var handler = new JwtSecurityTokenHandler(); return(handler.WriteToken(securityToken)); }
/// <summary> /// Method to generate access token. /// </summary> /// <param name="userProfile"></param> /// <returns></returns> public async Task <TokenResponse> GetToken(UserProfile userProfile) { var claims = new[] { new Claim(TokenClaims.UserId, userProfile.Id.ToString()), new Claim(ClaimTypes.Role, userProfile.RoleName.ToString()), new Claim(TokenClaims.FirstName, userProfile.FirstName), new Claim(TokenClaims.LastName, userProfile.LastName), new Claim(TokenClaims.Permission, userProfile.Permission) }; var certificatePath = configurationManager.WebRootPath + authorizationConfig.KeyFilePath; var certificate = new X509Certificate2(certificatePath, authorizationConfig.ConvertToUnsecureString (authorizationConfig.SigningPassword), X509KeyStorageFlags.EphemeralKeySet); var signingKey = new X509SecurityKey(certificate); var creds = new SigningCredentials(signingKey, SecurityAlgorithms.RsaSha256); var token = new JwtSecurityToken( issuer: authorizationConfig.Issuer, audience: authorizationConfig.Audience, claims: claims, expires: DateTime.Now.AddMinutes(authorizationConfig.TokenExpiryInMinutes), signingCredentials: creds); var accessToken = new TokenResponse { AccessToken = new JwtSecurityTokenHandler().WriteToken(token), ExpiresIn = authorizationConfig.SessionInMinutes * 60 * 1000 }; return(await Task.FromResult(accessToken)); }
public void X509SecurityKey_Constructor() { X509SecurityKey x509SecurityKey; ExpectedException expectedException = new ExpectedException(typeExpected: typeof(ArgumentNullException), substringExpected: "certificate"); try { x509SecurityKey = new X509SecurityKey(null); expectedException.ProcessNoException(); } catch (Exception exception) { expectedException.ProcessException(exception); } X509Certificate2 x509Certificate2 = KeyingMaterial.DefaultCert_2048; expectedException = ExpectedException.NoExceptionExpected; try { x509SecurityKey = new X509SecurityKey(x509Certificate2); Assert.ReferenceEquals(x509Certificate2, x509SecurityKey.Certificate); } catch (Exception exception) { expectedException.ProcessException(exception); } }
private static string CreateToken() { //Load up the pulic / private key var bytes = File.ReadAllBytes("registry-auth.pfx"); X509Certificate2 cert = new X509Certificate2(bytes, new SecureString()); var key = new X509SecurityKey(cert) { KeyId = GetKid(cert) }; var credentials = new SigningCredentials(key, SecurityAlgorithms.RsaSha256); var header = new JwtHeader(credentials); var claims = new Claim[] { //new Claim("scope", "agent:"), }; DateTime expires = DateTime.UtcNow.Add(TimeSpan.FromDays(100)); DateTime notBefore = DateTime.UtcNow.Subtract(TimeSpan.FromMinutes(30)); DateTime issuedAt = DateTime.UtcNow; var payload = new JwtPayload("issuer", "Docker registry", claims, notBefore, expires, issuedAt); var secToken = new JwtSecurityToken(header, payload); var handler = new JwtSecurityTokenHandler(); var token = handler.WriteToken(secToken); return(token); }
public virtual async Task <TokenValidationResult> ValidateIdentityTokenAsync(string token, string clientId = null, bool validateLifetime = true) { Logger.Info("Start identity token validation"); if (clientId.IsMissing()) { clientId = GetClientIdFromJwt(token); if (clientId.IsMissing()) { Logger.Error("No clientId supplied, can't find id in identity token."); return(Invalid(Constants.ProtectedResourceErrors.InvalidToken)); } } _log.ClientId = clientId; _log.ValidateLifetime = validateLifetime; var client = await _clients.FindClientByIdAsync(clientId); if (client == null) { LogError("Unknown or diabled client."); return(Invalid(Constants.ProtectedResourceErrors.InvalidToken)); } _log.ClientName = client.ClientName; var signingKey = new X509SecurityKey(_options.SigningCertificate); var result = await ValidateJwtAsync(token, clientId, signingKey, validateLifetime); result.Client = client; if (result.IsError) { LogError("Error validating JWT"); return(result); } if (_options.LoggingOptions.IncludeSensitiveDataInLogs) { _log.Claims = result.Claims.ToClaimsDictionary(); } var customResult = await _customValidator.ValidateIdentityTokenAsync(result); if (customResult.IsError) { LogError("Custom validator failed: " + customResult.Error ?? "unknown"); return(customResult); } if (_options.LoggingOptions.IncludeSensitiveDataInLogs) { _log.Claims = customResult.Claims.ToClaimsDictionary(); } LogSuccess(); return(customResult); }
/// <summary> /// Converts a X509 Certificate to JWK. /// </summary> public static Task <JsonWebKey> ToJsonWebKeyAsync(this X509Certificate2 certificate, bool includePrivateKey = false) { if (certificate == null) { new ArgumentNullException(nameof(certificate)); } var jwk = new JsonWebKey(); jwk.Kty = JsonWebAlgorithmsKeyTypes.RSA; var securityKey = new X509SecurityKey(certificate); jwk.KeyId = securityKey.KeyId; jwk.X5c.Add(Convert.ToBase64String(certificate.RawData)); jwk.X5t = WebEncoders.Base64UrlEncode(certificate.GetCertHash()); var parameters = (securityKey.PublicKey as RSA).ExportParameters(false); jwk.N = WebEncoders.Base64UrlEncode(parameters.Modulus); jwk.E = WebEncoders.Base64UrlEncode(parameters.Exponent); if (includePrivateKey && securityKey.PrivateKeyStatus == PrivateKeyStatus.Exists) { parameters = (securityKey.PrivateKey as RSA).ExportParameters(true); jwk.D = WebEncoders.Base64UrlEncode(parameters.D); jwk.P = WebEncoders.Base64UrlEncode(parameters.P); jwk.Q = WebEncoders.Base64UrlEncode(parameters.Q); jwk.DP = WebEncoders.Base64UrlEncode(parameters.DP); jwk.DQ = WebEncoders.Base64UrlEncode(parameters.DQ); jwk.QI = WebEncoders.Base64UrlEncode(parameters.InverseQ); } return(Task.FromResult(jwk)); }
private static bool Matches(SecurityKeyIdentifierClause keyIdentifierClause, SecurityKey key, CertMatcher certMatcher, out SecurityToken token) { token = null; if (certMatcher != null) { X509SecurityKey x509Key = key as X509SecurityKey; if (x509Key != null) { if (certMatcher(x509Key.Certificate)) { token = new X509SecurityToken(x509Key.Certificate); return(true); } } else { X509AsymmetricSecurityKey x509AsymmKey = key as X509AsymmetricSecurityKey; if (x509AsymmKey != null) { X509Certificate2 cert = _certFieldInfo.GetValue(x509AsymmKey) as X509Certificate2; if (cert != null && certMatcher(cert)) { token = new X509SecurityToken(cert); return(true); } } } } return(false); }
private static bool _ValidateJwtToken(string pJwt) { //X509Certificate2 DefaultCert_Public_2048 = new X509Certificate2(System.Text.Encoding.ASCII.GetBytes(CNST_PUBLIC_KEY)); X509Certificate2 DefaultCert_Public_2048 = new X509Certificate2(CNST_PK); X509SecurityKey DefaultX509Key_Public_2048 = new X509SecurityKey(DefaultCert_Public_2048); //SigningCredentials credentials = new SigningCredentials(DefaultX509Key_Public_2048, SecurityAlgorithms.RsaSha256Signature); TokenValidationParameters validationParameters = new TokenValidationParameters { ValidateActor = false, ValidateLifetime = true, ValidateAudience = false, ValidateIssuer = false, ValidateIssuerSigningKey = true, IssuerSigningKey = DefaultX509Key_Public_2048 }; SecurityToken validatedToken; JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler(); ClaimsPrincipal claims = handler.ValidateToken(pJwt, validationParameters, out validatedToken); if (claims?.Claims?.Count() > 0) { return(true); } return(false); }
public void AddSecretConfiguration(IHelseIdWebKonfigurasjon configAuth, OpenIdConnectOptions options) { var secretParts = configAuth.ClientSecret.Split(':'); if (secretParts.Length != 2) { throw new InvalidEnterpriseCertificateSecretException(configAuth.ClientSecret); } var storeLocation = (StoreLocation)Enum.Parse(typeof(StoreLocation), secretParts[0]); var thumprint = secretParts[1]; var store = new X509Store(storeLocation); store.Open(OpenFlags.ReadOnly); var certificates = store.Certificates.Find(X509FindType.FindByThumbprint, thumprint, true); if (certificates.Count == 0) { throw new Exception($"No certificate with thumbprint {options.ClientSecret} found in store LocalMachine"); } var x509SecurityKey = new X509SecurityKey(certificates[0]); options.Events.OnAuthorizationCodeReceived = ctx => { ctx.TokenEndpointRequest.ClientAssertionType = IdentityModel.OidcConstants.ClientAssertionTypes.JwtBearer; ctx.TokenEndpointRequest.ClientAssertion = ClientAssertion.Generate(configAuth, x509SecurityKey); return(Task.CompletedTask); }; }
private static TokenValidationResult ValidateSignedToken(string serviceJwt, JsonWebKeySet jwksTrustedSigningKeys, bool includeDetails) { // Now validate the JWT using the signing keys we just discovered TokenValidationParameters tokenValidationParams = new TokenValidationParameters { ValidateAudience = false, ValidateIssuer = false, IssuerSigningKeys = jwksTrustedSigningKeys.GetSigningKeys() }; var jwtHandler = new JsonWebTokenHandler(); var validatedToken = jwtHandler.ValidateToken(serviceJwt, tokenValidationParams); if (!validatedToken.IsValid) { throw new ArgumentException("JWT is not valid (signature verification failed)"); } Logger.WriteLine($"JWT signature validation : True"); if (includeDetails) { X509SecurityKey signingKey = (X509SecurityKey)validatedToken.SecurityToken.SigningKey; if (signingKey.PublicKey is RSA publicKey) { var modulus = publicKey.ExportParameters(false).Modulus; var exponent = publicKey.ExportParameters(false).Exponent; Logger.WriteLine(37, 80, " RSA signing key modulus : ", BitConverter.ToString(modulus).Replace("-", "")); Logger.WriteLine(37, 80, " RSA signing key exponent : ", BitConverter.ToString(exponent).Replace("-", "")); } else { Logger.WriteLine($"Unexpected signing key type. Signing Key Type: {signingKey.PublicKey.GetType()}"); } } return(validatedToken); }
/// <summary> /// Generate a token /// </summary> /// <param name="entitlements">Details of the entitlements to encode into the token.</param> /// <param name="signingCert">Certificate to use when signing the token (optional).</param> /// <param name="encryptionCert">Certificate to use when encrypting the token (optional).</param> /// <returns>Generated token, if any; otherwise all related errors.</returns> private static string GenerateToken( NodeEntitlements entitlements, X509Certificate2 signingCert = null, X509Certificate2 encryptionCert = null) { SigningCredentials signingCredentials = null; if (signingCert != null) { var signingKey = new X509SecurityKey(signingCert); signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.RsaSha512Signature); } EncryptingCredentials encryptingCredentials = null; if (encryptionCert != null) { var encryptionKey = new X509SecurityKey(encryptionCert); encryptingCredentials = new EncryptingCredentials( encryptionKey, SecurityAlgorithms.RsaOAEP, SecurityAlgorithms.Aes256CbcHmacSha512); } var entitlementWithIdentifier = entitlements.WithIdentifier($"entitlement-{Guid.NewGuid():D}"); var generator = new TokenGenerator(_logger, signingCredentials, encryptingCredentials); return(generator.Generate(entitlementWithIdentifier)); }
// Reads signing credentials from a certificate file private static SigningCredentials ReadSigningCredentials(string filename, string password) { var cert = new X509Certificate2(filename, password); var key = new X509SecurityKey(cert); return(new SigningCredentials(key, SecurityAlgorithms.RsaSha256)); }
public async Task <IActionResult> Callback(string id_token, string error) { var certString = "MIIC6TCCAdGgAwIBAgIQLixNjyZMMqVFi+Jdu8VmAjANBgkqhkiG9w0BAQsFADAOMQwwCgYDVQQDEwNzdHMwHhcNMTQxMjMxMjMwMDAwWhcNMTkxMjMxMjMwMDAwWjAOMQwwCgYDVQQDEwNzdHMwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCMcdzVjPPjMKaMYzvk1OvPMOkeF6gG3b2/Fdsy8u+w5AtDBIKtP4fFCdzFKRuZpMKEiNCARKu8+4kzeRi4QBeZGL+9wxg0jbfb7ae0tS5RpE4aWxmXcTu8hC7oCjT7KqwLrE7aqADpqdvzJIgwChwWVAAL8vzsG+HhmFJkNhnlvGpAIbzDCnmezGqdNgBRi5pleMiPqo2okUG6J52lCeLbBA8q1wzCtvbc+iegLgkRTGUso7iu3EZXmFcIoi/Djcuf2KHbWKoDBY0si/QifD2hOm29OcOxSoVyvFDTHhidDlCX4HWCNtZH53vh34uiws/F2SA46LnLx1PgLZNJbsJHAgMBAAGjQzBBMD8GA1UdAQQ4MDaAEDji3ClaURkjQzomnRqeCN6hEDAOMQwwCgYDVQQDEwNzdHOCEC4sTY8mTDKlRYviXbvFZgIwDQYJKoZIhvcNAQELBQADggEBAFCO5008ZA8McEi2UefY2MApJP6BSpfXtuscNzww1ASdrlKdNkR8iNF/60OOV2l+XyhqniyefcArApsOo6miJ8kLElCMiyJ0scHQETRBi0N80w+RXctmKzFmXUn1PL8rX5lUvQiKP0whZ+xyto3qsu6v0vj1p8JeBuuJYEmurUZa4ueWkUtHCL6wGQMqmKLBH7Rk6iLu3AP6hBHcHKq8Qu8owFfxmDMQh9v2hZUAAs0Y6pw3E1e2hyIQcZgMVZgfmxs7MYlCAloMWMxVTUk7mirOKRRzPK2HmTZtxCHE+py0mKhBa4vB+Ug8LBTDRQDNF9ZyKBKPBPEsEdS5YydIcrk="; var cert = new X509Certificate2(Convert.FromBase64String(certString)); var key = new X509SecurityKey(cert); var param = new TokenValidationParameters { ValidIssuer = "http://localhost:3308", ValidAudience = "client1", IssuerSigningKey = key }; var handler = new JwtSecurityTokenHandler(); handler.InboundClaimTypeMap.Clear(); var claims = handler.ValidateToken(id_token, param, out _); var nonce = claims.FindFirst("nonce")?.Value; if (nonce == null || nonce != "nonce") { throw new Exception("Invalid nonce"); } await HttpContext.SignInAsync("Cookies", claims); return(Redirect("/Home/Secure")); }
public void Configure(IApplicationBuilder app) { var certificate = LoadCertificate(); var key = new X509SecurityKey(certificate); var credentials = new SigningCredentials(key, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest); // Add a new middleware validating access tokens issued by the server. app.UseOAuthBearerAuthentication(options => { options.AutomaticAuthentication = true; options.Audience = "http://localhost:50000/"; options.Authority = "http://localhost:50000/"; }); // Add a new middleware issuing tokens. app.UseOpenIdConnectServer(options => { options.Issuer = "http://localhost:50000/"; options.AllowInsecureHttp = true; options.AuthorizationEndpointPath = PathString.Empty; options.SigningCredentials = credentials; options.Provider = new AuthorizationProvider(); }); app.Run(async(context) => { await context.Response.WriteAsync("Hello World!"); }); }
private void ValidateAccessToken(string accessTokenJwt, JsonWebKeySet jsonWebKeySet) { using (_logger.BeginScope("Validating AccessToken")) { var handler = new JwtSecurityTokenHandler(); var jwtToken = handler.ReadJwtToken(accessTokenJwt); var kid = jwtToken.Header.Kid; _logger.LogDebug($"Kid: {kid}"); var webKey = jsonWebKeySet.Keys.Single(k => k.Kid == kid); var certString = webKey.X5c[0]; _logger.LogDebug($"Cert64: {certString}"); var certBytes = Base64Url.Decode(certString); var cert = new X509Certificate2(certBytes); var key = new X509SecurityKey(cert); var parameters = new TokenValidationParameters { ValidIssuer = _auth.Issuer, ValidAudience = _auth.Audience, ValidateAudience = true, ValidateLifetime = true, AuthenticationType = "bearer", NameClaimType = "sub", IssuerSigningKey = key, RequireSignedTokens = true }; var user = handler.ValidateToken(accessTokenJwt, parameters, out var _); } }
private IEnumerable <Claim> ValidateToken(string token) { //Grab certificate for verifying JWT signature //In prod, we'd get this from the certificate store or similar var certPath = Path.Combine(Server.MapPath("~/bin"), "SscSign.pfx"); var cert = new X509Certificate2(certPath); var x509SecurityKey = new X509SecurityKey(cert); var parameters = new TokenValidationParameters { RequireSignedTokens = true, ValidAudience = audience, ValidIssuer = validIssuer, IssuerSigningKey = x509SecurityKey, RequireExpirationTime = true, ClockSkew = TimeSpan.FromMinutes(5) }; //Validate the token and retrieve ClaimsPrinciple var handler = new JwtSecurityTokenHandler(); SecurityToken jwt; var id = handler.ValidateToken(token, parameters, out jwt); //Discard temp cookie and cookie-based middleware authentication objects (we just needed it for storing State) this.Request.GetOwinContext().Authentication.SignOut("TempCookie"); return(id.Claims); }
public static X509SecurityKey LoadPublicSigningCertificate(string publicSigningCertificatePath) { var publicCertificate = new X509Certificate2(publicSigningCertificatePath); var key = new X509SecurityKey(publicCertificate); return(key); }
public string ParseJWE(string jwe) { var key = new X509SecurityKey(AuthenticationExtensionMethods.TokenEncryptionCertificate()); var sigkey = new X509SecurityKey(AuthenticationExtensionMethods.TokenSigningCertificate()); var handler = new JwtSecurityTokenHandler(); var claimsPrincipal = handler.ValidateToken( jwe, new TokenValidationParameters { //ValidAudience = "abc123", NameClaimType = OpenIdConnectConstants.Claims.Name, RoleClaimType = OpenIdConnectConstants.Claims.Role, ValidIssuer = "https://localhost:44365/", RequireSignedTokens = true, TokenDecryptionKey = key, IssuerSigningKey = sigkey, ValidateAudience = false }, out SecurityToken securityToken); var result = new { Principal = new { Name = claimsPrincipal.Identity.Name, AuthType = claimsPrincipal.Identity.AuthenticationType }, Token = securityToken }; return(JsonConvert.SerializeObject(result, Formatting.Indented)); }
private bool Matches(X509SecurityKey key) { if (key == null) { return(false); } foreach (var data in X509Data) { foreach (var certificate in data.Certificates) { // depending on the target, X509Certificate2 may be disposable var cert = new X509Certificate2(Convert.FromBase64String(certificate)); try { if (cert.Equals(key.Certificate)) { return(true); } } finally { if (cert is IDisposable disposable) { disposable?.Dispose(); } } } } return(false); }
public LocalCertificateStore() { var store = new X509Store(StoreName.My, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadOnly); var subjectDistinguishedName = "CN=My OAuth2 Identity"; try { var certificates = store .Certificates .Find(X509FindType.FindBySubjectDistinguishedName, subjectDistinguishedName, false); var securityKeys = new List <SecurityKey>(); foreach (var certificate in certificates) { var securityKey = new X509SecurityKey(certificate); securityKeys.Add(securityKey); } SecurityKeys = securityKeys; SigningCredentials = new SigningCredentials(securityKeys[0], SecurityAlgorithms.RsaSha256Signature); } finally { store.Close(); } }
public void ShouldSupportKeyWrapAlgorithm(string algorithm) { var key = new X509SecurityKey(Certificate); var crypto = CreateCryptoProviderFactory(); Assert.True(crypto.IsSupportedAlgorithm(algorithm, key)); }
/// <summary> /// Configure config setttings for the service. /// </summary> /// <param name="services">the service configuration.</param> public void ConfigureServices(IServiceCollection services) { // Configure Authentication // Use [Authorize] to require login on MVC Controller Actions X509Certificate2 cert = new X509Certificate2("JWTValidationCert.cer"); SecurityKey key = new X509SecurityKey(cert); services.AddAuthentication(JwtCookieDefaults.AuthenticationScheme) .AddJwtCookie(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = key, ValidateIssuer = false, ValidateAudience = false, RequireExpirationTime = true, ValidateLifetime = true }; options.ExpireTimeSpan = new TimeSpan(0, 30, 0); options.Cookie.Name = "AltinnStudioRuntime"; }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); services.AddMvc().AddControllersAsServices(); services.AddSingleton(Configuration); services.Configure <GeneralSettings>(Configuration.GetSection("GeneralSettings")); services.Configure <PlatformSettings>(Configuration.GetSection("PlatformSettings")); }
public string GetVerifiedUserFromToken(string tokenString) { var securityKey = new X509SecurityKey(_Options.Certificate); var validationParameters = new TokenValidationParameters { ValidIssuer = _Options.ValidIssuer, ValidAudience = _Options.ValidAudience, IssuerSigningKey = securityKey, // Why is this necessary? // Something to do with .NET Core 1.0 // See https://github.com/IdentityServer/IdentityServer3/issues/3040 IssuerSigningKeyResolver = (token, token1, kid, parameters) => new List <X509SecurityKey> { securityKey } }; var handler = new JwtSecurityTokenHandler(); handler.ValidateToken( tokenString, validationParameters, out var securityToken); var jwtSecurityToken = (JwtSecurityToken)securityToken; return(jwtSecurityToken.Subject); }
static IServiceCollection ConfigureJwtOptions(this IServiceCollection services, IConfiguration config) { var keyPath = config.GetByProxy(Config.Jwt.SigningKey); var keyPass = config.GetByProxy(Config.Jwt.Password); var issuer = config.GetValue <string>(Config.Jwt.Issuer); var certPath = config.GetByProxy(Config.Jwt.Certificate); var certBytes = File.ReadAllBytes(certPath); var cert = new X509SecurityKey(new X509Certificate2(certBytes)); services.Configure <JwtSigningOptions>(opts => { opts.Issuer = issuer; opts.Secret = File.ReadAllBytes(keyPath); opts.Password = keyPass; }); services.Configure <JwtVerifyingOptions>(opts => { opts.Issuer = issuer; opts.Certificate = certBytes; opts.KeyId = cert.KeyId; }); return(services); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddHttpContextAccessor(); services.AddAuthorization(options => { options.AddPolicy("DataRead", policy => policy.Requirements.Add(new DataAccessRequirement("read"))); }); services.AddSingleton <IAuthorizationHandler, DataAccessHandler>(); X509Certificate2 cert = new X509Certificate2("C:\\Repos\\JWTAspNetCore\\JWTAspNetCore\\JWTValidationCert.cer"); SecurityKey key = new X509SecurityKey(cert); services.AddAuthentication(x => { x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(x => { x.RequireHttpsMetadata = false; x.SaveToken = true; x.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = key, ValidateIssuer = false, ValidateAudience = false }; }); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddSingleton(this.Logger); //services.AddScoped<GlobalExceptionFilter>(); services.AddMvc( config => { config.Filters.Add(typeof(GlobalExceptionFilter)); } ); services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>(); X509SecurityKey publicKey = null; string rawKey = Configuration.GetSection("AppSettings:TokenKey").Value; var x509Cert = new X509Certificate2(Convert.FromBase64String(rawKey)); publicKey = new X509SecurityKey(x509Cert); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer( options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Configuration.GetSection("AppSettings:TokenKey").Value)), ValidateIssuer = false, ValidateAudience = false, ValidateLifetime = true, ClockSkew = TimeSpan.Zero }; } ); }
static string GetHostName(X509SecurityKey securityKey) { try { #if DEBUG using var chain = new X509Chain(); var chainBuilt = chain.Build(securityKey.Certificate); if (!chainBuilt) { var s = string.Empty; foreach (var chainStatus in chain.ChainStatus) { s += $"Chain error: {chainStatus.Status} {chainStatus.StatusInformation}\n"; } } #endif if (!securityKey.Certificate.Verify()) { return(null); } return(securityKey.Certificate.GetNameInfo(X509NameType.DnsName, false)); } catch (CryptographicException) { return(null); } }
private string GetJwtAssertion() { X509SecurityKey securityKey = new X509SecurityKey(_certificate); JwtHeader header = new JwtHeader(new SigningCredentials(securityKey, SecurityAlgorithms.RsaSha256)) { { "x5c", new List <string> { Convert.ToBase64String(_certificate.GetRawCertData()) } } }; header.Remove("typ"); header.Remove("kid"); DateTimeOffset dateTimeOffset = new DateTimeOffset(DateTime.UtcNow); JwtPayload payload = new JwtPayload { { "aud", _generalSettings.MaskinportenBaseAddress }, { "resource", _generalSettings.MaskinportenResource }, { "scope", _generalSettings.MaskinportenScopes }, { "iss", _generalSettings.MaskinportenClientId }, { "exp", dateTimeOffset.ToUnixTimeSeconds() + 10 }, { "iat", dateTimeOffset.ToUnixTimeSeconds() }, { "jti", Guid.NewGuid().ToString() }, }; JwtSecurityToken securityToken = new JwtSecurityToken(header, payload); JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler(); return(handler.WriteToken(securityToken)); }
private async Task <SecurityToken> CreateSecurityTokenAsync(SignInValidationResult result, ClaimsIdentity outgoingSubject) { var credentials = await _keys.GetSigningCredentialsAsync().ConfigureAwait(false); var x509Key = new X509SecurityKey(credentials.Key.GetX509Certificate(_keys)); var relyingParty = result.RelyingParty; var descriptor = new SecurityTokenDescriptor { Audience = result.Client.ClientId, IssuedAt = DateTime.UtcNow, NotBefore = DateTime.UtcNow, Expires = DateTime.UtcNow.AddSeconds(result.Client.IdentityTokenLifetime), SigningCredentials = new SigningCredentials(x509Key, relyingParty.SignatureAlgorithm, relyingParty.DigestAlgorithm), Subject = outgoingSubject, #if DUENDE Issuer = await _issuerNameService.GetCurrentAsync().ConfigureAwait(false), #else Issuer = _contextAccessor.HttpContext.GetIdentityServerIssuerUri(), #endif }; if (result.RelyingParty.EncryptionCertificate != null) { descriptor.EncryptingCredentials = new X509EncryptingCredentials(result.RelyingParty.EncryptionCertificate); } var handler = CreateTokenHandler(result.RelyingParty.TokenType); return(handler.CreateToken(descriptor)); }
/// <summary> /// Signs the token. /// </summary> /// <param name="token">The token.</param> /// <returns> /// A protected and serialized security token /// </returns> public virtual async Task<string> SignTokenAsync(Token token) { var key = new X509SecurityKey(await _keyService.GetSigningKeyAsync()); var header = await CreateHeaderAsync(token, key); var payload = await CreatePayloadAsync(token); return await SignAsync(new JwtSecurityToken(header, payload)); }
/// <summary> /// Calculates the key id for a given x509 certificate /// </summary> /// <param name="certificate"></param> /// <returns>kid</returns> public Task<string> GetKidAsync(X509Certificate2 certificate) { var key = new X509SecurityKey(certificate); return Task.FromResult(key.KeyId); }