public async Task LoginAsync()
        {
            var discoveryResponse = await GetDicoveryDocumentAsync();

            var nonce = ToUrlBase64String(CryptoRandom.CreateRandomKey(64));

            Console.WriteLine($"Nonce: {nonce}");

            var verifier = ToUrlBase64String(CryptoRandom.CreateRandomKey(64));
            await _jsRuntime.InvokeVoidAsync("sessionStorage.setItem", "verfier", verifier);

            var challenge = GetChallenge(Encoding.ASCII.GetBytes(verifier));

            Console.WriteLine($"Challenge: {challenge}");

            var authorizationUri = QueryHelpers.AddQueryString(discoveryResponse.AuthorizeEndpoint, new Dictionary <string, string>
            {
                ["client_id"]             = "spa",
                ["redirect_uri"]          = "http://localhost:5002",
                ["scope"]                 = "openid profile api1",
                ["response_type"]         = "code",
                ["nonce"]                 = nonce,
                ["code_challenge"]        = challenge,
                ["code_challenge_method"] = "S256"
            });

            _navigationManager.NavigateTo(authorizationUri);
        }
 public void OnGet()
 {
     InputModel = new CreateClientModel
     {
         Secret = Convert.ToBase64String(CryptoRandom.CreateRandomKey(16))
     };
 }
        /// <summary>
        /// Get an access token from the issuer.
        /// </summary>
        /// <param name="issuer">The issuer.</param>
        /// <param name="scope">The scope to request.</param>
        /// <returns>The token response.</returns>
        public async Task <TokenResponse> GetAccessTokenAsync(string issuer, string scope)
        {
            // Use a signed JWT as client credentials.
            var payload = new JwtPayload();

            payload.AddClaim(new Claim(JwtRegisteredClaimNames.Iss, _oidcModel.ClientId));
            payload.AddClaim(new Claim(JwtRegisteredClaimNames.Sub, _oidcModel.ClientId));
            payload.AddClaim(new Claim(JwtRegisteredClaimNames.Aud, _oidcModel.Audience));
            payload.AddClaim(new Claim(JwtRegisteredClaimNames.Iat, EpochTime.GetIntDate(DateTime.UtcNow).ToString()));
            payload.AddClaim(new Claim(JwtRegisteredClaimNames.Nbf, EpochTime.GetIntDate(DateTime.UtcNow.AddSeconds(-5)).ToString()));
            payload.AddClaim(new Claim(JwtRegisteredClaimNames.Exp, EpochTime.GetIntDate(DateTime.UtcNow.AddMinutes(5)).ToString()));
            var bytes = CryptoRandom.CreateRandomKey(32);
            var jti   = Base64Url.Encode(bytes);

            payload.AddClaim(new Claim(JwtRegisteredClaimNames.Jti, jti));

            var handler = new JwtSecurityTokenHandler();
            var rsaKey  = _rsaKeyService.GetKey();
            var jwt     = handler.WriteToken(new JwtSecurityToken(new JwtHeader(new SigningCredentials(rsaKey, SecurityAlgorithms.RsaSha512)), payload));

            var httpClient = _httpClientFactory.CreateClient();

            return(await httpClient.RequestClientCredentialsTokenWithJwtAsync(
                       new JwtClientCredentialsTokenRequest
            {
                Address = _oidcModel.AccessTokenUrl,
                ClientId = _oidcModel.ClientId,
                Jwt = jwt,
                Scope = scope
            }));
        }
Exemple #4
0
 public SessionTokenConfiguration()
 {
     DefaultTokenLifetime = TimeSpan.FromHours(10);
     EndpointAddress      = "/token";
     Scheme     = "Session";
     Audience   = new Uri("http://session.tt");
     IssuerName = "session issuer";
     SigningKey = Convert.ToBase64String(CryptoRandom.CreateRandomKey(32));
 }
Exemple #5
0
 public SessionTokenConfiguration()
 {
     DefaultTokenLifetime = TimeSpan.FromHours(10);
     EndpointAddress      = "/token";
     HeaderName           = "Authorization";
     Scheme     = "Session";
     Audience   = "http://session.tt";
     IssuerName = "session issuer";
     SigningKey = CryptoRandom.CreateRandomKey(32);
 }
Exemple #6
0
        public byte[] Get()
        {
            string key = ConfigurationManager.AppSettings["SigningKey"];

            if (!string.IsNullOrWhiteSpace(key))
            {
                return(Convert.FromBase64String(key));
            }

            return(CryptoRandom.CreateRandomKey(32));
        }
        internal static byte[] GetCookieToken(IDictionary <string, object> env)
        {
            var options = env.ResolveDependency <IdentityServerOptions>();

            var ctx        = new OwinContext(env);
            var cookieName = options.AuthenticationOptions.CookieOptions.Prefix + TokenName;
            var cookie     = ctx.Request.Cookies[cookieName];

            if (cookie != null)
            {
                try
                {
                    var protectedCookieBytes = Base64Url.Decode(cookie);
                    var tokenBytes           = options.DataProtector.Unprotect(protectedCookieBytes, CookieEntropy);
                    return(tokenBytes);
                }
                catch (Exception ex)
                {
                    // if there's an exception we fall thru the catch block to reissue a new cookie
                    Logger.WarnFormat("Problem unprotecting cookie; Issuing new cookie. Error message: {0}", ex.Message);
                }
            }

            var bytes = CryptoRandom.CreateRandomKey(16);
            var protectedTokenBytes = options.DataProtector.Protect(bytes, CookieEntropy);
            var token = Base64Url.Encode(protectedTokenBytes);

            var secure = ctx.Request.Scheme == Uri.UriSchemeHttps;
            var path   = ctx.Request.Environment.GetIdentityServerBasePath();

            if (path.EndsWith("/"))
            {
                path = path.Substring(0, path.Length - 1);
            }
            if (String.IsNullOrWhiteSpace(path))
            {
                path = "/";
            }
            ctx.Response.Cookies.Append(cookieName, token, new Microsoft.Owin.CookieOptions
            {
                HttpOnly = true,
                Secure   = secure,
                Path     = path
            });

            return(bytes);
        }
        byte[] GetCookieToken()
        {
            var cookieName = options.AuthenticationOptions.CookieOptions.Prefix + TokenName;
            var cookie     = context.Request.Cookies[cookieName];

            if (cookie != null)
            {
                try
                {
                    var protectedCookieBytes = Base64Url.Decode(cookie);
                    var tokenBytes           = options.DataProtector.Unprotect(protectedCookieBytes, CookieEntropy);
                    return(tokenBytes);
                }
                catch (Exception ex)
                {
                    // if there's an exception we fall thru the catch block to reissue a new cookie
                    Logger.WarnFormat("Problem unprotecting cookie; Issuing new cookie. Error message: {0}", ex.Message);
                }
            }

            var bytes = CryptoRandom.CreateRandomKey(16);
            var protectedTokenBytes = options.DataProtector.Protect(bytes, CookieEntropy);
            var token = Base64Url.Encode(protectedTokenBytes);

            var secure =
                options.AuthenticationOptions.CookieOptions.SecureMode == CookieSecureMode.Always ||
                context.Request.Scheme == Uri.UriSchemeHttps;

            var path = context.Request.Environment.GetIdentityServerBasePath().CleanUrlPath();

            context.Response.Cookies.Append(cookieName, token, new Microsoft.Owin.CookieOptions
            {
                HttpOnly = true,
                Secure   = secure,
                Path     = path,
                SameSite = secure ? SameSiteMode.None : (SameSiteMode?)null
            });

            return(bytes);
        }
Exemple #9
0
 public ActionResult Random()
 {
     return(Content(Convert.ToBase64String(CryptoRandom.CreateRandomKey(32)), "text/plain"));
 }
Exemple #10
0
            public RsaKeyPair()
            {
                var bytes = CryptoRandom.CreateRandomKey(8);

                KeyId = Base64Url.Encode(bytes);
            }
Exemple #11
0
        public ActionResult Index(InitialConfigurationModel model)
        {
            if (ConfigurationRepository.Keys.SigningCertificate != null)
            {
                return(RedirectToAction("index", "home"));
            }

            if (ModelState.IsValid)
            {
                var config = ConfigurationRepository.Global;
                config.SiteName  = model.SiteName;
                config.IssuerUri = model.IssuerUri;

                // create default IdentityServer groups and admin user.
                if (model.CreateDefaultAccounts)
                {
                    var errors = CreateDefaultAccounts(model.UserName, model.Password);

                    if (errors.Count != 0)
                    {
                        errors.ForEach(e => ModelState.AddModelError("", e));
                        model.AvailableCertificates = GetAvailableCertificatesFromStore();
                        return(View(model));
                    }
                }

                // update global config
                ConfigurationRepository.Global = config;

                var keys = ConfigurationRepository.Keys;
                try
                {
                    var cert = X509.LocalMachine.My.SubjectDistinguishedName.Find(model.SigningCertificate, false).First();

                    // make sure we can access the private key
                    var pk = cert.PrivateKey;

                    keys.SigningCertificate = cert;
                }
                catch (CryptographicException)
                {
                    ModelState.AddModelError("", string.Format(Resources.InitialConfigurationController.NoReadAccessPrivateKey, WindowsIdentity.GetCurrent().Name));
                    model.AvailableCertificates = GetAvailableCertificatesFromStore();
                    return(View(model));
                }

                if (string.IsNullOrWhiteSpace(keys.SymmetricSigningKey))
                {
                    keys.SymmetricSigningKey = Convert.ToBase64String(CryptoRandom.CreateRandomKey(32));
                }

                // updates key material config
                ConfigurationRepository.Keys = keys;



                return(RedirectToAction("index", "home"));
            }

            ModelState.AddModelError("", Resources.InitialConfigurationController.ErrorsOcurred);
            model.AvailableCertificates = GetAvailableCertificatesFromStore();
            return(View(model));
        }
Exemple #12
0
 public byte[] GetKey()
 {
     return(CryptoRandom.CreateRandomKey(32));
 }