Exemplo n.º 1
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme);
            services.AddAuthorization();
            services.AddMvc();

            var signingKeys    = new MySigningCredentialStore().GetSigningCredentialsAsync().Result;
            var validationKeys = RsaKeyGenerationResult.GetRsaSecurityKey();
            var authOpt        = new AuthenticationOptions {
            };

            services.AddIdentityServer()
            .AddSigningCredential(signingKeys)
            .AddValidationKeys(new AsymmetricSecurityKey[] { validationKeys })
            .AddResourceOwnerValidator <MyUserPasswordValidator>()
            .AddClientStore <MyClient>()
            .AddResourceStore <MyResourceStore>()
            .AddJwtBearerClientAuthentication();

            services.AddDbContext <TodoDbContext>(opt =>
            {
                opt.UseSqlServer(Configuration.GetConnectionString("todoConnection"));
            });
            services.AddCors(cors => {
                cors.AddPolicy("localcors", d => {
                    d.AllowAnyOrigin();
                    d.AllowAnyMethod();
                });
            });
        }
Exemplo n.º 2
0
        public string CreateAuthenticationTokenMs()
        {
            try
            {
                RSACryptoServiceProvider publicAndPrivate    = new RSACryptoServiceProvider();
                RsaKeyGenerationResult   keyGenerationResult = GenerateRsaKeys();

                publicAndPrivate.FromXmlString(keyGenerationResult.PublicAndPrivateKey);
                JwtSecurityToken jwtToken = new JwtSecurityToken
                                                (issuer: "http://localhost"
                                                , audience: "http://localhost"
                                                , claims: new List <System.Security.Claims.Claim>()
                {
                    new System.Security.Claims.Claim(System.Security.Claims.ClaimTypes.Name, "", "http://localhost")
                }
                                                , notBefore: DateTime.Now, expires: DateTime.Now.AddDays(1.0)
                                                //,lifetime: new Lifetime(DateTime.UtcNow, DateTime.UtcNow.AddHours(1))
                                                , signingCredentials: new SigningCredentials(new RsaSecurityKey(publicAndPrivate), SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest));

                JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
                string tokenString = tokenHandler.WriteToken(jwtToken);
                StoreTokenInDb(tokenString);

                return(tokenString);
            }
            catch (Exception ex)
            {
                _logger.ErrorException(ex.Message, ex);
                return(null);
            }
        }
Exemplo n.º 3
0
        private static RsaKeyGenerationResult GenerateRsaKeys()
        {
            RSACryptoServiceProvider myRSA     = new RSACryptoServiceProvider(2048);
            RSAParameters            publicKey = myRSA.ExportParameters(true);
            RsaKeyGenerationResult   result    = new RsaKeyGenerationResult();

            result.PublicAndPrivateKey = myRSA.ToXmlString(true);
            result.PublicKeyOnly       = myRSA.ToXmlString(false);
            return(result);
        }
Exemplo n.º 4
0
        private static RsaKeyGenerationResult GenerateRsaKeys()
        {
            //Uses: using System.Security.Cryptography;

            RSACryptoServiceProvider myRSA = new RSACryptoServiceProvider(keySize);

            //RSAParameters publicKey = myRSA.ExportParameters(true);

            #region RSA Algorithm, XML Structure and Properties

            /* RSA Algorithm and  XML Structure
             * -------------------------------
             * RSA Algorithm
             * To generate a key pair, you start by creating two large prime numbers named p and q.
             * These numbers are multiplied and the result is called n.
             * Because p and q are both prime numbers, the only factors of n are 1, p, q, and n.
             * -------------------------------
             *
             *
             * <RSAKeyValue>
             * <Modulus>…</Modulus>
             * <Exponent>…</Exponent>
             * <P>…</P>
             * <Q>…</Q>
             * <DP>…</DP>
             * <DQ>…</DQ>
             * <InverseQ>…</InverseQ>
             * <D>…</D>
             * </RSAKeyValue>
             *
             * SUMMARY OF FIELDS
             *
             * D	        ==          d, the private exponent	privateExponent
             * DP	        ==          d mod (p - 1)	exponent1
             * DQ	        ==          d mod (q - 1)	exponent2
             * Exponent    ==	        e, the public exponent	publicExponent
             * InverseQ    ==	        (InverseQ)(q) = 1 mod p	coefficient
             * Modulus     ==	        n	modulus
             * P           ==       p	prime1
             * Q	        ==          q	prime2
             *
             *
             * The security of RSA derives from the fact that, given the public key { e, n }, it is computationally infeasible to calculate d, either directly or by factoring n into p and q. Therefore, any part of the key related to d, p, or q must be kept secret. If you call
             *
             * ExportParameters and ask for only the public key information, this is why you will receive only Exponent and Modulus. The other fields are available only if you have access to the private key, and you request it.
             *
             */

            #endregion

            // Note: Requires the RSACryptoServiceProviderExtensions.cs file on project root (ToXMLString(true/flase) does not work in .Net Core so we have an extention method that parses pub/priv without boolean flag)

            var result = new RsaKeyGenerationResult
            {
                PrivateKeyParameters = myRSA.ExportParameters(true),
                PublicKeyParameters  = myRSA.ExportParameters(false),

                PublicKeyXmlString            = myRSA.ToXmlRsaString_PublicOnly(),
                PrivateAndPublicKeysXmlString = myRSA.ToXmlRsaString_Full(),

                //PrivateBase64Key = "",
                //PublicBase64Key = ""
            };

            return(result);
        }