Example #1
0
        public IActionResult GetRegisterCertificateOptions()
        {
            var challenge = CryptoRandom.CreateRandomKeyString(30);

            HttpContext.Session.SetString("certificateRegister.challenge", challenge);
            return(Json(new { challenge }));
        }
Example #2
0
        public async Task CallBack(string code)
        {
            if (string.IsNullOrEmpty(code))
            {
                var state = CryptoRandom.CreateRandomKeyString(64);
                var nonce = CryptoRandom.CreateRandomKeyString(64);

                var request = new AuthorizeRequest(Configuration.AuthorizeEndpoint);
                var url     = request.CreateAuthorizeUrl(
                    clientId: "padmate_AuthorizationCode",
                    responseType: "code",
                    scope: "dpcontrolapiscope",
                    redirectUri: Configuration.CodeCallBackUrl,
                    state: state,
                    nonce: nonce);

                Process.Start(url);
            }
            else
            {
                var client = new TokenClient(
                    Configuration.TokenEndpoint,
                    "padmate_AuthorizationCode",
                    "padmate_authorizationcode_secret");

                var response = await client.RequestAuthorizationCodeAsync(code, Configuration.CodeCallBackUrl);

                await this.CallApi(response.AccessToken);
            }
        }
Example #3
0
        /// <summary>
        /// Get an access token from the issuer.
        /// </summary>
        /// <param name="issuer">The issuer.</param>
        /// <param name="scopes">The scopes to request.</param>
        /// <param name="clientId">The tool's client identifier.</param>
        /// <param name="accessTokenUrl">The platform's access token url.</param>
        /// <param name="privateKey">The tool's private key.</param>
        /// <returns>The token response.</returns>
        public static async Task <TokenResponse> GetAccessTokenAsync(string issuer, string[] scopes, string clientId, string accessTokenUrl, string privateKey)
        {
            if (issuer.IsMissing())
            {
                return(new TokenResponse(new ArgumentNullException(nameof(issuer))));
            }

            if (scopes == null)
            {
                return(new TokenResponse(new ArgumentNullException(nameof(scopes))));
            }

            if (clientId.IsMissing())
            {
                return(new TokenResponse(new ArgumentNullException(nameof(clientId))));
            }

            if (accessTokenUrl.IsMissing())
            {
                return(new TokenResponse(new ArgumentNullException(nameof(accessTokenUrl))));
            }

            if (privateKey.IsMissing())
            {
                return(new TokenResponse(new ArgumentNullException(nameof(privateKey))));
            }

            // Use a signed JWT as client credentials.
            var payload = new JwtPayload();

            payload.AddClaim(new Claim(JwtRegisteredClaimNames.Iss, clientId));
            payload.AddClaim(new Claim(JwtRegisteredClaimNames.Sub, clientId));
            payload.AddClaim(new Claim(JwtRegisteredClaimNames.Aud, accessTokenUrl));
            payload.AddClaim(new Claim(JwtRegisteredClaimNames.Iat, EpochTime.GetIntDate(DateTime.UtcNow).ToString()));
            payload.AddClaim(new Claim(JwtRegisteredClaimNames.Nbf,
                                       EpochTime.GetIntDate(DateTime.UtcNow.AddSeconds(-5)).ToString(), ClaimValueTypes.Integer64));
            payload.AddClaim(new Claim(JwtRegisteredClaimNames.Exp,
                                       EpochTime.GetIntDate(DateTime.UtcNow.AddMinutes(5)).ToString(), ClaimValueTypes.Integer64));
            payload.AddClaim(new Claim(JwtRegisteredClaimNames.Jti, CryptoRandom.CreateRandomKeyString(32)));

            var handler     = new JwtSecurityTokenHandler();
            var credentials = PemHelper.SigningCredentialsFromPemString(privateKey);
            var jwt         = handler.WriteToken(new JwtSecurityToken(new JwtHeader(credentials), payload));

            return(await HttpClient.RequestClientCredentialsTokenWithJwtAsync(
                       new JwtClientCredentialsTokenRequest
            {
                Address = accessTokenUrl,
                ClientId = clientId,
                Jwt = jwt,
                Scope = string.Join(" ", scopes)
            }));
        }
        public IActionResult FidoRegister([FromForm] UsernameModel model)
        {
            // generate challenge
            var challenge = CryptoRandom.CreateRandomKeyString(16);

            // store challenge for later use
            tempData.SaveTempData(HttpContext, new Dictionary <string, object> {
                { "challenge", challenge }, { "username", model.Username }
            });

            // send challenge & RP ID to view
            return(View(new RegisterViewModel {
                Challenge = challenge, RelyingPartyId = RelyingPartyId, Username = model.Username
            }));
        }
        public ActionResult LogIn()
        {
            var nonce = CryptoRandom.CreateRandomKeyString(64);

            Session["nonce"] = nonce;
            var request = new AuthorizeRequest(_authorizeEndpoint);
            var url     = request.CreateAuthorizeUrl(
                _clientId,
                "code",
                _scopes,
                $"{_redirectUri}",
                responseMode: "form_post");

            return(Redirect(url));
        }
Example #6
0
        /// <summary>
        /// Implicit
        /// </summary>
        /// <param name="oidc"></param>
        /// <returns></returns>
        public static string AuthorizeUrl(OidcSpec oidc)
        {
            // https://leastprivilege.com/2016/02/02/pkce-support-in-identityserver-and-identitymodel/
            var nonce = CryptoRandom.CreateRandomKeyString(64);


            return(new AuthorizeRequest(AuthorizeEndpoint)
                   .CreateAuthorizeUrl(
                       clientId: oidc.clientId,
                       responseType: oidc.responseType, // OidcConstants.ResponseTypes.IdTokenToken,
                       scope: oidc.scope,               //"openid profile idm roles",
                       redirectUri: oidc.redirectUri,   // $"http://localhost:1391/Home/PostResult",
                       responseMode: oidc.responseMode, //OidcConstants.ResponseModes.FormPost
                       nonce: nonce,
                       acrValues: oidc.acrValues
                       ));
        }
        public IActionResult FidoLogin([FromForm] UsernameModel model)
        {
            // generate challenge
            var challenge = CryptoRandom.CreateRandomKeyString(16);

            var user = Users.First(x => x.Username == model.Username);

            // store challenge & key ID for later use
            tempData.SaveTempData(HttpContext,
                                  new Dictionary <string, object> {
                { "challenge", challenge }, { "keyId", user.CredentialId }, { "returnUrl", model.ReturnUrl }
            });

            return(View(new FidoLoginModel {
                KeyId = user.CredentialId, Challenge = challenge, RelyingPartyId = RelyingPartyId
            }));
        }
        /// <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)
        {
            if (issuer.IsMissing())
            {
                return(new TokenResponse(new ArgumentNullException(nameof(issuer))));
            }

            if (scope.IsMissing())
            {
                return(new TokenResponse(new ArgumentNullException(nameof(scope))));
            }

            var platform = await _context.GetPlatformByIssuerAsync(issuer);

            if (platform == null)
            {
                return(new TokenResponse(new Exception("Cannot find platform registration.")));
            }

            // Use a signed JWT as client credentials.
            var payload = new JwtPayload();

            payload.AddClaim(new Claim(JwtRegisteredClaimNames.Iss, platform.ClientId));
            payload.AddClaim(new Claim(JwtRegisteredClaimNames.Sub, platform.ClientId));
            payload.AddClaim(new Claim(JwtRegisteredClaimNames.Aud, platform.AccessTokenUrl));
            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()));
            payload.AddClaim(new Claim(JwtRegisteredClaimNames.Jti, CryptoRandom.CreateRandomKeyString(32)));

            var handler     = new JwtSecurityTokenHandler();
            var credentials = PemHelper.SigningCredentialsFromPemString(platform.PrivateKey);
            var jwt         = handler.WriteToken(new JwtSecurityToken(new JwtHeader(credentials), payload));

            var httpClient = _httpClientFactory.CreateClient();

            return(await httpClient.RequestClientCredentialsTokenWithJwtAsync(
                       new JwtClientCredentialsTokenRequest
            {
                Address = platform.AccessTokenUrl,
                ClientId = platform.ClientId,
                Jwt = jwt,
                Scope = scope
            }));
        }
Example #9
0
        private async void Authorize_Click(object sender, RoutedEventArgs e)
        {
            var state = CryptoRandom.CreateRandomKeyString(25);

            CodeVerifier = CryptoRandom.CreateRandomKeyString(50);

            var codeVerifierBytes = Encoding.ASCII.GetBytes(CodeVerifier);
            var hashedBytes       = SHA256.Create().ComputeHash(codeVerifierBytes);
            var codeChallenge     = Base64Url.Encode(hashedBytes);



            var url = "http://localhost:5000/connect/authorize" +
                      "?client_id=native_client" +
                      "&scope=wiredbrain_api.rewards" +
                      "&redirect_uri=com.pluralsight.windows:/callback" +
                      "&response_type=code" +
                      $"&state={WebUtility.UrlEncode(state)}" +
                      $"&code_challenge={WebUtility.UrlEncode(codeChallenge)}" +
                      "&code_challenge_method=S256";

            ResultFeed.Text += "\nStarting Authorization";
            ResultFeed.Text += $"\nState = {state}";
            ResultFeed.Text += $"\nCode Verifier = {CodeVerifier}";
            ResultFeed.Text += $"\nCode Challange = {codeChallenge}";

            var result = await new SystemBrowser().InvokeAsync(url);

            ResultFeed.Text += "\n\nAuthorization callback received...";

            if (result.State != state)
            {
                ResultFeed.Text += "\nState not recognised. Cannot trust response.";
                return;
            }

            Code = result.Code;

            ResultFeed.Text += "\nApplication Authorized!";
            ResultFeed.Text += $"\nAuthorization Code: {result.Code}";
            ResultFeed.Text += $"\nState: {result.State}";
        }
Example #10
0
        /// <summary>
        /// Authorize With Code Challenge
        /// allows for hybrid client setup to get in one request: auth_code, id_token and access_token
        /// </summary>
        /// <param name="oidc"></param>
        /// <returns>
        /// Item1: AuthorizeUrl,
        /// Item2: challenge,
        /// Item3: verifier
        /// </returns>
        public static (string, string, string) AuthorizeUrlWithCodeChallenge(OidcSpec oidc)
        {
            // https://leastprivilege.com/2016/02/02/pkce-support-in-identityserver-and-identitymodel/

            var nonce     = CryptoRandom.CreateRandomKeyString(64);
            var verifier  = CryptoRandom.CreateRandomKeyString(64);
            var challenge = verifier.ToSha256();

            return(new AuthorizeRequest(AuthorizeEndpoint)
                   .CreateAuthorizeUrl(
                       clientId: oidc.clientId,
                       responseType: oidc.responseType, // OidcConstants.ResponseTypes.CodeIdTokenToken,
                       scope: oidc.scope,               //"openid profile idm roles",
                       redirectUri: oidc.redirectUri,   // $"http://localhost:1391/Home/PostResult",
                       nonce: nonce,
                       acrValues: oidc.acrValues,
                       responseMode: oidc.responseMode,//OidcConstants.ResponseModes.FormPost
                       codeChallenge: challenge,
                       codeChallengeMethod: OidcConstants.CodeChallengeMethods.Sha256

                       ), challenge, verifier);
        }
Example #11
0
        public IActionResult FidoLoginJSON([FromForm] UsernameModel model)
        {
            // generate challenge
            var challenge = CryptoRandom.CreateRandomKeyString(16);

            // store challenge & key ID for later use
            tempData.SaveTempData(HttpContext,
                                  new Dictionary <string, object> {
                { "challenge", challenge }
            });

            List <User>      _Users     = (List <User>)cache.Get("Users");
            List <PublicKey> publicKeys = new List <PublicKey>();

            foreach (User user in _Users)
            {
                publicKeys.Add(new PublicKey(user.CredentialId));
            }

            return(Ok(new AuthRequest {
                challenge = challenge, rpId = RelyingPartyId, allowCredentials = publicKeys
            }));
        }
Example #12
0
        public async Task <IActionResult> Login()
        {
            var nonce     = CryptoRandom.CreateRandomKeyString(64);
            var verifier  = CryptoRandom.CreateRandomKeyString(64);
            var challenge = verifier.ToSha256();

            var requestUrl = new RequestUrl(AUTHORIZE_ENDPOINT);
            var client     = new HttpClient();

            var url = requestUrl.Create(new
            {
                client_id             = "Plc.LacHdr.Client.Mvc.AuthCode",
                response_type         = "code",
                scope                 = "openid profile Plc.LacHdr.Api",
                redirect_uri          = "https://localhost:5021/auth-callback",
                code_challenge        = challenge,
                code_challenge_method = "S256"
            }
                                        );
            var response = await client.GetAsync(url);

            return(Redirect(url));
        }
Example #13
0
 public RsaKeyPair()
 {
     KeyId = CryptoRandom.CreateRandomKeyString(8);
 }
Example #14
0
 public string Create()
 {
     return(CryptoRandom.CreateRandomKeyString(Constants.SecretLength));
 }