Search in sources :

Example 1 with Session

use of com.predic8.membrane.core.interceptor.authentication.session.SessionManager.Session in project service-proxy by membrane.

the class OAuth2ResourceInterceptor method handleRequestInternal.

private Outcome handleRequestInternal(Exchange exc) throws Exception {
    if (initPublicURLOnFirstExchange)
        setPublicURL(exc);
    if (firstInitWhenDynamicAuthorizationService) {
        firstInitWhenDynamicAuthorizationService = false;
        getAuthService().dynamicRegistration(exc, publicURL);
    }
    if (isFaviconRequest(exc)) {
        exc.setResponse(Response.badRequest().build());
        return Outcome.RETURN;
    }
    if (isLoginRequest(exc)) {
        handleLoginRequest(exc);
        return Outcome.RETURN;
    }
    Session session = sessionManager.getSession(exc);
    if (session == null) {
        String auth = exc.getRequest().getHeader().getFirstValue(Header.AUTHORIZATION);
        if (auth != null && auth.substring(0, 7).equalsIgnoreCase("Bearer ")) {
            session = sessionManager.createSession(exc);
            session.getUserAttributes().put(ParamNames.ACCESS_TOKEN, auth.substring(7));
            OAuth2AnswerParameters oauth2Answer = new OAuth2AnswerParameters();
            oauth2Answer.setAccessToken(auth.substring(7));
            oauth2Answer.setTokenType("Bearer");
            HashMap<String, String> userinfo = revalidateToken(oauth2Answer);
            if (userinfo == null)
                return respondWithRedirect(exc);
            oauth2Answer.setUserinfo(userinfo);
            session.getUserAttributes().put(OAUTH2_ANSWER, oauth2Answer.serialize());
            processUserInfo(userinfo, session);
        }
    }
    if (session == null)
        return respondWithRedirect(exc);
    if (session.getUserAttributes().get(OAUTH2_ANSWER) != null && tokenNeedsRevalidation(session.getUserAttributes().get(ParamNames.ACCESS_TOKEN))) {
        if (revalidateToken(OAuth2AnswerParameters.deserialize(session.getUserAttributes().get(OAUTH2_ANSWER))) == null)
            session.clear();
    }
    if (session.getUserAttributes().get(OAUTH2_ANSWER) != null)
        exc.setProperty(Exchange.OAUTH2, OAuth2AnswerParameters.deserialize(session.getUserAttributes().get(OAUTH2_ANSWER)));
    if (refreshingOfAccessTokenIsNeeded(session)) {
        synchronized (session) {
            refreshAccessToken(session);
            exc.setProperty(Exchange.OAUTH2, OAuth2AnswerParameters.deserialize(session.getUserAttributes().get(OAUTH2_ANSWER)));
        }
    }
    if (session.isAuthorized()) {
        applyBackendAuthorization(exc, session);
        statistics.successfulRequest();
        return Outcome.CONTINUE;
    }
    if (handleRequest(exc, session.getUserAttributes().get("state"), publicURL, session)) {
        if (exc.getResponse() == null && exc.getRequest() != null && session.isAuthorized() && session.getUserAttributes().containsKey(OAUTH2_ANSWER)) {
            exc.setProperty(Exchange.OAUTH2, OAuth2AnswerParameters.deserialize(session.getUserAttributes().get(OAUTH2_ANSWER)));
            return Outcome.CONTINUE;
        }
        if (exc.getResponse().getStatusCode() >= 400)
            session.clear();
        return Outcome.RETURN;
    }
    return respondWithRedirect(exc);
}
Also used : Session(com.predic8.membrane.core.interceptor.authentication.session.SessionManager.Session)

Example 2 with Session

use of com.predic8.membrane.core.interceptor.authentication.session.SessionManager.Session in project service-proxy by membrane.

the class OAuth2ResourceInterceptor method respondWithRedirect.

private Outcome respondWithRedirect(Exchange exc) {
    if (loginLocation == null) {
        String state = new BigInteger(130, new SecureRandom()).toString(32);
        exc.setResponse(Response.redirectGet(auth.getLoginURL(state, publicURL, exc.getRequestURI())).build());
        stateToOriginalUrl.put(state, exc.getRequest());
        Session session = sessionManager.getOrCreateSession(exc);
        synchronized (session) {
            if (session.getUserAttributes().containsKey(ParamNames.STATE))
                state = session.getUserAttributes().get(ParamNames.STATE) + " " + state;
            if (!session.isPreAuthorized() || !session.isAuthorized())
                session.preAuthorize("", new HashMap<>());
            session.getUserAttributes().put(ParamNames.STATE, state);
        }
    } else {
        exc.setResponse(Response.redirectGet(loginPath).build());
    }
    return Outcome.RETURN;
}
Also used : HashMap(java.util.HashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) BigInteger(java.math.BigInteger) SecureRandom(java.security.SecureRandom) Session(com.predic8.membrane.core.interceptor.authentication.session.SessionManager.Session)

Example 3 with Session

use of com.predic8.membrane.core.interceptor.authentication.session.SessionManager.Session in project service-proxy by membrane.

the class OAuth2ResourceInterceptor method handleLoginRequest.

public void handleLoginRequest(Exchange exc) throws Exception {
    Session s = sessionManager.getSession(exc);
    String uri = exc.getRequest().getUri().substring(loginPath.length() - 1);
    if (uri.indexOf('?') >= 0)
        uri = uri.substring(0, uri.indexOf('?'));
    exc.getDestinations().set(0, uri);
    if (uri.equals("/logout")) {
        if (s != null && s.getUserAttributes() != null) {
            String token;
            synchronized (s) {
                token = s.getUserAttributes().get("access_token");
            }
            Exchange e = new Request.Builder().post(auth.getRevocationEndpoint()).header(Header.CONTENT_TYPE, "application/x-www-form-urlencoded").header(Header.USER_AGENT, Constants.USERAGENT).body(// TODO maybe send client credentials ( as it was before ) but Google doesn't accept that
            "token=" + token).buildExchange();
            Response response = auth.doRequest(e);
            if (response.getStatusCode() != 200)
                throw new RuntimeException("Revocation of token did not work. Statuscode: " + response.getStatusCode() + ".");
            s.clear();
            sessionManager.removeSession(exc);
        }
        exc.setResponse(Response.redirect("/", false).build());
    } else if (uri.equals("/")) {
        if (s == null || !s.isAuthorized()) {
            String state = new BigInteger(130, new SecureRandom()).toString(32);
            showPage(exc, state);
            Session session = sessionManager.createSession(exc);
            HashMap<String, String> userAttributes = new HashMap<String, String>();
            userAttributes.put("state", state);
            session.preAuthorize("", userAttributes);
        } else {
            showPage(exc, s.getUserAttributes().get("state"));
        }
    } else {
        wsi.handleRequest(exc);
    }
}
Also used : Exchange(com.predic8.membrane.core.exchange.Exchange) Response(com.predic8.membrane.core.http.Response) HashMap(java.util.HashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Request(com.predic8.membrane.core.http.Request) BigInteger(java.math.BigInteger) SecureRandom(java.security.SecureRandom) Session(com.predic8.membrane.core.interceptor.authentication.session.SessionManager.Session)

Example 4 with Session

use of com.predic8.membrane.core.interceptor.authentication.session.SessionManager.Session in project service-proxy by membrane.

the class OAuth2ResourceInterceptor method refreshAccessToken.

private void refreshAccessToken(Session session) throws Exception {
    if (!refreshingOfAccessTokenIsNeeded(session))
        return;
    OAuth2AnswerParameters oauth2Params = OAuth2AnswerParameters.deserialize(session.getUserAttributes().get(OAUTH2_ANSWER));
    Exchange refreshTokenExchange = new Request.Builder().post(auth.getTokenEndpoint()).header(Header.CONTENT_TYPE, "application/x-www-form-urlencoded").header(Header.ACCEPT, "application/json").header(Header.USER_AGENT, Constants.USERAGENT).body("&grant_type=refresh_token" + "&refresh_token=" + oauth2Params.getRefreshToken()).buildExchange();
    Response refreshTokenResponse = auth.doRequest(refreshTokenExchange);
    if (!refreshTokenResponse.isOk()) {
        refreshTokenResponse.getBody().read();
        throw new RuntimeException("Statuscode from authorization server for refresh token request: " + refreshTokenResponse.getStatusCode());
    }
    HashMap<String, String> json = Util.parseSimpleJSONResponse(refreshTokenResponse);
    if (json.get("access_token") == null || json.get("refresh_token") == null) {
        refreshTokenResponse.getBody().read();
        throw new RuntimeException("Statuscode was ok but no access_token and refresh_token was received: " + refreshTokenResponse.getStatusCode());
    }
    oauth2Params.setAccessToken(json.get("access_token"));
    oauth2Params.setRefreshToken(json.get("refresh_token"));
    oauth2Params.setExpiration(json.get("expires_in"));
    oauth2Params.setReceivedAt(LocalDateTime.now());
    if (json.containsKey("id_token")) {
        if (idTokenIsValid(json.get("id_token")))
            oauth2Params.setIdToken(json.get("id_token"));
        else
            oauth2Params.setIdToken("INVALID");
    }
    session.getUserAttributes().put(OAUTH2_ANSWER, oauth2Params.serialize());
}
Also used : Exchange(com.predic8.membrane.core.exchange.Exchange) Response(com.predic8.membrane.core.http.Response) CacheBuilder(com.google.common.cache.CacheBuilder)

Example 5 with Session

use of com.predic8.membrane.core.interceptor.authentication.session.SessionManager.Session in project service-proxy by membrane.

the class AuthWithoutSessionRequest method processWithParameters.

@Override
protected Response processWithParameters() throws Exception {
    Client client;
    try {
        client = authServer.getClientList().getClient(getClientId());
    } catch (Exception e) {
        return OAuth2Util.createParameterizedJsonErrorResponse(exc, jsonGen, "error", "unauthorized_client");
    }
    if (!OAuth2Util.isAbsoluteUri(getRedirectUri()) || !getRedirectUri().equals(client.getCallbackUrl()))
        return OAuth2Util.createParameterizedJsonErrorResponse(exc, jsonGen, "error", "invalid_request");
    if (promptEqualsNone())
        return createParameterizedFormUrlencodedRedirect(exc, getState(), client.getCallbackUrl() + "?error=login_required");
    if (!authServer.getSupportedAuthorizationGrants().contains(getResponseType()))
        return createParameterizedFormUrlencodedRedirect(exc, getState(), client.getCallbackUrl() + "?error=unsupported_response_type");
    String validScopes = verifyScopes(getScope());
    if (validScopes.isEmpty())
        return createParameterizedFormUrlencodedRedirect(exc, getState(), client.getCallbackUrl() + "?error=invalid_scope");
    if (OAuth2Util.isOpenIdScope(validScopes)) {
        if (!isCodeRequest())
            return createParameterizedFormUrlencodedRedirect(exc, getState(), client.getCallbackUrl() + "?error=invalid_request");
        // Parses the claims parameter into a json object. Claim values are always ignored and set to "null" as it is optional to react to those values
        addValidClaimsToParams();
    } else
        removeClaimsWhenNotOpenidScope();
    setScope(validScopes);
    String invalidScopes = hasGivenInvalidScopes(getScope(), validScopes);
    if (!invalidScopes.isEmpty())
        setScopeInvalid(invalidScopes);
    SessionManager.Session session = authServer.getSessionManager().getOrCreateSession(exc);
    addParams(session, params);
    return new NoResponse();
}
Also used : SessionManager(com.predic8.membrane.core.interceptor.authentication.session.SessionManager) Client(com.predic8.membrane.core.interceptor.oauth2.Client) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Aggregations

Session (com.predic8.membrane.core.interceptor.authentication.session.SessionManager.Session)5 Exchange (com.predic8.membrane.core.exchange.Exchange)4 Response (com.predic8.membrane.core.http.Response)3 ParseException (com.floreysoft.jmte.message.ParseException)2 CacheBuilder (com.google.common.cache.CacheBuilder)2 Request (com.predic8.membrane.core.http.Request)2 SessionManager (com.predic8.membrane.core.interceptor.authentication.session.SessionManager)2 Client (com.predic8.membrane.core.interceptor.oauth2.Client)2 ServiceProxy (com.predic8.membrane.core.rules.ServiceProxy)2 ServiceProxyKey (com.predic8.membrane.core.rules.ServiceProxyKey)2 IOException (java.io.IOException)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 BigInteger (java.math.BigInteger)2 MalformedURLException (java.net.MalformedURLException)2 SecureRandom (java.security.SecureRandom)2 HashMap (java.util.HashMap)2 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)2 HttpRouter (com.predic8.membrane.core.HttpRouter)1 LogInterceptor (com.predic8.membrane.core.interceptor.LogInterceptor)1 Session (com.predic8.membrane.core.interceptor.balancer.Session)1