public override SecurityKey CreateKey()
 {
     if (this.rsaSecurityKey == null)
     {
         this.rsaSecurityKey = new RsaSecurityKey(this.rsa);
     }
     return this.rsaSecurityKey;
 }
		public static D2LSecurityToken CreateTokenWithTimeRemaining(
			TimeSpan remaining,
			Guid? id = null
		) {

			id = id ?? Guid.NewGuid();

			var validTo = DateTime.UtcNow + remaining;
			var validFrom = validTo - TimeSpan.FromHours( 1 );

			RSAParameters privateKey;
			using( var csp = new RSACryptoServiceProvider( Keys.Constants.GENERATED_RSA_KEY_SIZE ) {
				PersistKeyInCsp = false
			} ) {
				privateKey = csp.ExportParameters( includePrivateParameters: true );
			}

			return new D2LSecurityToken(
				id.Value,
				validFrom,
				validTo,
				keyFactory: () => {
					var csp = new RSACryptoServiceProvider() { PersistKeyInCsp = false };
					csp.ImportParameters( privateKey );
					var key = new RsaSecurityKey( csp );
					return new Tuple<AsymmetricSecurityKey, IDisposable>( key, csp );
				}
			);
		}
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //load key from file
            RSAParameters keyParams = SecurityRSAUtils.GetKeyParameters(@"C:\_Projects\auth.spear.roimantra.com\src\auth.spear.roimantra.com\SecurityKey\jwt_private_security_key.txt");


            _securityKey = new RsaSecurityKey(keyParams);

            _tokenOptions = new SecurityTokenAuthOptions()
            {
                Audience = TokenAudience,
                Issuer = TokenIssuer,
                SigningCredentials = new SigningCredentials(_securityKey, SecurityAlgorithms.RsaSha256Signature)
            };

            // Save the token options into an instance so they're accessible to the 
            // controller.
            services.AddInstance<SecurityTokenAuthOptions>(_tokenOptions);

            // Enable the use of an [Authorize("Bearer")] attribute on methods and classes to protect.
            services.AddAuthorization(auth =>
            {
                auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
                    .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme‌​)
                    .RequireAuthenticatedUser().Build());
            });

            services.AddMvc();
        }
示例#4
0
        /// <summary>
        /// Creates a SAML token for the specified email address and security token.
        /// </summary>
        private SamlSecurityToken CreateSAMLToken(
            string emailAddress,
            X509SecurityToken issuerToken)
        {
            // Create list of confirmation strings
            List <string> confirmations = new List <string>();

            // Add holder-of-key string to list of confirmation strings
            confirmations.Add("urn:oasis:names:tc:SAML:1.0:cm:bearer");

            // Create SAML subject statement based on issuer member variable, confirmation string collection
            // local variable and proof key identifier parameter
            SamlSubject subject =
                new SamlSubject("urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress", null, emailAddress);

            // Create a list of SAML attributes
            List <SamlAttribute> attributes = new List <SamlAttribute>();
            Claim claim = Claim.CreateNameClaim(emailAddress);

            attributes.Add(new SamlAttribute(claim));

            // Create list of SAML statements
            List <SamlStatement> statements = new List <SamlStatement>();

            // Add a SAML attribute statement to the list of statements. Attribute statement is based on
            // subject statement and SAML attributes resulting from claims
            statements.Add(new SamlAttributeStatement(subject, attributes));

            // Create a valid from/until condition
            DateTime validFrom = DateTime.UtcNow;
            DateTime validTo   = DateTime.UtcNow.AddHours(12);

            SamlConditions conditions = new SamlConditions(validFrom, validTo);

            // Create the SAML assertion
            SamlAssertion assertion = new SamlAssertion(
                "_" + Guid.NewGuid().ToString(),
                issuerToken.Certificate.Subject,
                validFrom,
                conditions,
                null,
                statements);

            SecurityKey signingKey =
                new System.IdentityModel.Tokens.RsaSecurityKey((RSA)issuerToken.Certificate.PrivateKey);

            // Set the signing credentials for the SAML assertion
            assertion.SigningCredentials = new SigningCredentials(
                signingKey,
                System.IdentityModel.Tokens.SecurityAlgorithms.RsaSha1Signature,
                System.IdentityModel.Tokens.SecurityAlgorithms.Sha1Digest,
                new SecurityKeyIdentifier(issuerToken.CreateKeyIdentifierClause <X509ThumbprintKeyIdentifierClause>()));

            return(new SamlSecurityToken(assertion));
        }
        public AzureKeyVaultSigningCredentials(RsaSecurityKey signingKey, string digestAlgorithm, SecurityKeyIdentifier signingKeyIdentifier = null) : base(signingKey, SecurityAlgorithms.RsaSha256Signature, digestAlgorithm, signingKeyIdentifier)
        {
            if (signingKey.HasPrivateKey())
            {
                throw new ArgumentException("For security reasons, the signing key cannot contain the private key. Please remove all traces of this from the application and defer to Azure Key Vault for signing.", nameof(signingKey));
            }

            if (digestAlgorithm != SecurityAlgorithms.Sha256Digest && digestAlgorithm != SecurityAlgorithms.Sha512Digest)
            {
                throw new ArgumentOutOfRangeException(nameof(digestAlgorithm), digestAlgorithm, "Only SHA256 and SHA512 are supported at this time.");
            }
        }
        /// <summary> Loads the RsaSecurityKey from <c>Configs\RSA.Key</c>. </summary>
        public static RsaSecurityKey LoadRsaSecurityKey(String path)
        {
            if (String.IsNullOrEmpty(path)) throw new ArgumentException("path is null or empty.", nameof(path));

            using (var textReader = new System.IO.StreamReader(path))
            {
                RSACryptoServiceProvider cryptoServiceProvider = new RSACryptoServiceProvider();
                cryptoServiceProvider.FromXmlString(textReader.ReadToEnd());

                var key = new RsaSecurityKey(cryptoServiceProvider.ExportParameters(true));
                return key;
            }
        }
        /// <summary>
        /// Retrieves the signing credential (override to load key from alternative locations)
        /// </summary>
        /// <returns>The signing credential</returns>
        protected virtual async Task<AzureKeyVaultSigningCredentials> GetSigningCredentialsAsync()
        {
            var jwk = (await _publicKeyProvider.GetAsync()).FirstOrDefault();
            if (jwk == null) throw new Exception("The public key provider service did not return a key."); // TODO: What's better than Exception? SecurityTokenSignatureKeyNotFoundException maybe?

            var rsa = RSA.Create();
            rsa.ImportParameters(new RSAParameters
            {
                Exponent = FromBase64Url(jwk.E),
                Modulus = FromBase64Url(jwk.N),
            });
            var securityKey = new RsaSecurityKey(rsa);

            return new AzureKeyVaultSigningCredentials(securityKey, SecurityAlgorithms.Sha256Digest);
        }
		internal override D2LSecurityToken ToSecurityToken() {
			var token = new D2LSecurityToken(
				id: Id,
				validFrom: DateTime.UtcNow,
				validTo: ExpiresAt ?? DateTime.UtcNow + Constants.REMOTE_KEY_MAX_LIFETIME,
				keyFactory: () => {
					var rsa = new RSACryptoServiceProvider() { PersistKeyInCsp = false };
					rsa.ImportParameters( m_parameters );
					var key = new RsaSecurityKey( rsa );
					return new Tuple<AsymmetricSecurityKey, IDisposable>( key, rsa );
				}
			);
			
			return token;
		}
		public async Task<IActionResult> Post([FromBody] RegistrationRequestModel registrationRequestModel)
		{
			if (!ModelState.IsValid)
			{
				return HttpUnauthorized();
			}
			
			if (UserManager.Users.Any(u => u.UserName == registrationRequestModel.UserName))
			{
				return HttpBadRequest($"User {registrationRequestModel.UserName} is already exists");
				// throw new DuplicateNameException();
			}

			var result = await UserManager.CreateAsync(new User()
			{
				UserName = registrationRequestModel.UserName,
				Email = registrationRequestModel.Email
			}, registrationRequestModel.Password);

			if (!result.Succeeded)
			{
				//TODO: change to aprop error
				return HttpUnauthorized();
			}

			var user = UserManager.Users.First(u => u.UserName == registrationRequestModel.UserName);

			var roles = await UserManager.GetRolesAsync(user);
			var claims = new List<Claim>(new Claim[] { new Claim(ClaimTypes.Name, user.UserName) });
			claims.AddRange(roles.Select(r => new Claim(ClaimTypes.Role, r)));
			claims.AddRange(user.Claims.Select(c => new Claim(c.ClaimType, c.ClaimValue)));
			var identity = new ClaimsIdentity(claims, "JWT");

			var handler = new JwtSecurityTokenHandler();
			var rsa = new RSACryptoServiceProvider(2048);
			var rsaParams = rsa.ExportParameters(true);
			var rsaKey = new RsaSecurityKey(rsaParams);

			var secKey = string.Empty;   // Shared secure key that used for JWT auth

			var secToken = handler.CreateToken("myself", "myself", identity, DateTime.UtcNow, DateTime.UtcNow.AddDays(1),
				new SigningCredentials(rsaKey, JwtAlgorithms.RSA_SHA256, JwtAlgorithms.RSA_SHA256, secKey));


			var token = handler.WriteToken(secToken);

			return this.Ok(token);
		}
 public static TokenAuthOptions GetTokenOptions(IServiceProvider aServiceProvider)
 {
   RSAKeyUtils lRsaKeyUtils = ActivatorUtilities.CreateInstance<RSAKeyUtils>(aServiceProvider);
   // Create the key, and a set of token options to record signing credentials 
   // using that key, along with the other parameters we will need in the 
   // token controlller.
   RSAParameters lKeyParams = RSAKeyUtils.GetKeyParameters("authtoken.key");
   RsaSecurityKey lKey = new RsaSecurityKey(lKeyParams);
   TokenAuthOptions lTokenOptions = new TokenAuthOptions()
   {
     Audience = Startup.TokenAudience,
     Issuer = Startup.TokenIssuer,
     SigningCredentials = new SigningCredentials(lKey, SecurityAlgorithms.RsaSha256Signature)
   };
   return lTokenOptions;
 }
示例#11
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Set up key for signing bearer tokens
            // TODO: A real key for production
            RSAParameters keyParams = RSAKeyUtils.GetRandomKey();
            key = new RsaSecurityKey(keyParams);
            tokenOptions = new TokenAuthOptions()
            {
                Audience = TokenAudience,
                Issuer = TokenIssuer,
                SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.RsaSha256Signature)
            };
            services.AddInstance<TokenAuthOptions>(tokenOptions);
            
            services.AddAuthorization(auth => {
                auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
                .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
                .RequireAuthenticatedUser().Build());
            });

            // Add framework services.
            services.AddEntityFramework()
                .AddSqlServer()
                .AddDbContext<ApplicationDbContext>(options =>
                    options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));

            services.AddIdentity<ApplicationUser, IdentityRole<Guid>>(options => {
                    options.Password.RequireNonLetterOrDigit = false;
                    options.Password.RequireUppercase = false;
                })
                .AddEntityFrameworkStores<ApplicationDbContext,Guid>()
                .AddDefaultTokenProviders();

            services.AddAuthentication();
            services.AddCaching();
            services.AddMvc();

            // Add application services.
            services.AddTransient<IEmailSender, AuthMessageSender>();
            services.AddTransient<ISmsSender, AuthMessageSender>();
        }
        public void ConfigureServices(IServiceCollection services)
        {
            // *** CHANGE THIS FOR PRODUCTION USE ***
            // Here, we're generating a random key to sign tokens - obviously this means
            // that each time the app is started the key will change, and multiple servers 
            // all have different keys. This should be changed to load a key from a file 
            // securely delivered to your application, controlled by configuration.
            //
            // See the RSAKeyUtils.GetKeyParameters method for an examle of loading from
            // a JSON file.
            RSAParameters keyParams = RSAKeyUtils.GetRandomKey();

            // Create the key, and a set of token options to record signing credentials 
            // using that key, along with the other parameters we will need in the 
            // token controlller.
            key = new RsaSecurityKey(keyParams);
            tokenOptions = new TokenAuthOptions()
            {
                Audience = TokenAudience,
                Issuer = TokenIssuer,
                SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.RsaSha256Signature)
            };

            // Save the token options into an instance so they're accessible to the 
            // controller.
            services.AddInstance<TokenAuthOptions>(tokenOptions);

            // Enable the use of an [Authorize("Bearer")] attribute on methods and classes to protect.
            services.AddAuthorization(auth =>
            {
                auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
                    .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme‌​)
                    .RequireAuthenticatedUser().Build());
            });

            services.AddMvc();
        }
示例#13
0
        private void GenerateRsaKeys()
        {
            var key = "IxrAjDoa2FqElO7IhrSrUJELhUckePEPVpaePlS_Xaw";
            var keyByte = TextEncodings.Base64Url.Decode(key);
            var symmetricSecurityKey = new SymmetricSecurityKey(keyByte);
            using (var rsa = new RSACryptoServiceProvider(2048))
            {
                _key = new RsaSecurityKey(rsa.ExportParameters(true));

                _signingCredentials = new SigningCredentials(
                    symmetricSecurityKey,
                    SecurityAlgorithms.HmacSha256Signature,
                    SecurityAlgorithms.Sha256Digest,
                    "secret");

                rsa.PersistKeyInCsp = false;
            }
        }
		public async Task<IActionResult> Login([FromBody] AuthRequestModel authRequestModel)
		{
			if (!ModelState.IsValid)
			{
				return HttpUnauthorized();
			}

			var user = UserManager.Users.FirstOrDefault(u => u.UserName == authRequestModel.UserName);
			if (user == null || !await this.UserManager.CheckPasswordAsync(user, authRequestModel.Password))
			{
				return HttpUnauthorized();
			}

			var roles = await UserManager.GetRolesAsync(user);
			var claims = new List<Claim>(new Claim[] { new Claim(ClaimTypes.Name, user.UserName) });
			claims.AddRange(roles.Select(r => new Claim(ClaimTypes.Role, r)));
			claims.AddRange(user.Claims.Select(c => new Claim(c.ClaimType, c.ClaimValue)));
			var identity = new ClaimsIdentity(claims, "JWT");

			var handler = new JwtSecurityTokenHandler();
			var rsa = new RSACryptoServiceProvider(2048);
			var rsaParams = rsa.ExportParameters(true);
			var rsaKey = new RsaSecurityKey(rsaParams);

			var secKey = string.Empty;   // Shared secure key that used for JWT auth

			var secToken = handler.CreateToken("myself", "myself", identity, DateTime.UtcNow, DateTime.UtcNow.AddDays(1),
				new SigningCredentials(rsaKey, JwtAlgorithms.RSA_SHA256, JwtAlgorithms.RSA_SHA256, secKey));


			var token = handler.WriteToken(secToken);

			return this.Ok(token);
		}
示例#15
0
        /// <summary>
        /// Creates a SAML token for the specified email address.
        /// </summary>
        public static async System.Threading.Tasks.Task <UserIdentity> CreateSAMLTokenAsync(string emailAddress)
        {
            // Normally this would be done by a server that is capable of verifying that
            // the user is a legimate holder of email address. Using a local certficate to
            // signed the SAML token is a short cut that would never be done in a real system.
            CertificateIdentifier userid = new CertificateIdentifier();

            userid.StoreType   = CertificateStoreType.X509Store;
            userid.StorePath   = "LocalMachine\\My";
            userid.SubjectName = "UA Sample Client";

            X509Certificate2 certificate = await userid.Find();

            X509SecurityToken signingToken = new X509SecurityToken(certificate);

            // Create list of confirmation strings
            List <string> confirmations = new List <string>();

            // Add holder-of-key string to list of confirmation strings
            confirmations.Add("urn:oasis:names:tc:SAML:1.0:cm:bearer");

            // Create SAML subject statement based on issuer member variable, confirmation string collection
            // local variable and proof key identifier parameter
            SamlSubject subject = new SamlSubject("urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress", null, emailAddress);

            // Create a list of SAML attributes
            List <SamlAttribute> attributes = new List <SamlAttribute>();
            Claim claim = Claim.CreateNameClaim(emailAddress);

            attributes.Add(new SamlAttribute(claim));

            // Create list of SAML statements
            List <SamlStatement> statements = new List <SamlStatement>();

            // Add a SAML attribute statement to the list of statements. Attribute statement is based on
            // subject statement and SAML attributes resulting from claims
            statements.Add(new SamlAttributeStatement(subject, attributes));

            // Create a valid from/until condition
            DateTime validFrom = DateTime.UtcNow;
            DateTime validTo   = DateTime.UtcNow.AddHours(12);

            SamlConditions conditions = new SamlConditions(validFrom, validTo);

            // Create the SAML assertion
            SamlAssertion assertion = new SamlAssertion(
                "_" + Guid.NewGuid().ToString(),
                signingToken.Certificate.Subject,
                validFrom,
                conditions,
                null,
                statements);

            SecurityKey signingKey = new System.IdentityModel.Tokens.RsaSecurityKey((RSA)signingToken.Certificate.PrivateKey);

            // Set the signing credentials for the SAML assertion
            assertion.SigningCredentials = new SigningCredentials(
                signingKey,
                System.IdentityModel.Tokens.SecurityAlgorithms.RsaSha1Signature,
                System.IdentityModel.Tokens.SecurityAlgorithms.Sha1Digest,
                new SecurityKeyIdentifier(signingToken.CreateKeyIdentifierClause <X509ThumbprintKeyIdentifierClause>()));
            // TODO
            // return new UserIdentity(new SamlSecurityToken(assertion));
            throw new NotImplementedException();
        }
示例#16
0
        /// <summary>
        /// Creates a SAML token for the specified email address.
        /// </summary>
        public static UserIdentity CreateSAMLToken(string emailAddress)
        {
            // Normally this would be done by a server that is capable of verifying that
            // the user is a legimate holder of email address. Using a local certficate to
            // signed the SAML token is a short cut that would never be done in a real system.
            CertificateIdentifier userid = new CertificateIdentifier();

            userid.StoreType = CertificateStoreType.Windows;
            userid.StorePath = "LocalMachine\\My";
            userid.SubjectName = "UA Sample Client";

            X509Certificate2 certificate = userid.Find();
            X509SecurityToken signingToken = new X509SecurityToken(certificate);

            // Create list of confirmation strings
            List<string> confirmations = new List<string>();

            // Add holder-of-key string to list of confirmation strings
            confirmations.Add("urn:oasis:names:tc:SAML:1.0:cm:bearer");

            // Create SAML subject statement based on issuer member variable, confirmation string collection 
            // local variable and proof key identifier parameter
            SamlSubject subject = new SamlSubject("urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress", null, emailAddress);

            // Create a list of SAML attributes
            List<SamlAttribute> attributes = new List<SamlAttribute>();
            Claim claim = Claim.CreateNameClaim(emailAddress);
            attributes.Add(new SamlAttribute(claim));

            // Create list of SAML statements
            List<SamlStatement> statements = new List<SamlStatement>();

            // Add a SAML attribute statement to the list of statements. Attribute statement is based on 
            // subject statement and SAML attributes resulting from claims
            statements.Add(new SamlAttributeStatement(subject, attributes));

            // Create a valid from/until condition
            DateTime validFrom = DateTime.UtcNow;
            DateTime validTo = DateTime.UtcNow.AddHours(12);

            SamlConditions conditions = new SamlConditions(validFrom, validTo);

            // Create the SAML assertion
            SamlAssertion assertion = new SamlAssertion(
                "_" + Guid.NewGuid().ToString(),
                signingToken.Certificate.Subject,
                validFrom,
                conditions,
                null,
                statements);

            SecurityKey signingKey = new System.IdentityModel.Tokens.RsaSecurityKey((RSA)signingToken.Certificate.PrivateKey);

            // Set the signing credentials for the SAML assertion
            assertion.SigningCredentials = new SigningCredentials(
                signingKey,
                System.IdentityModel.Tokens.SecurityAlgorithms.RsaSha1Signature,
                System.IdentityModel.Tokens.SecurityAlgorithms.Sha1Digest,
                new SecurityKeyIdentifier(signingToken.CreateKeyIdentifierClause<X509ThumbprintKeyIdentifierClause>()));

            return new UserIdentity(new SamlSecurityToken(assertion));
        }
示例#17
0
        /*private string GetSignedJwtToken(string rsaKeyFilePath, X509Certificate2 cert, string url)
        {
            //var claimsetSerialized = @"{""token_class"":""solution_assertion"",""token_type"":""Bearer""" +
            //    @",""jti"":""" + new Random().Next().ToString() + @"""" +
            //    @",""iss"":""" + cert.Subject + @""",""sub"":""" + cert.Subject + @"""" +
            //    @",""aud"":""" + url + @""",""iat"":""" + DateTimeHelper.WindowsToUnix(DateTime.Now).ToString() + @"""" +
            //    @",""exp"":""" + DateTimeHelper.WindowsToUnix(DateTime.Now.AddTicks(356 * 24 * 60 * 60)).ToString() + @"""}";

            // header
            //var headerSerialized = @"{""typ"":""JWT"", ""alg"":""RS256""}";
            var header = new JwtHeaderDto { Typ = "JWT", Alg = "RS256" };

            // encoded header
            var headerSerialized = JsonConvert.Serialize(header);
            var headerBytes = Encoding.UTF8.GetBytes(headerSerialized);
            var headerEncoded = Convert.ToBase64String(headerBytes);

            // encoded claimset
            var claimset = new JwtClaimDto
            {
                TokenClass = "solution_assertion",
                TokenType = "Bearer",
                Jti = new Random().Next().ToString(),
                Iss = cert.Subject,
                Sub = cert.Subject,
                Aud = url,
                Iat = DateTimeHelper.WindowsToUnix(DateTime.Now).ToString(),
                Exp = DateTimeHelper.WindowsToUnix(DateTime.Now.AddTicks(356 * 24 * 60 * 60)).ToString()
            };
            //var claimset = new JwtPayload
            //{
            //    Jti = new Random().Next().ToString(),
            //    Iss = cert.Subject,
            //    Sub = cert.Subject,
            //    Aud = url,
            //    Iat = DateTimeHelper.WindowsToUnix(DateTime.Now).ToString(),
            //    Exp = DateTimeHelper.WindowsToUnix(DateTime.Now.AddTicks(356 * 24 * 60 * 60)).ToString(),
            //    Claims = new List<Claim>() { new Claim("token_class", "solution_assertion"), new Claim("token_type", "Bearer") }
            //};
            //var claimset = new JwtPayload();
            //var claims = new List<Claim>();
            //claims.Add(new Claim("token_class", "solution_assertion"));
            //claims.Add(new Claim("token_type", "Bearer"));
            //claims.Add(new Claim("jti", new Random().Next().ToString()));
            //claims.Add(new Claim("iss", cert.Subject));
            //claims.Add(new Claim("sub", cert.Subject));
            //claims.Add(new Claim("aud", url));
            //claims.Add(new Claim("iat", DateTimeHelper.WindowsToUnix(DateTime.Now).ToString()));
            //claims.Add(new Claim("exp", DateTimeHelper.WindowsToUnix(DateTime.Now.AddTicks(356 * 24 * 60 * 60)).ToString()));
            //claimset.AddClaims(claims);
            var claimsetSerialized = JsonConvert.Serialize(claimset);
            var claimsetBytes = Encoding.UTF8.GetBytes(claimsetSerialized);
            var claimsetEncoded = Convert.ToBase64String(claimsetBytes);

            // input
            var input = String.Join(".", headerEncoded, claimsetEncoded);
            var inputBytes = Encoding.UTF8.GetBytes(input);

            //var signatureBytes = rsaKey.SignData(inputBytes, "SHA256");
            var signature = ShaWithRsaSigner.Sign(input, rsaKeyFilePath, "SHA256");
            var signatureBytes = Encoding.UTF8.GetBytes(signature);
            var signatureEncoded = Convert.ToBase64String(signatureBytes);

            // jwt
            return String.Join(".", input, signatureEncoded);
        }*/
        private string GetSignedJwtToken(RSACryptoServiceProvider rsa, X509Certificate2 cert, string url)
        {
            var claims = new List<Claim>();
            claims.Add(new Claim("token_class", "solution_assertion"));
            claims.Add(new Claim("token_type", "Bearer"));
            claims.Add(new Claim("jti", new Random().Next().ToString()));
            claims.Add(new Claim("sub", cert.Subject));
            var payload = new JwtPayload(cert.Issuer, url, claims, DateTime.Now, DateTime.Now.AddMinutes(5));

            //var cert = new X509Certificate2(Encoding.UTF8.GetBytes(certificate.Encoded));
            //var signingCredentials = new X509SigningCredentials(cert);
            //var payload = new JwtPayload(cert.Subject,url, DateTime.Now,DateTime.Now.AddMinutes(5));
            //var claims = new List<Claim>();
            //claims.Add(new Claim("token_class", "solution_assertion"));
            //claims.Add(new Claim("token_type", "Bearer"));
            //claims.Add(new Claim("jti", new Random().Next().ToString()));
            //claims.Add(new Claim("iss", cert.Subject));
            //claims.Add(new Claim("sub", cert.Subject));
            //claims.Add(new Claim("aud", url));
            //claims.Add(new Claim("iat", DateTimeHelper.WindowsToUnix(DateTime.Now).ToString()));
            //claims.Add(new Claim("exp", DateTimeHelper.WindowsToUnix(DateTime.Now.AddTicks(356 * 24 * 60 * 60)).ToString()));
            //payload.Exp = DateTimeHelper.WindowsToUnix(DateTime.Now.AddTicks(356 * 24 * 60 * 60));
            //payload.Iat = DateTimeHelper.WindowsToUnix(DateTime.Now);
            //payload.AddClaims(claims);

            //var keyBytes = GetBytes(privateKey.Encoded);
            //var key = new InMemorySymmetricSecurityKey(keyBytes);
            var key = new RsaSecurityKey(rsa);
            var signingCredentials = new SigningCredentials(key, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest);

            var header = new JwtHeader(signingCredentials);
            var token = new JwtSecurityToken(header, payload);
            var jwtSecurityTokenHandler = new JwtSecurityTokenHandler();
            try
            {                
                var jsonToken = jwtSecurityTokenHandler.WriteToken(token);
                return jsonToken;
            }
            catch (Exception)
            {
                // todo: Log exception                
            }
            return null;
        }
示例#18
0
        // This method gets called by a runtime.
        // Use this method to add services to the container
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddEntityFramework()
                .AddSqlServer()
                .AddDbContext<ApplicationDbContext>(options =>
                    options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));

            services.AddIdentity<ApplicationUser, IdentityRole>(options => {
                options.User.RequireUniqueEmail = true;
            })
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();

            services.AddMvc().Configure<MvcOptions>(options => {
                var jsonFormatter = options.OutputFormatters.OfType<JsonOutputFormatter>().First();

                jsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
                jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            });
            // Uncomment the following line to add Web API services which makes it easier to port Web API 2 controllers.
            // You will also need to add the Microsoft.AspNet.Mvc.WebApiCompatShim package to the 'dependencies' section of project.json.
            // services.AddWebApiConventions();

            // Bearer Token Stuff
            #region Bearer Token Setup
            RsaSecurityKey key;
            RSACryptoServiceProvider publicAndPrivate = new RSACryptoServiceProvider();
            var savykeyParams = JsonConvert.DeserializeObject<RSAParametersSerializable>(Configuration["rsa-key"]);
            //This if is necessary because migrations don't find environment variables, and so we have to put a blank savy-rsa-key in the config file.
            //That creates a null object. Thus the if.
            if(savykeyParams != null) {
                publicAndPrivate.ImportParameters(savykeyParams.RSAParameters);

                key = new RsaSecurityKey(publicAndPrivate.ExportParameters(true));

                services.AddInstance(new SigningCredentials(key, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest));

                services.Configure<OAuthBearerAuthenticationOptions>(bearer => {
                    bearer.TokenValidationParameters.IssuerSigningKey = key;
                    bearer.TokenValidationParameters.ValidAudience = "mybearertokenapi";
                    bearer.TokenValidationParameters.ValidIssuer = "mybearertokenapi";
                    bearer.Notifications.AuthenticationFailed = async notification => {
                        if(notification.Exception.GetType() == typeof(SecurityTokenExpiredException)) {
                            //TODO: Figure out how to actually send a body. Just getting a 0-length 401 right now.
                            var message = "Access token expired.";
                            notification.HttpContext.Response.StatusCode = 401;
                            //notification.HttpContext.Response.ContentLength = message.Length * 2;
                            notification.HttpContext.Response.ContentType = "application/json; charset=utf-8";
                            await notification.HttpContext.Response.WriteAsync(message);

                        }
                    };
                });
            }

            #endregion

            services.AddScoped<IAuthRepository, AuthRepository>();

            // Authorization policies
            services.ConfigureAuthorization(auth => {
                auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
                    .AddAuthenticationSchemes(OAuthBearerAuthenticationDefaults.AuthenticationScheme‌​)
                    .RequireAuthenticatedUser()
                    .Build());
            });
        }
        public void ConfigureServices(IServiceCollection services)
        {
            RsaSecurityKey key;

            // Obviously, hard coding the private key here is a horrendous idea - this should be passed in from
            // some sort of configuration file supplied securely to the application. This is just to prove the
            // concept of the auth strategy.
            RSAParameters p = new RSAParameters()
            {
                Modulus = Convert.FromBase64String("z7eXmrs9z3Xm7VXwYIdziDYzXGfi3XQiozIRa58m3ApeLVDcsDeq6Iv8C5zJ2DHydDyc0x6o5dtTRIb23r5/ZRj4I/UwbgrwMk5iHA0bVsXVPBDSWsrVcPDGafr6YbUNQnNWIF8xOqgpeTwxrqGiCJMUjuKyUx01PBzpBxjpnQ++Ryz6Y7MLqKHxBkDiOw5wk9cxO8/IMspSNJJosOtRXFTR74+bj+pvNBa8IJ+5Jf/UfJEEjk+qC+pohCAryRk0ziXcPdxXEv5KGT4zf3LdtHy1YwsaGLnTb62vgbdqqCJaVyHWOoXsDTQBLjxNl9o9CzP6CrfBGK6JV8pA/xfQlw=="),
                Exponent = Convert.FromBase64String("AQAB"),
                P = Convert.FromBase64String("+VsETS2exORYlg2CxaRMzyG60dTfHSuv0CsfmO3PFv8mcYxglGa6bUV5VGtB6Pd1HdtV/iau1WR/hYXQphCP99Pu803NZvFvVi34alTFbh0LMfZ+2iQ9toGzVfO8Qdbj7go4TWoHNzCpG4UCx/9wicVIWJsNzkppSEcXYigADMM="),
                Q = Convert.FromBase64String("1UCJ2WAHasiCdwJtV2Ep0VCK3Z4rVFLWg3q1v5OoOU1CkX5/QAcrr6bX6zOdHR1bDCPsH1n1E9cCMvwakgi9M4Ch0dYF5CxDKtlx+IGsZJL0gB6HhcEsHat+yXUtOAlS4YB82G1hZqiDw+Q0O8LGyu/gLDPB+bn0HmbkUC2kP50="),
                DP = Convert.FromBase64String("CBqvLxr2eAu73VSfFXFblbfQ7JTwk3AiDK/6HOxNuL+eLj6TvP8BvB9v7BB4WewBAHFqgBIdyI21n09UErGjHDjlIT88F8ZtCe4AjuQmboe/H2aVhN18q/vXKkn7qmAjlE78uXdiuKZ6OIzAJGPm8nNZAJg5gKTmexTka6pFJiU="),
                DQ = Convert.FromBase64String("ND6zhwX3yzmEfROjJh0v2ZAZ9WGiy+3fkCaoEF9kf2VmQa70DgOzuDzv+TeT7mYawEasuqGXYVzztPn+qHhrogqJmpcMqnINopnTSka6rYkzTZAtM5+35yz0yvZiNbBTFdwcuglSK4xte7iU828stNs/2JR1mXDtVeVvWhVUgCE="),
                InverseQ = Convert.FromBase64String("Heo0BHv685rvWreFcI5MXSy3AN0Zs0YbwAYtZZd1K/OzFdYVdOnqw+Dg3wGU9yFD7h4icJFwZUBGOZ0ww/gZX/5ZgJK35/YY/DeV+qfZmywKauUzC6+DPsrDdW1uf1eAety6/huRZTduBFTwIOlPdZ+PY49j6S38DjPFNImn0cU="),
                D = Convert.FromBase64String("IvjMI5cGzxkQqkDf2cC0aOiHOTWccqCM/GD/odkH1+A+/u4wWdLliYWYB/R731R5d6yE0t7EnP6SRGVcxx/XnxPXI2ayorRgwHeF+ScTxUZFonlKkVK5IOzI2ysQYMb01o1IoOamCTQq12iVDMvV1g+9VFlCoM+4GMjdSv6cxn6ELabuD4nWt8tCskPjECThO+WdrknbUTppb2rRgMvNKfsPuF0H7+g+WisbzVS+UVRvJe3U5O5X5j7Z82Uq6hw2NCwv2YhQZRo/XisFZI7yZe0OU2JkXyNG3NCk8CgsM9yqX8Sk5esXMZdJzjwXtEpbR7FiKZXiz9LhPSmzxz/VsQ==")
            };

            key = new RsaSecurityKey(p);

            // Add the signing credentials so we can access them in the controller that doles out the tokens.
            services.AddInstance(new SigningCredentials(key, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest));

            // Configure the bearer token validation to use the supplied key, and validate the lifetime and signature when a
            // key is supplied.
            services.Configure<OAuthBearerAuthenticationOptions>(bearer =>
            {
                // Basic settings - signing key to validate with, audience and issuer.
                bearer.TokenValidationParameters.IssuerSigningKey = key;
                bearer.TokenValidationParameters.ValidAudience = TokenAudience;
                bearer.TokenValidationParameters.ValidIssuer = TokenIssuer;

                // When receiving a token, check that we've signed it.
                bearer.TokenValidationParameters.ValidateSignature = true;

                // When receiving a token, check that it is still valid.
                bearer.TokenValidationParameters.ValidateLifetime = true;

                // This defines the maximum allowable clock skew - i.e. provides a tolerance on the token expiry time
                // when validating the lifetime. As we're creating the tokens locally and validating them on the same
                // machines which should have synchronised time, this can be set to zero. Where external tokens are
                // used, some leeway here could be useful.
                bearer.TokenValidationParameters.ClockSkew = TimeSpan.FromMinutes(0);
            });

            // Enable the use of an [Authorize("Bearer")] attribute on methods and classes to protect.
            services.ConfigureAuthorization(auth =>
            {
                auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
                    .AddAuthenticationSchemes(OAuthBearerAuthenticationDefaults.AuthenticationScheme‌​)
                    .RequireAuthenticatedUser().Build());
            });

            services.AddMvc();
        }
示例#20
0
        /// <summary>
        /// Creates a SAML token for the specified email address and security token.
        /// </summary>
        private SamlSecurityToken CreateSAMLToken(
            string            emailAddress,
            X509SecurityToken issuerToken)
        {            
            // Create list of confirmation strings
            List<string> confirmations = new List<string>();

            // Add holder-of-key string to list of confirmation strings
            confirmations.Add("urn:oasis:names:tc:SAML:1.0:cm:bearer");

            // Create SAML subject statement based on issuer member variable, confirmation string collection 
            // local variable and proof key identifier parameter
            SamlSubject subject = new SamlSubject("urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress", null, emailAddress);

            // Create a list of SAML attributes
            List<SamlAttribute> attributes = new List<SamlAttribute>();
            Claim claim = Claim.CreateNameClaim(emailAddress);            
            attributes.Add(new SamlAttribute(claim));

            // Create list of SAML statements
            List<SamlStatement> statements = new List<SamlStatement>();

            // Add a SAML attribute statement to the list of statements. Attribute statement is based on 
            // subject statement and SAML attributes resulting from claims
            statements.Add(new SamlAttributeStatement(subject, attributes));

            // Create a valid from/until condition
            DateTime validFrom = DateTime.UtcNow;
            DateTime validTo = DateTime.UtcNow.AddHours(12);

            SamlConditions conditions = new SamlConditions(validFrom, validTo);
            
            // Create the SAML assertion
            SamlAssertion assertion = new SamlAssertion(
                "_" + Guid.NewGuid().ToString(),
                issuerToken.Certificate.Subject,
                validFrom, 
                conditions, 
                null,
                statements);

            SecurityKey signingKey = new System.IdentityModel.Tokens.RsaSecurityKey((RSA)issuerToken.Certificate.PrivateKey);

            // Set the signing credentials for the SAML assertion
            assertion.SigningCredentials = new SigningCredentials(
                signingKey, 
                System.IdentityModel.Tokens.SecurityAlgorithms.RsaSha1Signature,
                System.IdentityModel.Tokens.SecurityAlgorithms.Sha1Digest,
                new SecurityKeyIdentifier(issuerToken.CreateKeyIdentifierClause<X509ThumbprintKeyIdentifierClause>()));

            return new SamlSecurityToken(assertion);
        }
        public virtual ClaimsPrincipal AuthenticateSessionToken(HttpRequestMessage request)
        {
            // grab header
            var headerValues = request.Headers.SingleOrDefault(h => h.Key == Configuration.SessionToken.HeaderName).Value;
            if (headerValues != null)
            {
                var header = headerValues.SingleOrDefault();
                if (header != null)
                {
                    var parts = header.Split(' ');
                    if (parts.Length == 2)
                    {
                        // if configured scheme was sent, try to authenticate the session token
                        if (parts[0] == Configuration.SessionToken.Scheme)
                        {
                            var token = new JwtSecurityToken(parts[1]);

                            var validationParameters = new TokenValidationParameters
                            {
                                ValidIssuer = Configuration.SessionToken.IssuerName,
                                AllowedAudience = Configuration.SessionToken.Audience,
                                SigningToken = new BinarySecretSecurityToken(Configuration.SessionToken.SigningKey),
                            };

                            // Create provider to ensure that CrptoHelper.GetIdentityFromConfig has
                            // loaded and avoid race condition see https://connect.microsoft.com/VisualStudio/feedback/details/1477048/system-identitymodel-cryptohelper-getidentityfromconfig-has-race-condition-issue-that-results-in-miseading-error-message
                            RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider();
                            RsaSecurityKey rsaKey = new RsaSecurityKey(rsaProvider);
                            rsaKey.IsSupportedAlgorithm(token.SignatureAlgorithm);

                            var handler = new JwtSecurityTokenHandler();
                            return handler.ValidateToken(token, validationParameters);
                        }
                    }
                }
            }

            return Principal.Anonymous;
        }