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();
}
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;
}
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();
}
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");
}
Aggregations