Search in sources :

Example 11 with SecurityTokenHolder

use of ddf.security.common.SecurityTokenHolder in project ddf by codice.

the class TestLogoutServlet method testLocalLogout.

@Test
public void testLocalLogout() {
    LocalLogoutServlet localLogoutServlet = new MockLocalLogoutServlet();
    HttpServletRequest request = mock(HttpServletRequest.class);
    HttpServletResponse response = mock(HttpServletResponse.class);
    Subject subject = mock(Subject.class);
    when(subject.hasRole(anyString())).thenReturn(false);
    ThreadContext.bind(subject);
    System.setProperty("security.audit.roles", "none");
    HttpSession httpSession = mock(HttpSession.class);
    when(request.getSession()).thenReturn(httpSession);
    when(request.getSession().getId()).thenReturn("id");
    when(request.getRequestURL()).thenReturn(new StringBuffer("http://foo.bar"));
    //Used for detecting basic auth
    when(request.getHeaders(anyString())).thenReturn(new Enumeration() {

        @Override
        public boolean hasMoreElements() {
            return true;
        }

        @Override
        public Object nextElement() {
            return "Basic";
        }
    });
    //used for detecting pki
    when(request.getAttribute("javax.servlet.request.X509Certificate")).thenReturn(new X509Certificate[] { mock(X509Certificate.class) });
    SecurityTokenHolder securityTokenHolder = mock(SecurityTokenHolder.class);
    when(httpSession.getAttribute(SecurityConstants.SAML_ASSERTION)).thenReturn(securityTokenHolder);
    try {
        localLogoutServlet.doGet(request, response);
    } catch (ServletException | IOException e) {
        fail(e.getMessage());
    }
    verify(httpSession).invalidate();
}
Also used : Enumeration(java.util.Enumeration) HttpSession(javax.servlet.http.HttpSession) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) Subject(org.apache.shiro.subject.Subject) X509Certificate(java.security.cert.X509Certificate) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) SecurityTokenHolder(ddf.security.common.SecurityTokenHolder) Test(org.junit.Test)

Example 12 with SecurityTokenHolder

use of ddf.security.common.SecurityTokenHolder in project ddf by codice.

the class SAMLAssertionHandler method getNormalizedToken.

@Override
public HandlerResult getNormalizedToken(ServletRequest request, ServletResponse response, FilterChain chain, boolean resolve) {
    HandlerResult handlerResult = new HandlerResult();
    String realm = (String) request.getAttribute(ContextPolicy.ACTIVE_REALM);
    SecurityToken securityToken;
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    String authHeader = ((HttpServletRequest) request).getHeader(SecurityConstants.SAML_HEADER_NAME);
    // check for full SAML assertions coming in (federated requests, etc.)
    if (authHeader != null) {
        String[] tokenizedAuthHeader = authHeader.split(" ");
        if (tokenizedAuthHeader.length == 2 && tokenizedAuthHeader[0].equals("SAML")) {
            String encodedSamlAssertion = tokenizedAuthHeader[1];
            LOGGER.trace("Header retrieved");
            try {
                String tokenString = RestSecurity.inflateBase64(encodedSamlAssertion);
                LOGGER.trace("Header value: {}", tokenString);
                securityToken = new SecurityToken();
                Element thisToken = null;
                if (tokenString.contains(SAML_NAMESPACE)) {
                    try {
                        thisToken = StaxUtils.read(new StringReader(tokenString)).getDocumentElement();
                    } catch (XMLStreamException e) {
                        LOGGER.info("Unexpected error converting XML string to element - proceeding without SAML token.", e);
                    }
                } else {
                    thisToken = parseAssertionWithoutNamespace(tokenString);
                }
                securityToken.setToken(thisToken);
                SAMLAuthenticationToken samlToken = new SAMLAuthenticationToken(null, securityToken, realm);
                handlerResult.setToken(samlToken);
                handlerResult.setStatus(HandlerResult.Status.COMPLETED);
            } catch (IOException e) {
                LOGGER.info("Unexpected error converting header value to string", e);
            }
            return handlerResult;
        }
    }
    // Check for legacy SAML cookie
    Map<String, Cookie> cookies = HttpUtils.getCookieMap(httpRequest);
    Cookie samlCookie = cookies.get(SecurityConstants.SAML_COOKIE_NAME);
    if (samlCookie != null) {
        String cookieValue = samlCookie.getValue();
        LOGGER.trace("Cookie retrieved");
        try {
            String tokenString = RestSecurity.inflateBase64(cookieValue);
            LOGGER.trace("Cookie value: {}", tokenString);
            securityToken = new SecurityToken();
            Element thisToken = StaxUtils.read(new StringReader(tokenString)).getDocumentElement();
            securityToken.setToken(thisToken);
            SAMLAuthenticationToken samlToken = new SAMLAuthenticationToken(null, securityToken, realm);
            handlerResult.setToken(samlToken);
            handlerResult.setStatus(HandlerResult.Status.COMPLETED);
        } catch (IOException e) {
            LOGGER.info("Unexpected error converting cookie value to string - proceeding without SAML token.", e);
        } catch (XMLStreamException e) {
            LOGGER.info("Unexpected error converting XML string to element - proceeding without SAML token.", e);
        }
        return handlerResult;
    }
    HttpSession session = httpRequest.getSession(false);
    if (session == null && httpRequest.getRequestedSessionId() != null) {
        session = sessionFactory.getOrCreateSession(httpRequest);
    }
    if (session != null) {
        //Check if there is a SAML Assertion in the session
        //If so, create a SAMLAuthenticationToken using the sessionId
        SecurityTokenHolder savedToken = (SecurityTokenHolder) session.getAttribute(SecurityConstants.SAML_ASSERTION);
        if (savedToken != null && savedToken.getSecurityToken(realm) != null) {
            SecurityAssertionImpl assertion = new SecurityAssertionImpl(savedToken.getSecurityToken(realm));
            if (assertion.isPresentlyValid()) {
                LOGGER.trace("Creating SAML authentication token with session.");
                SAMLAuthenticationToken samlToken = new SAMLAuthenticationToken(null, session.getId(), realm);
                handlerResult.setToken(samlToken);
                handlerResult.setStatus(HandlerResult.Status.COMPLETED);
                return handlerResult;
            } else {
                LOGGER.trace("SAML token in session has expired - removing from session and returning with no results");
                savedToken.remove(realm);
            }
        } else {
            LOGGER.trace("No SAML token located in session - returning with no results");
        }
    } else {
        LOGGER.trace("No HTTP Session - returning with no results");
    }
    return handlerResult;
}
Also used : Cookie(javax.servlet.http.Cookie) HttpSession(javax.servlet.http.HttpSession) Element(org.w3c.dom.Element) HandlerResult(org.codice.ddf.security.handler.api.HandlerResult) IOException(java.io.IOException) SAMLAuthenticationToken(org.codice.ddf.security.handler.api.SAMLAuthenticationToken) SecurityAssertionImpl(ddf.security.assertion.impl.SecurityAssertionImpl) SecurityToken(org.apache.cxf.ws.security.tokenstore.SecurityToken) HttpServletRequest(javax.servlet.http.HttpServletRequest) SecurityTokenHolder(ddf.security.common.SecurityTokenHolder) XMLStreamException(javax.xml.stream.XMLStreamException) StringReader(java.io.StringReader)

Example 13 with SecurityTokenHolder

use of ddf.security.common.SecurityTokenHolder in project ddf by codice.

the class AuthenticationEndpoint method login.

@POST
public Response login(@Context HttpServletRequest request, @FormParam("username") String username, @FormParam("password") String password, @FormParam("prevurl") String prevurl) throws SecurityServiceException {
    // Make sure we're using HTTPS
    if (!request.isSecure()) {
        throw new IllegalArgumentException("Authentication request must use TLS.");
    }
    HttpSession session = request.getSession(false);
    if (session != null) {
        session.invalidate();
    }
    // Get the realm from the previous url
    String realm = BaseAuthenticationToken.DEFAULT_REALM;
    ContextPolicy policy = contextPolicyManager.getContextPolicy(prevurl);
    if (policy != null) {
        realm = policy.getRealm();
    }
    // Create an authentication token
    UPAuthenticationToken authenticationToken = new UPAuthenticationToken(username, password, realm);
    // Authenticate
    Subject subject = securityManager.getSubject(authenticationToken);
    if (subject == null) {
        throw new SecurityServiceException("Authentication failed");
    }
    for (Object principal : subject.getPrincipals()) {
        if (principal instanceof SecurityAssertion) {
            SecurityToken securityToken = ((SecurityAssertion) principal).getSecurityToken();
            if (securityToken == null) {
                LOGGER.debug("Cannot add null security token to session");
                continue;
            }
            // Create a session and add the security token
            session = sessionFactory.getOrCreateSession(request);
            SecurityTokenHolder holder = (SecurityTokenHolder) session.getAttribute(SecurityConstants.SAML_ASSERTION);
            holder.addSecurityToken(realm, securityToken);
        }
    }
    // Redirect to the previous url
    URI redirect = uriInfo.getBaseUriBuilder().replacePath(prevurl).build();
    return Response.seeOther(redirect).build();
}
Also used : SecurityToken(org.apache.cxf.ws.security.tokenstore.SecurityToken) SecurityServiceException(ddf.security.service.SecurityServiceException) SecurityTokenHolder(ddf.security.common.SecurityTokenHolder) HttpSession(javax.servlet.http.HttpSession) UPAuthenticationToken(org.codice.ddf.security.handler.api.UPAuthenticationToken) SecurityAssertion(ddf.security.assertion.SecurityAssertion) URI(java.net.URI) ContextPolicy(org.codice.ddf.security.policy.context.ContextPolicy) Subject(ddf.security.Subject) POST(javax.ws.rs.POST)

Example 14 with SecurityTokenHolder

use of ddf.security.common.SecurityTokenHolder in project ddf by codice.

the class LogoutRequestServiceTest method setup.

@Before
public void setup() throws ParserConfigurationException, SAXException, IOException {
    simpleSign = mock(SimpleSign.class);
    idpMetadata = mock(IdpMetadata.class);
    relayStates = mock(RelayStates.class);
    sessionFactory = mock(SessionFactory.class);
    request = mock(HttpServletRequest.class);
    logoutMessage = mock(LogoutMessage.class);
    encryptionService = mock(EncryptionService.class);
    session = mock(HttpSession.class);
    securityTokenHolder = mock(SecurityTokenHolder.class);
    Element issuedAssertion = readSamlAssertion().getDocumentElement();
    String assertionId = issuedAssertion.getAttributeNodeNS(null, "ID").getNodeValue();
    SecurityToken token = new SecurityToken(assertionId, issuedAssertion, null);
    when(securityTokenHolder.getSecurityToken("idp")).thenReturn(token);
    logoutRequestService = new MockLogoutRequestService(simpleSign, idpMetadata, relayStates);
    logoutRequestService.setEncryptionService(encryptionService);
    logoutRequestService.setLogOutPageTimeOut(LOGOUT_PAGE_TIMEOUT);
    logoutRequestService.setLogoutMessage(logoutMessage);
    logoutRequestService.setRequest(request);
    logoutRequestService.setSessionFactory(sessionFactory);
    logoutRequestService.init();
    when(sessionFactory.getOrCreateSession(request)).thenReturn(session);
    when(session.getAttribute(eq(SecurityConstants.SAML_ASSERTION))).thenReturn(securityTokenHolder);
    when(request.getRequestURL()).thenReturn(new StringBuffer("www.url.com/url"));
    when(idpMetadata.getSigningCertificate()).thenReturn("signingCertificate");
    when(idpMetadata.getSingleLogoutBinding()).thenReturn(SamlProtocol.REDIRECT_BINDING);
    when(idpMetadata.getSingleLogoutLocation()).thenReturn(redirectLogoutUrl);
    System.setProperty("security.audit.roles", "none");
}
Also used : SessionFactory(ddf.security.http.SessionFactory) RelayStates(ddf.security.samlp.impl.RelayStates) LogoutMessage(ddf.security.samlp.LogoutMessage) HttpSession(javax.servlet.http.HttpSession) Element(org.w3c.dom.Element) Matchers.anyString(org.mockito.Matchers.anyString) HttpServletRequest(javax.servlet.http.HttpServletRequest) SecurityToken(org.apache.cxf.ws.security.tokenstore.SecurityToken) SimpleSign(ddf.security.samlp.SimpleSign) SecurityTokenHolder(ddf.security.common.SecurityTokenHolder) EncryptionService(ddf.security.encryption.EncryptionService) Before(org.junit.Before)

Aggregations

SecurityTokenHolder (ddf.security.common.SecurityTokenHolder)14 HttpSession (javax.servlet.http.HttpSession)11 SecurityToken (org.apache.cxf.ws.security.tokenstore.SecurityToken)9 HttpServletRequest (javax.servlet.http.HttpServletRequest)5 SecurityAssertion (ddf.security.assertion.SecurityAssertion)4 SecurityAssertionImpl (ddf.security.assertion.impl.SecurityAssertionImpl)4 Subject (ddf.security.Subject)3 IOException (java.io.IOException)3 HttpServletResponse (javax.servlet.http.HttpServletResponse)3 Subject (org.apache.shiro.subject.Subject)3 HandlerResult (org.codice.ddf.security.handler.api.HandlerResult)3 Test (org.junit.Test)3 SessionFactory (ddf.security.http.SessionFactory)2 SecurityManager (ddf.security.service.SecurityManager)2 SecurityServiceException (ddf.security.service.SecurityServiceException)2 ArrayList (java.util.ArrayList)2 Enumeration (java.util.Enumeration)2 HashMap (java.util.HashMap)2 FilterChain (javax.servlet.FilterChain)2 ServletException (javax.servlet.ServletException)2