org.apache.catalina.authenticator.Constants Java Examples

The following examples show how to use org.apache.catalina.authenticator.Constants. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: FederationAuthenticator.java    From cxf-fediz with Apache License 2.0 6 votes vote down vote up
protected void saveRequest(Request request, RequestState requestState) throws IOException {
    String contextId = requestState.getState();
    String uri = request.getDecodedRequestURI();
    Session session = request.getSessionInternal(true);
    if (session != null) {
        LOG.debug("Save request in session '{}'", session.getIdInternal());
    }
    if (session != null && uri != null) {
        SavedRequest saved;
        synchronized (session) {
            super.saveRequest(request, session);
            saved = (SavedRequest) session.getNote(Constants.FORM_REQUEST_NOTE);
        }
        session.setNote(SESSION_SAVED_REQUEST_PREFIX + uri, saved);
        StringBuilder sb = new StringBuilder(saved.getRequestURI());
        if (saved.getQueryString() != null) {
            sb.append('?');
            sb.append(saved.getQueryString());
        }
        session.setNote(SESSION_SAVED_URI_PREFIX + contextId, sb.toString());
        //we set Request State as session attribute for later retrieval in SigninHandler
        request.getSession().setAttribute(
            FederationConstants.SESSION_SAVED_REQUEST_STATE_PREFIX + requestState.getState(), requestState);
    }
}
 
Example #2
Source File: Tomcat7Valve.java    From flex-blazeds with Apache License 2.0 6 votes vote down vote up
public boolean logout(HttpServletRequest servletRequest)
{
    if (servletRequestMatches(servletRequest))
    {
        Session session = getSession(request, false);
        if (session != null)
        {
            session.setPrincipal(null);
            session.setAuthType(null);
            session.removeNote(Constants.SESS_USERNAME_NOTE);
            session.removeNote(Constants.SESS_PASSWORD_NOTE);
        }
        return true;
    }
    return false;
}
 
Example #3
Source File: TomcatValve4150.java    From flex-blazeds with Apache License 2.0 6 votes vote down vote up
public boolean logout(HttpServletRequest request)
{
    if (this.request != null && this.request.getRequest() == request)
    {
        Session session = getSession(this.request, false);
        if (session != null)
        {
            session.setPrincipal(null);
            session.setAuthType(null);
            session.removeNote(Constants.SESS_USERNAME_NOTE);
            session.removeNote(Constants.SESS_PASSWORD_NOTE);
        }
        return true;
    }
    return false;
}
 
Example #4
Source File: TomcatValve.java    From flex-blazeds with Apache License 2.0 6 votes vote down vote up
public boolean logout(HttpServletRequest servletRequest)
{
    if (servletRequestMatches(servletRequest))
    {
        Session session = getSession(request, false);
        if (session != null)
        {
            session.setPrincipal(null);
            session.setAuthType(null);
            session.removeNote(Constants.SESS_USERNAME_NOTE);
            session.removeNote(Constants.SESS_PASSWORD_NOTE);
        }
        return true;
    }
    return false;
}
 
Example #5
Source File: BaseOpenIDConnectAuthenticator.java    From tomcat-oidcauth with Apache License 2.0 6 votes vote down vote up
/**
 * Redirect to the configured landing page, if any.
 *
 * @param request The request.
 * @param response The response.
 *
 * @return {@code true} if successfully redirected, {@code false} if no
 * landing page is configured.
 *
 * @throws IOException If an I/O error happens communicating with the
 * client.
 */
protected boolean redirectToLandingPage(final Request request,
		final HttpServletResponse response)
	throws IOException {

	// do we have landing page configured?
	if (this.landingPage == null)
		return false;

	// construct landing page URI
	final String uri = request.getContextPath() + this.landingPage;

	// make it think the user originally requested the landing page
	final SavedRequest savedReq = new SavedRequest();
	savedReq.setMethod("GET");
	savedReq.setRequestURI(uri);
	savedReq.setDecodedRequestURI(uri);
	request.getSessionInternal(true).setNote(
			Constants.FORM_REQUEST_NOTE, savedReq);

	// send the redirect
	response.sendRedirect(response.encodeRedirectURL(uri));

	// done, success
	return true;
}
 
Example #6
Source File: FederationAuthenticator.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
protected boolean restoreRequest(Request request) throws IOException {
    Session session = request.getSessionInternal(false);
    String uri = request.getDecodedRequestURI();
    if (session != null && uri != null) {
        SavedRequest saved = (SavedRequest)session.getNote(SESSION_SAVED_REQUEST_PREFIX + uri);
        if (saved != null) {
            session.removeNote(SESSION_SAVED_REQUEST_PREFIX + uri); // cleanup session
            synchronized (session) {
                session.setNote(Constants.FORM_REQUEST_NOTE, saved);
                return super.restoreRequest(request, session);
            }
        }
    }
    return false;
}
 
Example #7
Source File: FederationAuthenticator.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean matchRequest(Request request) {
    Session session = request.getSessionInternal(false);
    String uri = request.getDecodedRequestURI();
    if (session != null && uri != null) {
        SavedRequest saved = (SavedRequest) session.getNote(SESSION_SAVED_REQUEST_PREFIX + uri);
        if (saved != null) {
            synchronized (session) {
                session.setNote(Constants.FORM_REQUEST_NOTE, saved);
                return super.matchRequest(request);
            }
        }
    }
    return false;
}
 
Example #8
Source File: Tomcat7Valve.java    From flex-blazeds with Apache License 2.0 5 votes vote down vote up
public Principal login(String username, String password, HttpServletRequest servletRequest)
{
    Realm realm = valve.getContainer().getRealm();
    if (realm == null)
        return null;

    Principal principal = realm.authenticate(username, password);
    if (principal == null)
        return null;

    if (servletRequestMatches(servletRequest))
    {
        request.setAuthType(AUTH_TYPE);
        request.setUserPrincipal(principal);

        Session session = getSession(request, true);

        // Cache the authentication information in our session.
        if (session != null) 
        {
            session.setAuthType(AUTH_TYPE);
            session.setPrincipal(principal);

            if (username != null)
                session.setNote(Constants.SESS_USERNAME_NOTE, username);
            else
                session.removeNote(Constants.SESS_USERNAME_NOTE);

            if (password != null)
                session.setNote(Constants.SESS_PASSWORD_NOTE, password);
            else
                session.removeNote(Constants.SESS_PASSWORD_NOTE);
        }
    }

    return principal;
}
 
Example #9
Source File: TomcatValve4150.java    From flex-blazeds with Apache License 2.0 5 votes vote down vote up
public Principal login(String username, String password, HttpServletRequest servletRequest)
{
    Realm realm = container.getRealm();
    if (realm == null)
        return null;
    Principal principal = realm.authenticate(username, password);

    if (principal != null) 
    {
        if (this.request != null && this.request.getRequest() == servletRequest)
        {
            request.setAuthType("flexmessaging"); //was "flashgateway"
            request.setUserPrincipal(principal);

            Session session = getSession(request, true);

            // Cache the authentication information in our session, if any
            if (session != null) 
            {
                session.setAuthType("flexmessaging"); //was "flashgateway"
                session.setPrincipal(principal);
                if (username != null)
                    session.setNote(Constants.SESS_USERNAME_NOTE, username);
                else
                    session.removeNote(Constants.SESS_USERNAME_NOTE);
                if (password != null)
                    session.setNote(Constants.SESS_PASSWORD_NOTE, password);
                else
                    session.removeNote(Constants.SESS_PASSWORD_NOTE);
            }
        }
    }

    return principal;
}
 
Example #10
Source File: TomcatValve.java    From flex-blazeds with Apache License 2.0 5 votes vote down vote up
public Principal login(String username, String password, HttpServletRequest servletRequest)
{
    Realm realm = container.getRealm();
    if (realm == null)
        return null;

    Principal principal = realm.authenticate(username, password);
    if (principal == null)
        return null;

    if (servletRequestMatches(servletRequest))
    {
        request.setAuthType(AUTH_TYPE);
        request.setUserPrincipal(principal);

        Session session = getSession(request, true);

        // Cache the authentication information in our session.
        if (session != null) 
        {
            session.setAuthType(AUTH_TYPE);
            session.setPrincipal(principal);

            if (username != null)
                session.setNote(Constants.SESS_USERNAME_NOTE, username);
            else
                session.removeNote(Constants.SESS_USERNAME_NOTE);

            if (password != null)
                session.setNote(Constants.SESS_PASSWORD_NOTE, password);
            else
                session.removeNote(Constants.SESS_PASSWORD_NOTE);
        }
    }

    return principal;
}
 
Example #11
Source File: BaseOpenIDConnectAuthenticator.java    From tomcat-oidcauth with Apache License 2.0 5 votes vote down vote up
@Override
public void logout(final Request request) {

	final Session session = request.getSessionInternal(false);
	if (session != null) {
		session.removeNote(SESS_STATE_NOTE);
		session.removeNote(Constants.SESS_USERNAME_NOTE);
		session.removeNote(SESS_OIDC_AUTH_NOTE);
		session.removeNote(Constants.FORM_REQUEST_NOTE);
		session.getSession().removeAttribute(AUTHORIZATION_ATT);
	}

	super.logout(request);
}
 
Example #12
Source File: BaseOpenIDConnectAuthenticator.java    From tomcat-oidcauth with Apache License 2.0 5 votes vote down vote up
/**
 * Process original request resubmit after successful authentication.
 *
 * @param request The request.
 * @param response The response.
 *
 * @return {@code true} if success, {@code false} if failure, in which case
 * an HTTP 400 response is sent back by this method.
 *
 * @throws IOException If an I/O error happens communicating with the
 * client.
 */
protected boolean processResubmit(final Request request,
		final HttpServletResponse response)
	throws IOException {

	// get session
	final Session session = request.getSessionInternal(true);

	final boolean debug = this.log.isDebugEnabled();
	if (debug)
		this.log.debug("restore request from session "
				+ session.getIdInternal());

	// if principal is cached, remove authentication info from the session
	if (this.cache) {
		session.removeNote(Constants.SESS_USERNAME_NOTE);
		session.removeNote(Constants.SESS_PASSWORD_NOTE);
		session.removeNote(SESS_OIDC_AUTH_NOTE);
	}

	// try to restore original request
	if (!this.restoreRequest(request, session)) {
		if (debug)
			this.log.debug("restore of original request failed");
		response.sendError(HttpServletResponse.SC_BAD_REQUEST);
		return false;
	}

	// all good, no further authentication action is required
	if (debug)
		this.log.debug("proceed to restored request");
	return true;
}
 
Example #13
Source File: TestCookieFilter.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@Test
public void test09() {
    // Simple SSO case
    String id = "0123456789";
    String cookie = Constants.SINGLE_SIGN_ON_COOKIE + "=" + id;
    Assert.assertEquals(cookie, CookieFilter.filter(cookie, id));
}
 
Example #14
Source File: TestCookieFilter.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
@Test
public void test09() {
    // Simple SSO case
    String id = "0123456789";
    String cookie = Constants.SINGLE_SIGN_ON_COOKIE + "=" + id;
    Assert.assertEquals(cookie, CookieFilter.filter(cookie, id));
}
 
Example #15
Source File: TestCookieFilter.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Test
public void test09() {
    // Simple SSO case
    String id = "0123456789";
    String cookie = Constants.SINGLE_SIGN_ON_COOKIE + "=" + id;
    Assert.assertEquals(cookie, CookieFilter.filter(cookie, id));
}
 
Example #16
Source File: BaseOpenIDConnectAuthenticator.java    From tomcat-oidcauth with Apache License 2.0 4 votes vote down vote up
/**
 * Call the OP's token endpoint and exchange the authorization code.
 *
 * @param opDesc OP descriptor.
 * @param authCode The authorization code received from the authentication
 * endpoint.
 * @param request The request.
 *
 * @return The token endpoint response.
 *
 * @throws IOException If an I/O error happens communicating with the
 * endpoint.
 */
protected TokenEndpointResponse callTokenEndpoint(final OPDescriptor opDesc,
		final String authCode, final Request request)
	throws IOException {

	final boolean debug = this.log.isDebugEnabled();

	// get the OP configuration
	final OPConfiguration opConfig =
		this.ops.getOPConfiguration(opDesc.getIssuer());
	final URL tokenEndpointURL = new URL(opConfig.getTokenEndpoint());

	// build POST body
	final StringBuilder buf = new StringBuilder(256);
	buf.append("grant_type=authorization_code");
	buf.append("&code=").append(URLEncoder.encode(authCode, UTF8.name()));
	buf.append("&redirect_uri=").append(URLEncoder.encode(
			this.getBaseURL(request) + Constants.FORM_ACTION, UTF8.name()));

	// configure connection
	final HttpURLConnection con =
		(HttpURLConnection) tokenEndpointURL.openConnection();
	con.setConnectTimeout(this.httpConnectTimeout);
	con.setReadTimeout(this.httpReadTimeout);
	con.setDoOutput(true);
	con.addRequestProperty("Content-Type",
			"application/x-www-form-urlencoded");
	con.addRequestProperty("Accept", "application/json");
	con.setInstanceFollowRedirects(false);

	// configure authentication
	switch (opDesc.getTokenEndpointAuthMethod()) {
	case CLIENT_SECRET_BASIC:
		con.addRequestProperty("Authorization",
			"Basic " + BASE64_ENCODER.encodeToString(
					(opDesc.getClientId() + ":" + opDesc.getClientSecret())
							.getBytes(UTF8)));
		break;
	case CLIENT_SECRET_POST:
		buf.append("&client_id=").append(URLEncoder.encode(
				opDesc.getClientId(), UTF8.name()));
		buf.append("&client_secret=").append(URLEncoder.encode(
				opDesc.getClientSecret(), UTF8.name()));
		break;
	default:
		// nothing
	}

	// finish POST body and log the call
	final String postBody = buf.toString();
	if (debug)
		this.log.debug("calling token endpoint at " + tokenEndpointURL
				+ " with: " + postBody);

	// send POST and read response
	JSONObject responseBody;
	try (final OutputStream out = con.getOutputStream()) {
		out.write(postBody.getBytes(UTF8.name()));
		out.flush();
		try (final Reader in = new InputStreamReader(
				con.getInputStream(), UTF8)) {
			responseBody = new JSONObject(new JSONTokener(in));
		} catch (final IOException e) {
			final InputStream errorStream = con.getErrorStream();
			if (errorStream == null)
				throw e;
			try (final Reader in = new InputStreamReader(errorStream, UTF8)) {
				responseBody = new JSONObject(new JSONTokener(in));
			}
		}
	}

	// create response object
	final TokenEndpointResponse response = new TokenEndpointResponse(
			con.getResponseCode(), con.getDate(), responseBody);

	// log the response
	if (debug)
		this.log.debug("received response: " + response.toString());

	// return the response
	return response;
}
 
Example #17
Source File: BaseOpenIDConnectAuthenticator.java    From tomcat-oidcauth with Apache License 2.0 4 votes vote down vote up
/**
 * Add request attributes for the login or the login error page.
 *
 * @param request The request.
 *
 * @throws IOException If an I/O error happens.
 */
protected void addLoginConfiguration(final Request request)
	throws IOException {

	// generate state value and save it in the session
	final byte[] stateBytes = new byte[16];
	this.rand.nextBytes(stateBytes);
	final String state = HexUtils.toHexString(stateBytes);
	request.getSessionInternal(true).setNote(SESS_STATE_NOTE, state);

	// add OP authorization endpoints to the request for the login page
	final List<AuthEndpointDesc> authEndpoints = new ArrayList<>();
	final StringBuilder buf = new StringBuilder(128);
	for (int i = 0; i < this.opDescs.size(); i++) {
		final OPDescriptor opDesc = this.opDescs.get(i);

		// get the OP configuration
		final String issuer = opDesc.getIssuer();
		final OPConfiguration opConfig =
			this.ops.getOPConfiguration(issuer);

		// construct the authorization endpoint URL
		buf.setLength(0);
		buf.append(opConfig.getAuthorizationEndpoint());
		buf.append("?scope=openid");
		final String extraScopes = opDesc.getAdditionalScopes();
		if (extraScopes != null)
			buf.append(URLEncoder.encode(" " + extraScopes, UTF8.name()));
		buf.append("&response_type=code");
		buf.append("&client_id=").append(URLEncoder.encode(
				opDesc.getClientId(), UTF8.name()));
		buf.append("&redirect_uri=").append(URLEncoder.encode(
				this.getBaseURL(request) + Constants.FORM_ACTION,
				UTF8.name()));
		buf.append("&state=").append(i).append('Z').append(state);
		final String addlParams = opDesc.getExtraAuthEndpointParams();
		if (addlParams != null)
			buf.append('&').append(addlParams);

		// add the URL to the map
		authEndpoints.add(new AuthEndpointDesc(
				opDesc.getName(), issuer, buf.toString()));
	}
	request.setAttribute(AUTHEPS_ATT, authEndpoints);

	// add no form flag to the request
	request.setAttribute(NOFORM_ATT, Boolean.valueOf(this.noForm));
}
 
Example #18
Source File: BaseOpenIDConnectAuthenticator.java    From tomcat-oidcauth with Apache License 2.0 4 votes vote down vote up
/**
 * If caching principal on the session by the authenticator is disabled,
 * check if the session has authentication information (username, password
 * or OP issuer ID) and if so, reauthenticate the user.
 *
 * @param request The request.
 * @param response The response.
 *
 * @return {@code true} if was successfully reauthenticated and no further
 * authentication action is required. If authentication logic should
 * proceed, returns {@code false}.
 */
protected boolean reauthenticateNoCache(final Request request,
		final HttpServletResponse response) {

	// get session
	final Session session = request.getSessionInternal(true);

	final boolean debug = this.log.isDebugEnabled();
	if (debug)
		this.log.debug("checking for reauthenticate in session "
				+ session.getIdInternal());

	// check if authentication info is in the session
	final String username =
		(String) session.getNote(Constants.SESS_USERNAME_NOTE);
	if (username == null)
		return false;

	// get the rest of the authentication info
	final Authorization authorization =
		(Authorization) session.getNote(SESS_OIDC_AUTH_NOTE);
	final String password =
		(String) session.getNote(Constants.SESS_PASSWORD_NOTE);

	// get the principal from the realm (try to reauthenticate)
	Principal principal = null;
	if (authorization != null) { // was authenticated using OpenID Connect
		if (debug)
			this.log.debug("reauthenticating username \""
					+ username + "\" authenticated by "
					+ authorization.getIssuer());
		principal = this.context.getRealm().authenticate(
				username);
	} else if (password != null) { // was form-based authentication
		if (debug)
			this.log.debug("reauthenticating username \""
					+ username + "\" using password");
		principal = this.context.getRealm().authenticate(
				username, password);
	}

	// check if could not reauthenticate
	if (principal == null) {
		if (debug)
			this.log.debug("reauthentication failed, proceed normally");
		return false;
	}

	// successfully reauthenticated, register the principal
	if (debug)
		this.log.debug("successfully reauthenticated username \""
				+ username + "\"");
	this.register(request, response, principal,
			HttpServletRequest.FORM_AUTH, username, password);

	// check if resubmit after successful authentication
	if (this.matchRequest(request)) {
		if (debug)
			this.log.debug("reauthenticated username \"" + username
					+ "\" for resubmit after successful authentication");
		return false;
	}

	// no further authentication action required
	return true;
}
 
Example #19
Source File: TestCookieFilter.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
@Test
public void test07() {
    // Simple SSO case
    Assert.assertEquals(Constants.SINGLE_SIGN_ON_COOKIE + "=[obfuscated]",
            CookieFilter.filter(Constants.SINGLE_SIGN_ON_COOKIE + "=0123456789", null));
}
 
Example #20
Source File: TestCookieFilter.java    From Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
@Test
public void test07() {
    // Simple SSO case
    Assert.assertEquals(Constants.SINGLE_SIGN_ON_COOKIE + "=[obfuscated]",
            CookieFilter.filter(Constants.SINGLE_SIGN_ON_COOKIE + "=0123456789", null));
}
 
Example #21
Source File: TestCookieFilter.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
@Test
public void test07() {
    // Simple SSO case
    Assert.assertEquals(Constants.SINGLE_SIGN_ON_COOKIE + "=[obfuscated]",
            CookieFilter.filter(Constants.SINGLE_SIGN_ON_COOKIE + "=0123456789", null));
}