public static IAppBuilder UseOpenIDConnect(this IAppBuilder app, OpenIDConnectOptions options)
        {
            // In order to talk to Pivotal SSO tile, we must limit the TLS defaults used by the service
            // point manager, otherwise the SSO tile will reject the TLS level on the connection and remotely
            // close the socket.
            ServicePointManager.SecurityProtocol =
                SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

            return(app.Use(typeof(OpenIDConnectAuthenticationMiddleware), app, options));
        }
Example #2
0
        private static string DetermineRedirectUri(OpenIDConnectOptions options)
        {
            // TODO: determine the right host name and port.
            var uri = "https://" + options.AppHost;

            if (options.AppPort > 0 && options.AppPort != 443)
            {
                uri = uri + ":" + options.AppPort.ToString();
            }

            return(uri + options.CallbackPath);
        }
Example #3
0
        internal static string CalculateFullRedirectUri(OpenIDConnectOptions options)
        {
            var uri = options.AuthDomain + "/" + Constants.EndPointOAuthAuthorize;

            var queryString = WebUtilities.AddQueryString(uri, Constants.ParamsClientID, options.ClientID);

            queryString = WebUtilities.AddQueryString(queryString, Constants.ParamsResponseType, "code");
            queryString = WebUtilities.AddQueryString(queryString, Constants.ParamsScope, Constants.ScopeOpenID);
            queryString = WebUtilities.AddQueryString(queryString, Constants.ParamsRedirectUri, DetermineRedirectUri(options));

            return(queryString);
        }
 public OpenIDConnectAuthenticationMiddleware(OwinMiddleware next, IAppBuilder app, OpenIDConnectOptions options)
     : base(next, app, options)
 {
 }
        internal static async Task <ClaimsIdentity> ExchangeCodeForToken(string code, OpenIDConnectOptions options)
        {
            string redirect_url = "https://" + options.AppHost;

            if (options.AppPort != 0)
            {
                redirect_url = redirect_url + ":" + options.AppPort + options.CallbackPath;
            }
            else
            {
                redirect_url = redirect_url + options.CallbackPath;
            }

            var hostName = options.AuthDomain;
            var pairs    = new[]
            {
                new KeyValuePair <string, string>(Constants.ParamsClientID, options.ClientID),
                new KeyValuePair <string, string>(Constants.ParamsClientSecret, options.ClientSecret),
                new KeyValuePair <string, string>(Constants.ParamsGrantType, Constants.GrantTypeAuthorizationCode),
                new KeyValuePair <string, string>(Constants.ParamsRedirectUri, redirect_url),
                new KeyValuePair <string, string>(Constants.ParamsCode, code)
            };
            var content   = new FormUrlEncodedContent(pairs);
            var targetUrl = hostName + "/" + Constants.EndPointOAuthToken;

            Debug.WriteLine("About to submit request for token to : " + targetUrl);
            foreach (var item in pairs)
            {
                Debug.WriteLine(item.Key + ": " + item.Value);
            }

            HttpClientHelper.ConfigureCertificateValidatation(options.ValidateCertificates, out SecurityProtocolType protocolType, out RemoteCertificateValidationCallback prevValidator);

            using (var client = new HttpClient())
            {
                var byteArray = Encoding.ASCII.GetBytes(options.ClientID + ":" + options.ClientSecret);
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
                try
                {
                    var response = await client.PostAsync(targetUrl, content);

                    if (response.IsSuccessStatusCode)
                    {
                        var tokens = await response.Content.ReadAsJsonAsync <OpenIDTokenResponse>();

                        Debug.WriteLine("Identity token from IDP: " + tokens.IdentityToken);
                        Debug.WriteLine("Access token from IDP: " + tokens.AccessToken);
                        JwtSecurityToken securityToken = new JwtSecurityToken(tokens.IdentityToken);
                        var    claimsId = new ClaimsIdentity(options.SignInAsAuthenticationType);
                        string userName = securityToken.Claims.First(c => c.Type == "user_name").Value;
                        string email    = securityToken.Claims.First(c => c.Type == "email").Value;
                        string userId   = securityToken.Claims.First(c => c.Type == "user_id").Value;
                        foreach (var claim in securityToken.Claims)
                        {
                            Debug.WriteLine(claim.Type + " : " + claim.Value);
                        }

                        claimsId.AddClaims(new List <Claim>
                        {
                            new Claim(ClaimTypes.NameIdentifier, userId),
                            new Claim(ClaimTypes.Name, userName),
                            new Claim(ClaimTypes.Email, email),
                        });

                        var additionalScopes = tokens.Scope.Split(' ').Where(s => s != "openid");
                        foreach (var scope in additionalScopes)
                        {
                            claimsId.AddClaim(new Claim("scope", scope));
                        }

                        claimsId.AddClaim(new Claim(ClaimTypes.Authentication, tokens.AccessToken));

                        return(claimsId);
                    }
                    else
                    {
                        Debug.WriteLine("Failed call to exchange code for token : " + response.StatusCode);
                        Debug.WriteLine(response.ReasonPhrase);
                        string resultJson = await response.Content.ReadAsStringAsync();

                        Debug.WriteLine(resultJson);
                        return(null);
                    }
                }
                finally
                {
                    HttpClientHelper.RestoreCertificateValidation(options.ValidateCertificates, protocolType, prevValidator);
                }
            }
        }
Example #6
0
        internal static async Task <ClaimsIdentity> ExchangeCodeForToken(string code, OpenIDConnectOptions options)
        {
            string redirect_url = "https://" + options.AppHost;

            if (options.AppPort != 0)
            {
                redirect_url = redirect_url + ":" + options.AppPort + options.CallbackPath;
            }
            else
            {
                redirect_url = redirect_url + options.CallbackPath;
            }

            var hostName = options.AuthDomain;
            var pairs    = new[]
            {
                new KeyValuePair <string, string>(Constants.ParamsClientID, options.ClientID),
                new KeyValuePair <string, string>(Constants.ParamsClientSecret, options.ClientSecret),
                new KeyValuePair <string, string>(Constants.ParamsGrantType, Constants.GrantTypeAuthorizationCode),
                new KeyValuePair <string, string>(Constants.ParamsResponseType, Constants.ResponseTypeIDToken),
                new KeyValuePair <string, string>(Constants.ParamsTokenFormat, Constants.TokenFormatOpaque),
                new KeyValuePair <string, string>(Constants.ParamsRedirectUri, redirect_url),
                new KeyValuePair <string, string>(Constants.ParamsCode, code)
            };
            var content   = new FormUrlEncodedContent(pairs);
            var targetUrl = hostName + "/" + Constants.EndPointOAuthToken;

            Debug.WriteLine("About to submit request for token to : " + targetUrl);
            foreach (var item in pairs)
            {
                Debug.WriteLine(item.Key + ": " + item.Value);
            }

            using (var client = new HttpClient())
            {
                var byteArray = Encoding.ASCII.GetBytes(options.ClientID + ":" + options.ClientSecret);
                client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));

                var response = await client.PostAsync(targetUrl, content);

                if (response.IsSuccessStatusCode)
                {
                    string resultJson = await response.Content.ReadAsStringAsync();

                    Debug.WriteLine("Got from token endpoint:" + resultJson);
                    dynamic data     = JObject.Parse(resultJson);
                    string  jwtToken = data.id_token;
                    Debug.WriteLine("Retrieved authorization token from IDP: " + jwtToken);
                    JwtSecurityToken securityToken = new JwtSecurityToken(jwtToken);
                    var    claimsId = new ClaimsIdentity(options.SignInAsAuthenticationType);
                    string userName = securityToken.Claims.First(c => c.Type == "user_name").Value;
                    string email    = securityToken.Claims.First(c => c.Type == "email").Value;
                    string userId   = securityToken.Claims.First(c => c.Type == "user_id").Value;
                    foreach (var claim in securityToken.Claims)
                    {
                        Debug.WriteLine(claim.Type + " : " + claim.Value);

                        // claimsId.AddClaim(claim);
                    }

                    claimsId.AddClaim(new Claim(ClaimTypes.NameIdentifier, userId));
                    claimsId.AddClaim(new Claim(ClaimTypes.Name, userName));
                    claimsId.AddClaim(new Claim(ClaimTypes.Email, email));
                    return(claimsId);
                }
                else
                {
                    Debug.WriteLine("Failed call to exchange code for token : " + response.StatusCode);
                    Debug.WriteLine(response.ReasonPhrase);
                    string resultJson = await response.Content.ReadAsStringAsync();

                    Debug.WriteLine(resultJson);
                    return(null);
                }
            }
        }