protected override Scope GetScope(ClaimsPrincipal principal, RequestSecurityToken request) { // // TODO: Limit use of STS (via RequestSecurityToken.AppliesTo property) and add encryption in this method. // ValidateAppliesTo(request.AppliesTo); var scope = new Scope(request.AppliesTo.Uri.OriginalString, SecurityTokenServiceConfiguration.SigningCredentials); if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["EncryptionCertificate"])) { // Important note on setting the encrypting credentials. // In a production deployment, you would need to select a certificate that is specific to the RP that is requesting the token. // You can examine the 'request' to obtain information to determine the certificate to use. var encryptingCertificate = GetCertificate(ConfigurationManager.AppSettings["EncryptionCertificate"]); var encryptingCredentials = new X509EncryptingCredentials(encryptingCertificate); scope.EncryptingCredentials = encryptingCredentials; } else { // If there is no encryption certificate specified, the STS will not perform encryption. // This will succeed for tokens that are created without keys (BearerTokens) or asymmetric keys. scope.TokenEncryptionRequired = false; } // Specify where the user will be redirected to, upon posting the form. scope.ReplyToAddress = request.ReplyTo; return(scope); }
protected override Scope GetScope(ClaimsPrincipal principal, RequestSecurityToken request) { if (principal == null) { throw new ArgumentNullException(nameof(principal), "principal cannot be null."); } if (request == null) { throw new ArgumentNullException(nameof(request), "request cannot be null"); } //Creating new Token Scope var scope = new Scope(request.AppliesTo.Uri.OriginalString, SecurityTokenServiceConfiguration.SigningCredentials); //Getting the Certificate from the Certificate Store //which certificate to get is configured by the TokenServiceOptions X509Certificate2 encryptingCertificate = CertificateHelper.GetCertificate(_tokenServiceOptions.CertificateStoreName, _tokenServiceOptions.CertificateStoreLocation, _tokenServiceOptions.CertificateSubject); var encryptingCredentials = new X509EncryptingCredentials(encryptingCertificate); //Setting the encryption credentials for our Scope scope.EncryptingCredentials = encryptingCredentials; //Enable encryption (true by default) scope.TokenEncryptionRequired = true; scope.SymmetricKeyEncryptionRequired = true; scope.ReplyToAddress = request.ReplyTo; return(scope); }
protected virtual byte[] TransformResponse(byte[] response, X509Certificate2 certificate) { var creds = new X509EncryptingCredentials(certificate, SecurityAlgorithms.RsaPKCS1, SecurityAlgorithms.Aes128CbcHmacSha256); var header = new JwtHeader(creds); var payload = new CustomPayload(Encoding.UTF8.GetString(response)); var token = new JwtSecurityToken(header, payload); var responseBody = _jwtHandler.WriteToken(token); return(Encoding.UTF8.GetBytes(responseBody)); }
private X509EncryptingCredentials GetCredentialsForAppliesTo(EndpointAddress appliesTo) { if (appliesTo == null || appliesTo.Uri == null || string.IsNullOrEmpty(appliesTo.Uri.AbsolutePath)) { throw new InvalidRequestException("AppliesTo must be supplied in the RST."); } X509EncryptingCredentials creds; if (!string.IsNullOrWhiteSpace(appliesTo.Uri.AbsoluteUri)) { creds = new X509EncryptingCredentials(GetCertificate(StoreName.My, StoreLocation.LocalMachine)); } else throw new InvalidRequestException(String.Format("Invalid relying party address: {0}", appliesTo.Uri.AbsoluteUri)); return creds; }
public RequestDetailsScope(RequestDetails details, SigningCredentials signingCredentials, bool requireEncryption) : base(details.Realm.Uri.AbsoluteUri, signingCredentials) { RequestDetails = details; if (RequestDetails.UsesEncryption) { EncryptingCredentials = new X509EncryptingCredentials(details.EncryptingCertificate); } if (RequestDetails.TokenType == SimpleWebToken.OasisTokenProfile) { SigningCredentials = new SymmetricSigningCredentials(details.RelyingPartyRegistration.SymmetricSigningKey); } ReplyToAddress = RequestDetails.ReplyToAddress.AbsoluteUri; TokenEncryptionRequired = requireEncryption; }
public SamlRequestDetailsScope(SamlRequestDetails details, EncryptingCredentials signingCredentials, bool requireEncryption) : base(details.Realm.Uri.AbsoluteUri, signingCredentials) { RequestDetails = details; if (RequestDetails.UsesEncryption) { EncryptingCredentials = new X509EncryptingCredentials(details.EncryptingCertificate); } if (RequestDetails.TokenType == TokenTypes.SimpleWebToken || RequestDetails.TokenType == TokenTypes.JsonWebToken) { SigningCredentials = new HmacSigningCredentials(details.RelyingPartyRegistration.SymmetricSigningKey); } ReplyToAddress = RequestDetails.ReplyToAddress.AbsoluteUri; TokenEncryptionRequired = requireEncryption; }
/// <summary> /// Creates the outgoing claims identity. /// </summary> /// <param name="encryptingCredentials">Encrypting credentials for the endpoint to call.</param> /// <param name="claims">Claims from the calling claims identity.</param> /// <returns>Outgoing claims identity.</returns> private static IClaimsIdentity CreateOutgoingClaimsIdentity(X509EncryptingCredentials encryptingCredentials, IEnumerable <Claim> claims) { if (encryptingCredentials == null) { var argumentNullException = new ArgumentNullException("encryptingCredentials"); throw new InvalidRequestException(argumentNullException.Message, argumentNullException); } if (claims == null) { var argumentNullException = new ArgumentNullException("claims"); throw new InvalidRequestException(argumentNullException.Message, argumentNullException); } var outgoingClaimsIdentity = new ClaimsIdentity(encryptingCredentials.Certificate, encryptingCredentials.Certificate.Issuer); foreach (var missingClaim in claims.Where(claim => outgoingClaimsIdentity.Claims.Any(hasClaim => string.Compare(claim.ClaimType, hasClaim.ClaimType, StringComparison.Ordinal) == 0) == false)) { outgoingClaimsIdentity.Claims.Add(new Claim(missingClaim.ClaimType, missingClaim.Value, missingClaim.ValueType, encryptingCredentials.Certificate.Issuer, encryptingCredentials.Certificate.Issuer)); } return(outgoingClaimsIdentity); }
private X509EncryptingCredentials GetCredentialsForAppliesTo(EndpointAddress appliesTo) { if (appliesTo == null || appliesTo.Uri == null || string.IsNullOrEmpty(appliesTo.Uri.AbsolutePath)) { throw new InvalidRequestException("AppliesTo must be supplied in the RST."); } X509EncryptingCredentials creds; if (!string.IsNullOrWhiteSpace(appliesTo.Uri.AbsoluteUri)) { creds = new X509EncryptingCredentials(GetCertificate(StoreName.My, StoreLocation.LocalMachine)); } else { throw new InvalidRequestException(String.Format("Invalid relying party address: {0}", appliesTo.Uri.AbsoluteUri)); } return(creds); }
public RequestDetailsScope(RequestDetails details, SigningCredentials signingCredentials, bool requireEncryption) : base(details.Realm.Uri.AbsoluteUri, signingCredentials) { RequestDetails = details; if (RequestDetails.UsesEncryption) { EncryptingCredentials = new X509EncryptingCredentials(details.EncryptingCertificate); } if (RequestDetails.TokenType == TokenTypes.SimpleWebToken || RequestDetails.TokenType == TokenTypes.JsonWebToken) { if (details.RelyingPartyRegistration.SymmetricSigningKey != null && details.RelyingPartyRegistration.SymmetricSigningKey.Length > 0) { SigningCredentials = new HmacSigningCredentials(details.RelyingPartyRegistration.SymmetricSigningKey); } } ReplyToAddress = RequestDetails.ReplyToAddress.AbsoluteUri; TokenEncryptionRequired = requireEncryption; }
protected override Scope GetScope(ClaimsPrincipal principal, RequestSecurityToken request) { if (request.AppliesTo == null) { throw new InvalidRequestException("Specify RP in AppliesTo"); } if (!request.AppliesTo.Uri.Equals(new Uri("http://my-server.com"))) { Console.WriteLine("Invalid Relying party Address "); throw new InvalidRequestException("Invalid Relying party Address "); } var encryptingCredentials = new X509EncryptingCredentials("CN=RP".ToCertificate()); Scope scope = new Scope(request.AppliesTo.Uri.AbsoluteUri, SecurityTokenServiceConfiguration.SigningCredentials, encryptingCredentials); return(scope); }
public void Constructors(X509EncryptingCredentialsTheoryData theoryData) { var context = TestUtilities.WriteHeader($"{this}.Constructors", theoryData); try { var encryptingCredentials = new X509EncryptingCredentials(theoryData.Certificate, theoryData.Alg, theoryData.Enc); var encryptingCredentialsFromCert = new X509EncryptingCredentials(theoryData.Certificate); IdentityComparer.AreEqual(encryptingCredentials.Certificate, encryptingCredentialsFromCert.Certificate, context); IdentityComparer.AreEqual(encryptingCredentials.Key, encryptingCredentialsFromCert.Key, context); IdentityComparer.AreEqual(encryptingCredentials.Certificate, encryptingCredentialsFromCert.Certificate, context); IdentityComparer.AreEqual(encryptingCredentials.Alg, encryptingCredentialsFromCert.Alg, context); IdentityComparer.AreEqual(encryptingCredentials.Enc, encryptingCredentialsFromCert.Enc, context); theoryData.ExpectedException.ProcessNoException(context); } catch (Exception exception) { theoryData.ExpectedException.ProcessException(exception, context); } TestUtilities.AssertFailIfErrors(context); }
private void GetSigningCredentialsFromCertificate(string certificate, string password) { try { var certificateEncryptionAlgorithm = JwtOptions.Security.CertificateEncryptionAlgorithm ?? SecurityAlgorithms.Sha512; Certificate = new X509Certificate2(File.ReadAllBytes(FileOperations.GetFileFullPath(certificate)), password, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet); SecurityKey = new X509SecurityKey(Certificate); IssuerSigningKey = new X509SecurityKey(Certificate); EncryptingCredentials = new X509EncryptingCredentials(Certificate); SigningCredentials = new SigningCredentials(IssuerSigningKey, certificateEncryptionAlgorithm); } catch (CryptographicException ex) { Console.WriteLine(ex); throw; } catch (ArgumentNullException ex) { Console.WriteLine(ex); throw; } }
/// <summary> /// This method returns the configuration for the token issuance request. The configuration /// is represented by the Scope class. In our case, we are only capable of issuing a token to a /// single RP identity represented by CN=localhost. /// </summary> /// <param name="principal">The caller's principal</param> /// <param name="request">The incoming RST</param> /// <returns></returns> protected override Scope GetScope(IClaimsPrincipal principal, RequestSecurityToken request) { // We only support a single RP identity represented by CN=localhost. Set the RP certificate for encryption X509EncryptingCredentials encryptingCredentials = new X509EncryptingCredentials( CertificateUtil.GetCertificate(StoreName.My, StoreLocation.LocalMachine, EncryptingCertificateName)); // Create the scope using the request AppliesTo address, the STS signing certificate and the encryptingCredentials for the RP. if (request.AppliesTo == null || request.AppliesTo.Uri == null) { throw new InvalidRequestException("Cannot determine the AppliesTo address from the RequestSecurityToken."); } Scope scope = new Scope(request.AppliesTo.Uri.AbsoluteUri, SecurityTokenServiceConfiguration.SigningCredentials, encryptingCredentials); // Set the replyTo address. In WS-Federation passive case this value is used as the endpoint // where the user is redirected to. scope.ReplyToAddress = scope.AppliesToAddress; return(scope); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler(builder => { builder.Run(async context => { context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; var error = context.Features.Get <IExceptionHandlerFeature>(); if (error != null) { context.Response.AddApplicationError(error.Error.Message); await context.Response.WriteAsync(error.Error.Message); } }); } ); } //app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseCors(X509EncryptingCredentials => X509EncryptingCredentials.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()); app.UseEndpoints(endpoints => { endpoints.MapControllers(); // endpoints.MapFallbackToController("Index", "Fallback"); }); }
/// <summary> /// This method returns the configuration for the token issuance request. The configuration /// is represented by the Scope class. In our case, we are only capable of issuing a token to a /// single RP identity represented by CN=localhost. /// </summary> /// <param name="principal">The caller's principal</param> /// <param name="request">The incoming RST</param> /// <returns>The configuration for the token issuance request.</returns> protected override Scope GetScope(IClaimsPrincipal principal, RequestSecurityToken request) { // Validate the AppliesTo on the incoming request ValidateAppliesTo(request.AppliesTo); // Normally the STS will have a trust relationship with the RP and can look up a trusted encrypting certficate // using the AppliesTo endpoint. This is necessary to ensure that only the RP will be able to read the claims. // // In this sample the certificate of the AppliesTo Identity is used to encrypt the contents, so there is no // validation of any trust relationship with the RP. Since the certificate is not validated, // a malicious client can provide a known certificate allowing it to read the returned claims. // For this reason, THIS APPROACH SHOULD NOT BE USED if the claims should be kept private. It may be reasonable, // though, if the STS is simply verifying public information such as the client's email address. // Get RP certificate X509CertificateEndpointIdentity appliesToIdentity = (X509CertificateEndpointIdentity)request.AppliesTo.Identity; X509EncryptingCredentials encryptingCredentials = new X509EncryptingCredentials(appliesToIdentity.Certificates[0]); // Create the scope using the request AppliesTo address and the STS signing certificate Scope scope = new Scope(request.AppliesTo.Uri.AbsoluteUri, SecurityTokenServiceConfiguration.SigningCredentials, encryptingCredentials); return(scope); }
public async Task <AccessToken> GenerateAsync(User user) { var secretKey = Encoding.UTF8.GetBytes(_siteSetting.JwtSettings.SecretKey); // longer that 16 character var signingCredentials = new SigningCredentials(new SymmetricSecurityKey(secretKey), SecurityAlgorithms.HmacSha256Signature); //var encryptionkey = Encoding.UTF8.GetBytes(_siteSetting.JwtSettings.Encryptkey); //must be 16 character //var encryptingCredentials = new EncryptingCredentials(new SymmetricSecurityKey(encryptionkey), SecurityAlgorithms.Aes128KW, SecurityAlgorithms.Aes128CbcHmacSha256); var certificate = new X509Certificate2("d:\\aaaa2.cer" /*, "P@ssw0rd"*/); var encryptingCredentials = new X509EncryptingCredentials(certificate); var claims = await _getClaimsAsync(user); var descriptor = new SecurityTokenDescriptor { Issuer = _siteSetting.JwtSettings.Issuer, Audience = _siteSetting.JwtSettings.Audience, IssuedAt = DateTime.Now, NotBefore = DateTime.Now.AddMinutes(_siteSetting.JwtSettings.NotBeforeMinutes), Expires = DateTime.Now.AddMinutes(_siteSetting.JwtSettings.ExpirationMinutes), SigningCredentials = signingCredentials, EncryptingCredentials = encryptingCredentials, Subject = new ClaimsIdentity(claims) }; //JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); //JwtSecurityTokenHandler.DefaultMapInboundClaims = false; //JwtSecurityTokenHandler.DefaultOutboundClaimTypeMap.Clear(); var tokenHandler = new JwtSecurityTokenHandler(); var securityToken = tokenHandler.CreateJwtSecurityToken(descriptor); //string encryptedJwt = tokenHandler.WriteToken(securityToken); return(new AccessToken(securityToken)); }