指定SSO服务器的基础地址,自动配置其他的地址属性。

<p/>
示例:
<pre>

String baseUrl = "https://sso.example.com/v3/oauth2";

SSOConfig config = new SSOConfig().autoConfigure(baseUrl);

</pre>
427046
public SSOConfig autoConfigureUrls(String baseUrl) {
        if(baseUrl.endsWith("/")) {
            baseUrl = baseUrl.substring(0, baseUrl.length() - 1);
        }
        //todo :
        this.setPublicKeyEndpointUrl(baseUrl + "/oauth2/publickey");
        this.setTokenEndpointUrl(baseUrl + "/oauth2/token");
        this.setAuthorizationEndpointUrl(baseUrl + "/oauth2/authorize");
        this.setOauthLogoutEndpoint(baseUrl + "/oauth2/logout");
        this.setTokenInfoEndpointUrl(baseUrl + "/oauth2/tokeninfo");
        return this;
    }
552473
public HttpClientBuilder basicAuth(String username, String password) {
		basicAuthUsername = username;
		basicAuthPassword = password;
		return this;
	}
1075676
private SSLContext buildSSLContext(SecurityRealm realm) {
        if (realm.getAuthentication() == null || realm.getAuthentication().getTruststore() == null) {
            throw new IllegalArgumentException("No truststore configuration in security realm \"" + realm.getName() + "\".");
        }
        if (realm.getIdentities() == null || realm.getIdentities().getSsl() == null
                || realm.getIdentities().getSsl().getKeystore() == null) {
            throw new IllegalArgumentException("No keystore configuration in security realm \"" + realm.getName() + "\".");
        }

        SecurityRealm.Keystore keystore = realm.getIdentities().getSsl().getKeystore();
        SecurityRealm.Truststore truststore = realm.getAuthentication().getTruststore();

        String keystorePassword = keystore.getPassword();
        String keyPassword = keystore.getKeyPassword();

        // we'll reuse PID configuration for OCSP/CRL stuff
        return buildSSLContext(keystore.getPath(), keystore.getProvider(),
                keystorePassword, keyPassword,
                keystore.getAlias(),
                truststore.getPath(), truststore.getProvider(),
                truststore.getPassword(),
                configuration.isValidateCerts(), configuration.getCrlPath(),
                null, // "SHA1PRNG", "NativePRNGNonBlocking", ...
                configuration.isValidatePeerCerts(), configuration.isEnableCRLDP(), configuration.isEnableOCSP(),
                configuration.getOcspResponderURL(),
                configuration.getSslKeystoreProvider(),
                configuration.getSslTrustStoreProvider(),
                configuration.getSslProvider());
    }
1189135
@Nullable
	private static SSLContext createInternalSSLContext(Configuration config) throws Exception {
		checkNotNull(config, "config");

		if (!isInternalSSLEnabled(config)) {
			return null;
		}
		String keystoreFilePath = getAndCheckOption(
				config, SecurityOptions.SSL_INTERNAL_KEYSTORE, SecurityOptions.SSL_KEYSTORE);

		String keystorePassword = getAndCheckOption(
				config, SecurityOptions.SSL_INTERNAL_KEYSTORE_PASSWORD, SecurityOptions.SSL_KEYSTORE_PASSWORD);

		String certPassword = getAndCheckOption(
				config, SecurityOptions.SSL_INTERNAL_KEY_PASSWORD, SecurityOptions.SSL_KEY_PASSWORD);

		String trustStoreFilePath = getAndCheckOption(
				config, SecurityOptions.SSL_INTERNAL_TRUSTSTORE, SecurityOptions.SSL_TRUSTSTORE);

		String trustStorePassword = getAndCheckOption(
				config, SecurityOptions.SSL_INTERNAL_TRUSTSTORE_PASSWORD, SecurityOptions.SSL_TRUSTSTORE_PASSWORD);

		String sslProtocolVersion = config.getString(SecurityOptions.SSL_PROTOCOL);
		int sessionCacheSize = config.getInteger(SecurityOptions.SSL_INTERNAL_SESSION_CACHE_SIZE);
		int sessionTimeoutMs = config.getInteger(SecurityOptions.SSL_INTERNAL_SESSION_TIMEOUT);

		KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
		try (InputStream keyStoreFile = Files.newInputStream(new File(keystoreFilePath).toPath())) {
			keyStore.load(keyStoreFile, keystorePassword.toCharArray());
		}

		KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
		try (InputStream trustStoreFile = Files.newInputStream(new File(trustStoreFilePath).toPath())) {
			trustStore.load(trustStoreFile, trustStorePassword.toCharArray());
		}

		KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
		kmf.init(keyStore, certPassword.toCharArray());

		TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
		tmf.init(trustStore);

		SSLContext sslContext = SSLContext.getInstance(sslProtocolVersion);
		sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
		if (sessionCacheSize >= 0) {
			sslContext.getClientSessionContext().setSessionCacheSize(sessionCacheSize);
		}
		if (sessionTimeoutMs >= 0) {
			sslContext.getClientSessionContext().setSessionTimeout(sessionTimeoutMs / 1000);
		}

		return sslContext;
	}
162245
@Override
	protected void configure(HttpSecurity http) throws Exception {
		ConfigObject protectedResources = Config.getConfig().getObject("security.protected");
		ConfigValue apiSec = Config.getConfig().getValue("security.api_security");
		boolean enableRestFilter = apiSec != null && Boolean.TRUE.equals(apiSec.unwrapped());
		String signinPath = Config.getConfigParam("security.signin", "/signin");
		String signoutPath = Config.getConfigParam("security.signout", "/signout");
		String accessDeniedPath = Config.getConfigParam("security.access_denied", "/403");
		String signoutSuccessPath = Config.getConfigParam("security.signout_success", signinPath);

		// If API security is disabled don't add the API endpoint to the list of protected resources
		if (enableRestFilter) {
			http.authorizeRequests().requestMatchers(RestRequestMatcher.INSTANCE);
		}

		parseProtectedResources(http, protectedResources);

		if (Config.getConfigBoolean("security.csrf_protection", true)) {
			http.csrf().requireCsrfProtectionMatcher(CsrfProtectionRequestMatcher.INSTANCE).
					csrfTokenRepository(csrfTokenRepository);
		} else {
			http.csrf().disable();
		}

		http.sessionManagement().enableSessionUrlRewriting(false);
		http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER);
		http.sessionManagement().sessionAuthenticationStrategy(new NullAuthenticatedSessionStrategy());
		http.exceptionHandling().authenticationEntryPoint(new SimpleAuthenticationEntryPoint(signinPath));
		http.exceptionHandling().accessDeniedHandler(new SimpleAccessDeniedHandler(accessDeniedPath));
		http.requestCache().requestCache(new SimpleRequestCache());
		http.logout().logoutUrl(signoutPath).logoutSuccessUrl(signoutSuccessPath);
		http.rememberMe().rememberMeServices(rememberMeServices);

		registerAuthFilters(http);

		if (enableRestFilter) {
			if (jwtFilter != null) {
				jwtFilter.setAuthenticationManager(authenticationManager());
				http.addFilterBefore(jwtFilter, RememberMeAuthenticationFilter.class);
			}
			RestAuthFilter restFilter = new RestAuthFilter();
			http.addFilterAfter(restFilter, JWTRestfulAuthFilter.class);
		}
	}
1146054
public String getOauthPageUrl(String redirectUrl, OauthScope scope, String state) {
        BeanUtil.requireNonNull(redirectUrl, "redirectUrl is null");
        BeanUtil.requireNonNull(scope, "scope is null");
        String userState = StrUtil.isBlank(state) ? "STATE" : state;
        String url = null;
        try {
            url = URLEncoder.encode(redirectUrl, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            LOG.error("异常", e);
        }
        StringBuilder stringBuilder = new StringBuilder("https://open.weixin.qq.com/connect/oauth2/authorize?");
        stringBuilder.append("appid=").append(this.config.getAppid())
                .append("&redirect_uri=").append(url)
                .append("&response_type=code&scope=").append(scope.toString())
                .append("&state=")
                .append(userState)
                .append("#wechat_redirect");
        return stringBuilder.toString();
    }
1198314
public static ContentModeratorClient authenticate(AzureRegionBaseUrl baseUrl, String subscriptionKey) {
        return authenticate("https://{baseUrl}/", subscriptionKey)
                .withBaseUrl(baseUrl);
    }
64384
public boolean doesSSLConfigExist(String sslAliasName) {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            Tr.entry(tc, "doesSSLConfigExist", new Object[] { sslAliasName });

        if (sslAliasName == null)
            throw new IllegalArgumentException("sslAliasName is null.");

        boolean exists = (null != SSLConfigManager.getInstance().getProperties(sslAliasName));

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            Tr.exit(tc, "doesSSLConfigExist -> " + exists);
        return exists;
    }
352393
function baseStringUri(uri) {
    var parsed = url.parse(uri);

    //  The port MUST be included if it is not the default port for the
    //  scheme, and MUST be excluded if it is the default.
    if (parsed.protocol === 'https:/') {
        parsed.host = parsed.host.replace(/:443$/, '');
    } else if (parsed.protocol === 'http:/') {
        parsed.host = parsed.host.replace(/:80$/, '');
    }

    return url.format({
        protocol: parsed.protocol,
        host: parsed.host,
        auth: parsed.auth,
        pathname: parsed.pathname
    });
}
834980
public function getSessionCheckUrl($user_id, $sso_session)  {
        $host = Maestrano::with($this->_preset)->param('sso.idp');
        $api_base = Maestrano::with($this->_preset)->param('api.base');
        $endpoint = 'auth/saml';

        return "${host}${api_base}${endpoint}/${user_id}?session=${sso_session}";
    }
245860
protected String constructLoginURL(HttpServletRequest request, boolean isXMLRequest) {
        String delimiter = "?";
        if (authenticationProviderUrl.contains("?")) {
            delimiter = "&";
        }
        StringBuilder loginURL = new StringBuilder();
        if (isXMLRequest) {
            String atlasApplicationURL = "";
            String referalURL = request.getHeader("referer");

            if (referalURL == null) {
                atlasApplicationURL = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
            } else {
                atlasApplicationURL = referalURL;
            }

            loginURL.append(authenticationProviderUrl).append(delimiter).append(originalUrlQueryParam).append("=").append(atlasApplicationURL);
        } else {
            loginURL.append(authenticationProviderUrl).append(delimiter).append(originalUrlQueryParam).append("=").append(request.getRequestURL().append(getOriginalQueryString(request)));
        }
        return loginURL.toString();
    }
1261535
private String getLoginFormURL(HttpServletRequest req, HttpServletResponse res) throws IOException {

        CmsHttpAuthenticationSettings httpAuthenticationSettings = OpenCms.getSystemInfo().getHttpAuthenticationSettings();
        String loginFormURL = null;

        // this will create an admin user with the "right" site root already set
        CmsObject adminCms;
        try {
            adminCms = initCmsObject(req, res, OpenCms.getDefaultUsers().getUserAdmin(), null, null);
        } catch (CmsException e) {
            // this should never happen, if it does we can't continue
            throw new IOException(
                Messages.get().getBundle().key(
                    Messages.ERR_INVALID_INIT_USER_2,
                    OpenCms.getDefaultUsers().getUserAdmin(),

                    null),
                e);
        }
        // get the requested resource
        String path = adminCms.getRequestContext().getUri();
        CmsProperty propertyLoginForm = null;
        try {
            propertyLoginForm = adminCms.readPropertyObject(path, CmsPropertyDefinition.PROPERTY_LOGIN_FORM, true);
        } catch (Throwable t) {
            if (t instanceof CmsVfsResourceNotFoundException) {
                // if we can't read the property from the path, try to use the resource init handlers to find the
                // resource to read it from
                CmsResource alternativeResource = null;
                try {
                    // use null as the response to avoid side effects like redirects, etc.
                    alternativeResource = initResource(adminCms, path, req, null);
                    if (alternativeResource != null) {
                        propertyLoginForm = adminCms.readPropertyObject(
                            adminCms.getSitePath(alternativeResource),
                            CmsPropertyDefinition.PROPERTY_LOGIN_FORM,
                            true);
                    }
                } catch (Exception e) {
                    LOG.error(e.getLocalizedMessage(), e);
                }
            }

            if (propertyLoginForm == null) {
                if (LOG.isWarnEnabled()) {
                    LOG.warn(
                        Messages.get().getBundle().key(
                            Messages.LOG_ERROR_READING_AUTH_PROP_2,
                            CmsPropertyDefinition.PROPERTY_LOGIN_FORM,
                            path),
                        t);
                }

            }
        }

        String params = null;
        if ((propertyLoginForm != null)
            && (propertyLoginForm != CmsProperty.getNullProperty())
            && CmsStringUtil.isNotEmpty(propertyLoginForm.getValue())) {
            // login form property value was found
            // build a redirect URL using the value of the property
            // "__loginform" is a dummy request parameter that could be used in a JSP template to trigger
            // if the template should display a login formular or not
            loginFormURL = propertyLoginForm.getValue();
            params = "__loginform=true";
        } else if (!httpAuthenticationSettings.useBrowserBasedHttpAuthentication()
            && CmsStringUtil.isNotEmpty(httpAuthenticationSettings.getFormBasedHttpAuthenticationUri())) {
            // login form property value not set, but form login set in configuration
            // build a redirect URL to the default login form URI configured in opencms.properties
            loginFormURL = httpAuthenticationSettings.getFormBasedHttpAuthenticationUri();
        }

        String callbackURL = CmsRequestUtil.encodeParamsWithUri(path, req);
        if (loginFormURL != null) {
            if (!loginFormURL.startsWith("http")) {
                loginFormURL = m_linkManager.substituteLink(adminCms, loginFormURL, null, true);
            } else {
                callbackURL = m_linkManager.getServerLink(adminCms, path);
                callbackURL = CmsRequestUtil.encodeParamsWithUri(callbackURL, req);
            }
        }

        return m_authorizationHandler.getLoginFormURL(loginFormURL, params, callbackURL);
    }
720701
private String buildAuthUrl(String baseAuthUrl, GrantType grantType, OAuth2Parameters parameters) {
		StringBuilder authUrl = new StringBuilder(baseAuthUrl);
		if (grantType == GrantType.AUTHORIZATION_CODE) {
			authUrl.append('&').append("response_type").append('=').append("code");
		} else if (grantType == GrantType.IMPLICIT_GRANT) {
			authUrl.append('&').append("response_type").append('=').append("token");
		}
		for (Iterator<Entry<String, List<String>>> additionalParams = parameters.entrySet().iterator(); additionalParams.hasNext();) {
			Entry<String, List<String>> param = additionalParams.next();
			String name = formEncode(param.getKey());
			for (Iterator<String> values = param.getValue().iterator(); values.hasNext();) {
				authUrl.append('&').append(name);
				String value = values.next();
				if (StringUtils.hasLength(value)) {
					authUrl.append('=').append(formEncode(value));
				}
			}
		}
		return authUrl.toString();		
	}
960791
public HashMap<String, String> ssoTokenGenerator() throws Exception {
        String protocol = "https://";
        HashMap<String, String> cookieToken = new HashMap<>();

        SSLContext sslContext = SSLContext.getInstance("SSL");
        // set up a TrustManager that trusts everything
        sslContext.init(null, ALL_TRUSTING_TRUST_MANAGER, new SecureRandom());
        HttpClientContext context = HttpClientContext.create();
        HttpGet httpGet = new HttpGet(protocol + ssoHost + "/login");
        HttpClient client = HttpClientBuilder.create()
                .setSslcontext(sslContext)
                .setRedirectStrategy(new LaxRedirectStrategy())
                .setDefaultRequestConfig(RequestConfig.custom()
                        .setCookieSpec(CookieSpecs.STANDARD).setCircularRedirectsAllowed(true).build()).build();
        try {
            HttpResponse firstResponse = client.execute(httpGet, context);

            logger.debug(firstResponse.getStatusLine().toString());
            Document doc = Jsoup.parse(getStringFromIS(firstResponse.getEntity().getContent()));
            Elements code = doc.select("[name=lt]");
            String loginCode = code.attr("value");
            String executionCode = doc.select("[name=execution]").attr("value");
            for (Header oneHeader : firstResponse.getAllHeaders()) {
                logger.debug(oneHeader.getName() + ":" + oneHeader.getValue());
            }

            URI redirect = context.getRedirectLocations().get(context.getRedirectLocations().size() - 1);

            List<NameValuePair> params = new ArrayList<>();
            params.add(new BasicNameValuePair("_eventId", "submit"));
            params.add(new BasicNameValuePair("submit", "LOGIN"));
            params.add(new BasicNameValuePair("username", userName));
            params.add(new BasicNameValuePair("password", passWord));

            if (tenant != null) {
                params.add(new BasicNameValuePair("tenant", tenant));
            }

            params.add(new BasicNameValuePair("lt", loginCode));
            params.add(new BasicNameValuePair("execution", executionCode));
            HttpPost httpPost = new HttpPost(redirect);
            httpPost.setEntity(new UrlEncodedFormEntity(params));
            HttpResponse secondResponse = client.execute(httpPost, context);

            for (Header oneHeader : secondResponse.getAllHeaders()) {
                logger.debug(oneHeader.getName() + ":" + oneHeader.getValue());
            }

            HttpGet managementGet = new HttpGet(protocol + ssoHost + managementHost);
            client.execute(managementGet, context);

            for (Cookie oneCookie : context.getCookieStore().getCookies()) {
                logger.debug(oneCookie.getName() + ":" + oneCookie.getValue());
                cookieToken.put(oneCookie.getName(), oneCookie.getValue());
            }

        } catch (Exception e) {
            e.getStackTrace();
        }
        return cookieToken;
    }
1329826
private void configureSecurity(ServletContextHandler context, String realmName, String authMethod,
								   String formLoginPage, String formErrorPage) {
		final SecurityHandler securityHandler = context.getSecurityHandler();

		Authenticator authenticator = null;
		if (authMethod == null) {
			LOG.warn("UNKNOWN AUTH METHOD: " + authMethod);
		} else {
			switch (authMethod) {
				case Constraint.__FORM_AUTH:
					authenticator = new FormAuthenticator();
					securityHandler.setInitParameter(FormAuthenticator.__FORM_LOGIN_PAGE, formLoginPage);
					securityHandler.setInitParameter(FormAuthenticator.__FORM_ERROR_PAGE, formErrorPage);
					break;
				case Constraint.__BASIC_AUTH:
					authenticator = new BasicAuthenticator();
					break;
				case Constraint.__DIGEST_AUTH:
					authenticator = new DigestAuthenticator();
					break;
				case Constraint.__CERT_AUTH:
					authenticator = new ClientCertAuthenticator();
					break;
				case Constraint.__CERT_AUTH2:
					authenticator = new ClientCertAuthenticator();
					break;
				case Constraint.__SPNEGO_AUTH:
					authenticator = new SpnegoAuthenticator();
					break;
				default:
					authenticator = getAuthenticator(authMethod);
					break;
			}
		}

		securityHandler.setAuthenticator(authenticator);

		securityHandler.setRealmName(realmName);

	}
850827
private String getPathInfoforSecureloginlogout(String currentURI, String securityString) {
        String pathInfo = null;
        int lastIndex_Security = currentURI.lastIndexOf(securityString);
        String restURI = currentURI.substring(lastIndex_Security + securityString.length());

        if (restURI.equals(""))
            pathInfo = null;
        else
            pathInfo = restURI;
        return pathInfo;
    }
802619
@Override
    public Response getNonOAuth(String path, Map<String, String> parameters) {
        InputStream in = null;
        try {
            URL url = UrlUtilities.buildUrl(getScheme(), getHost(), getPort(), path, parameters);
            if (Flickr.debugRequest) {
                logger.debug("GET: " + url);
            }
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            if (proxyAuth) {
                conn.setRequestProperty("Proxy-Authorization", "Basic " + getProxyCredentials());
            }
            setTimeouts(conn);
            conn.connect();

            if (Flickr.debugStream) {
                in = new DebugInputStream(conn.getInputStream(), System.out);
            } else {
                in = conn.getInputStream();
            }

            Response response;
            DocumentBuilder builder = getDocumentBuilder();
            Document document = builder.parse(in);
            response = (Response) responseClass.newInstance();
            response.parse(document);

            return response;
        } catch (IllegalAccessException | SAXException | IOException | InstantiationException | ParserConfigurationException e) {
            throw new FlickrRuntimeException(e);
        } finally {
            IOUtilities.close(in);
        }
    }