Search in sources :

Example 6 with PreconditionException

use of com.microsoft.azure.oidc.exception.PreconditionException in project azure-tools-for-java by Microsoft.

the class LogoutServlet method service.

@Override
public void service(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
    try {
        final Configuration configuration = configurationCache.load();
        final ApplicationSettings applicationSettings = applicationSettingsLoader.load();
        // the finishLogout parameter set
        if (request.getParameter("finishLogout") == null) {
            String tokenString = null;
            final Cookie[] cookies = request.getCookies();
            for (final Cookie cookie : cookies) {
                if (cookie.getName().equals("id_token")) {
                    tokenString = cookie.getValue();
                    break;
                }
            }
            final String redirectURL = String.format("%s%spost_logout_redirect_uri=%s%s%s", configuration.getLogoutEndPoint(), configuration.getLogoutEndPoint().getName().contains("?") ? "&" : "?", URLEncoder.encode(applicationSettings.getRedirectURL().getValue(), "UTF-8"), URLEncoder.encode(request.getRequestURI(), "UTF-8"), URLEncoder.encode("?finishLogout=true", "UTF-8"));
            response.setHeader("Authorization", String.format("Bearer %s", tokenString));
            response.sendRedirect(redirectURL);
            return;
        }
        // setup clearing the cookies and invalidate the session
        for (final Cookie cookie : request.getCookies()) {
            if (cookie.getName().equals("id_token")) {
                cookie.setMaxAge(0);
                response.addCookie(cookie);
                HttpSession session = request.getSession(false);
                if (session != null) {
                    session.invalidate();
                }
            }
            if (cookie.getName().equals("JSESSIONID") || cookie.getName().equals("SESSON")) {
                cookie.setMaxAge(0);
                response.addCookie(cookie);
                HttpSession session = request.getSession(false);
                if (session != null) {
                    session.invalidate();
                }
            }
        }
        final HttpServletRequest newRequest = new HttpServletRequestWrapper(request) {

            @Override
            public Cookie[] getCookies() {
                final List<Cookie> cookieList = new ArrayList<Cookie>();
                for (Cookie cookie : request.getCookies()) {
                    if (!cookie.getName().equals("SESSION") && !cookie.getName().equals("JSESSIONID")) {
                        cookieList.add(cookie);
                    }
                }
                final Cookie[] cookieArray = new Cookie[cookieList.size()];
                cookieList.toArray(cookieArray);
                return cookieArray;
            }
        };
        // Second stage. Forward the request so the cookies are cleared
        if (request.getAttribute("logout") == null) {
            request.setAttribute("logout", Boolean.TRUE);
            request.getRequestDispatcher(request.getRequestURI() + "?finishLogout=true").forward(newRequest, response);
            return;
        }
        // Final stage. Return to the application landing page
        response.sendRedirect(applicationSettings.getRedirectURL().getValue());
        return;
    } catch (IOException | GeneralException | PreconditionException e) {
        LOGGER.warn(e.getMessage(), e);
        final ApplicationSettings applicationSettings = applicationSettingsLoader.load();
        response.sendRedirect(applicationSettings.getRedirectURL().getValue());
    }
}
Also used : Cookie(javax.servlet.http.Cookie) GeneralException(com.microsoft.azure.oidc.exception.GeneralException) Configuration(com.microsoft.azure.oidc.configuration.Configuration) HttpSession(javax.servlet.http.HttpSession) ArrayList(java.util.ArrayList) IOException(java.io.IOException) PreconditionException(com.microsoft.azure.oidc.exception.PreconditionException) HttpServletRequest(javax.servlet.http.HttpServletRequest) ApplicationSettings(com.microsoft.azure.oidc.application.settings.ApplicationSettings) HttpServletRequestWrapper(javax.servlet.http.HttpServletRequestWrapper)

Example 7 with PreconditionException

use of com.microsoft.azure.oidc.exception.PreconditionException in project azure-tools-for-java by Microsoft.

the class SimpleKeyStoreParser method getKeys.

@Override
public Map<Name, Key> getKeys(final JsonNode node) {
    if (node == null) {
        throw new PreconditionException("Required parameter is null");
    }
    final Map<Name, Key> keys = new HashMap<Name, Key>();
    for (final JsonNode n : node.get("keys")) {
        final TimeStamp notBefore = timeStampFactory.createTimeStamp(n.has("nbf") ? n.get("nbf").asLong() : 0L);
        final Name keyName = nameFactory.createKeyName(n.get("kid").asText());
        final Modulus modulus = modulusFactory.createKeyValue(n.get("n").asText());
        final Exponent exponent = exponentFactory.createKeyExponent(n.get("e").asText());
        final Key key = keyFactory.createKey(notBefore, modulus, exponent);
        keys.put(keyName, key);
    }
    return keys;
}
Also used : Exponent(com.microsoft.azure.oidc.configuration.key.exponent.Exponent) HashMap(java.util.HashMap) Modulus(com.microsoft.azure.oidc.configuration.key.modulus.Modulus) JsonNode(com.fasterxml.jackson.databind.JsonNode) Key(com.microsoft.azure.oidc.configuration.key.Key) TimeStamp(com.microsoft.azure.oidc.common.timestamp.TimeStamp) PreconditionException(com.microsoft.azure.oidc.exception.PreconditionException) Name(com.microsoft.azure.oidc.common.name.Name)

Example 8 with PreconditionException

use of com.microsoft.azure.oidc.exception.PreconditionException in project azure-tools-for-java by Microsoft.

the class SimpleTokenValidator method validateSignature.

@Override
public Boolean validateSignature(final Token token) {
    if (token == null) {
        throw new PreconditionException("Required parameter is null");
    }
    if (algorithmConfigurationService.get().getAlgorithmClassMap().get(token.getAlgorithm().getName()).equals("HMAC")) {
        return Boolean.FALSE;
    }
    final Configuration configuration = configurationCache.load();
    if (configuration == null) {
        throw new GeneralException("Error loading configuration");
    }
    try {
        final TimeStamp now = timeStampFactory.createTimeStamp(System.currentTimeMillis() / 1000);
        if (configuration.getKey(token.getKeyName()).getNotBefore().compareTo(now) > 0) {
            return Boolean.FALSE;
        }
        final Base64 decoder = new Base64();
        final BigInteger exponent = new BigInteger(1, decoder.decode(configuration.getKey(token.getKeyName()).getExponent().getValue()));
        final BigInteger modulus = new BigInteger(1, decoder.decode(configuration.getKey(token.getKeyName()).getSecret().getValue()));
        final RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(modulus, exponent);
        final KeyFactory keyFactory = KeyFactory.getInstance(algorithmConfigurationService.get().getAlgorithmClassMap().get(token.getAlgorithm().getName()));
        final PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);
        final Signature sig = Signature.getInstance(algorithmConfigurationService.get().getAlgorithmMap().get(token.getAlgorithm().getName()));
        sig.initVerify(pubKey);
        sig.update(token.getPayload().getValue().getBytes());
        return sig.verify(decoder.decode(token.getSignature().getValue()));
    } catch (NoSuchAlgorithmException | InvalidKeySpecException | SignatureException | InvalidKeyException e) {
        LOGGER.error(e.getMessage(), e);
        return Boolean.FALSE;
    }
}
Also used : GeneralException(com.microsoft.azure.oidc.exception.GeneralException) Base64(org.apache.commons.codec.binary.Base64) Configuration(com.microsoft.azure.oidc.configuration.Configuration) PublicKey(java.security.PublicKey) RSAPublicKeySpec(java.security.spec.RSAPublicKeySpec) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SignatureException(java.security.SignatureException) InvalidKeyException(java.security.InvalidKeyException) TimeStamp(com.microsoft.azure.oidc.common.timestamp.TimeStamp) PreconditionException(com.microsoft.azure.oidc.exception.PreconditionException) Signature(java.security.Signature) BigInteger(java.math.BigInteger) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) KeyFactory(java.security.KeyFactory)

Example 9 with PreconditionException

use of com.microsoft.azure.oidc.exception.PreconditionException in project azure-tools-for-java by Microsoft.

the class SimpleAuthenticationHelper method getState.

private State getState(final HttpServletRequest request) {
    if (request == null) {
        throw new PreconditionException("Required parameter is null");
    }
    try {
        final Base64 decoder = new Base64();
        final String stateString = request.getParameter("state") == null ? null : new String(decoder.decode(request.getParameter("state").getBytes()), "UTF-8");
        if (stateString == null || stateString.equals("")) {
            return null;
        }
        final ObjectMapper mapper = new ObjectMapper();
        final JsonNode stateNode = mapper.readValue(stateString, JsonNode.class);
        final State state = stateFactory.createState(stateNode.get("userID").asText(""), stateNode.get("sessionName").asText(""), stateNode.get("requestURI").asText());
        return state;
    } catch (IOException e) {
        throw new GeneralException("IO Exception", e);
    }
}
Also used : Base64(org.apache.commons.codec.binary.Base64) GeneralException(com.microsoft.azure.oidc.exception.GeneralException) State(com.microsoft.azure.oidc.common.state.State) JsonNode(com.fasterxml.jackson.databind.JsonNode) IOException(java.io.IOException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) PreconditionException(com.microsoft.azure.oidc.exception.PreconditionException)

Example 10 with PreconditionException

use of com.microsoft.azure.oidc.exception.PreconditionException in project azure-tools-for-java by Microsoft.

the class SimpleAuthenticationHelper method clearSessionCoookie.

// this needs refactoring.
private HttpServletRequest clearSessionCoookie(final HttpServletRequest httpRequest, final HttpServletResponse httpResponse, final Token token, final State state) {
    if (httpRequest == null || httpResponse == null || token == null || state == null) {
        throw new PreconditionException("Required parameter is null");
    }
    final Cookie redisSessionCookie = getCookie(httpRequest, "SESSION");
    final Cookie javaSessionCookie = getCookie(httpRequest, "JSESSIONID");
    if (redisSessionCookie != null || javaSessionCookie != null) {
        if (token.getUserID().toString().equals(state.getUserID())) {
            if (redisSessionCookie != null && redisSessionCookie.getValue().equals(state.getSessionName())) {
                return httpRequest;
            }
            if (javaSessionCookie != null && javaSessionCookie.getValue().equals(state.getSessionName())) {
                return httpRequest;
            }
        }
        if (redisSessionCookie != null) {
            redisSessionCookie.setMaxAge(0);
            httpResponse.addCookie(redisSessionCookie);
            HttpSession session = httpRequest.getSession(false);
            if (session != null) {
                session.invalidate();
            }
        }
        if (javaSessionCookie != null) {
            javaSessionCookie.setMaxAge(0);
            httpResponse.addCookie(javaSessionCookie);
            HttpSession session = httpRequest.getSession(false);
            if (session != null) {
                session.invalidate();
            }
        }
        return new HttpServletRequestWrapper(httpRequest) {

            @Override
            public Cookie[] getCookies() {
                final List<Cookie> cookieList = new ArrayList<Cookie>();
                for (Cookie cookie : httpRequest.getCookies()) {
                    if (!cookie.getName().equals("SESSION") && !cookie.getName().equals("JSESSIONID")) {
                        cookieList.add(cookie);
                    }
                }
                final Cookie[] cookieArray = new Cookie[cookieList.size()];
                cookieList.toArray(cookieArray);
                return cookieArray;
            }
        };
    }
    return httpRequest;
}
Also used : Cookie(javax.servlet.http.Cookie) HttpServletRequestWrapper(javax.servlet.http.HttpServletRequestWrapper) HttpSession(javax.servlet.http.HttpSession) ArrayList(java.util.ArrayList) PreconditionException(com.microsoft.azure.oidc.exception.PreconditionException)

Aggregations

PreconditionException (com.microsoft.azure.oidc.exception.PreconditionException)12 GeneralException (com.microsoft.azure.oidc.exception.GeneralException)5 IOException (java.io.IOException)5 JsonNode (com.fasterxml.jackson.databind.JsonNode)4 Cookie (javax.servlet.http.Cookie)4 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)3 Configuration (com.microsoft.azure.oidc.configuration.Configuration)3 ArrayList (java.util.ArrayList)3 HttpSession (javax.servlet.http.HttpSession)3 Base64 (org.apache.commons.codec.binary.Base64)3 ApplicationSettings (com.microsoft.azure.oidc.application.settings.ApplicationSettings)2 State (com.microsoft.azure.oidc.common.state.State)2 TimeStamp (com.microsoft.azure.oidc.common.timestamp.TimeStamp)2 HttpServletRequest (javax.servlet.http.HttpServletRequest)2 HttpServletRequestWrapper (javax.servlet.http.HttpServletRequestWrapper)2 Algorithm (com.microsoft.azure.oidc.common.algorithm.Algorithm)1 Name (com.microsoft.azure.oidc.common.name.Name)1 Key (com.microsoft.azure.oidc.configuration.key.Key)1 Exponent (com.microsoft.azure.oidc.configuration.key.exponent.Exponent)1 Modulus (com.microsoft.azure.oidc.configuration.key.modulus.Modulus)1