use of ddf.security.Subject in project ddf by codice.
the class UserService method getUser.
@Listener("/service/user")
public void getUser(final ServerSession remote, Message message) {
ServerMessage.Mutable reply = new ServerMessageImpl();
Map<String, Object> data = message.getDataAsMap();
Subject subject = (Subject) bayeux.getContext().getRequestAttribute(SecurityConstants.SECURITY_SUBJECT);
if (subject != null) {
if (data == null || data.isEmpty()) {
Map<String, Object> userMap = new HashMap<>();
String username = SubjectUtils.getName(subject);
userMap.put("username", username);
userMap.put("isGuest", String.valueOf(subject.isGuest()));
List<Map<String, Object>> preferencesList;
try {
preferencesList = persistentStore.get(PersistentStore.PREFERENCES_TYPE, "user = '" + username + "'");
if (preferencesList.size() == 1) {
Map<String, Object> preferences = preferencesList.get(0);
JSONContext.Client jsonContext = new Jackson1JSONContextClient();
String json = (String) preferences.get("preferences_json_txt");
LOGGER.debug("preferences extracted JSON text:\n {}", json);
Map preferencesMap;
try {
preferencesMap = jsonContext.getParser().parse(new StringReader(json), Map.class);
userMap.put("preferences", preferencesMap);
} catch (ParseException e) {
LOGGER.info("ParseException while trying to convert persisted preferences for user {} from JSON", username, e);
}
}
} catch (PersistenceException e) {
LOGGER.info("PersistenceException while trying to retrieve persisted preferences for user {}", username, e);
}
reply.put("user", userMap);
reply.put(Search.SUCCESSFUL, true);
remote.deliver(serverSession, "/service/user", reply);
} else {
JSONContext.Server jsonContext = new Jackson1JSONContextServer();
String json = jsonContext.getGenerator().generate(data);
LOGGER.debug("preferences JSON text:\n {}", json);
String username = SubjectUtils.getName(subject);
PersistentItem item = new PersistentItem();
item.addIdProperty(username);
item.addProperty("user", username);
item.addProperty("preferences_json", json);
try {
persistentStore.add(PersistentStore.PREFERENCES_TYPE, item);
} catch (PersistenceException e) {
LOGGER.info("PersistenceException while trying to persist preferences for user {}", username, e);
}
}
} else {
reply.put(Search.SUCCESSFUL, false);
remote.deliver(serverSession, "/service/user", reply);
}
}
use of ddf.security.Subject in project ddf by codice.
the class AuthenticationEndpointTest method mockUser.
private void mockUser(String username, String password, String realm) throws SecurityServiceException {
Subject subject = mock(Subject.class);
SecurityAssertion securityAssertion = mock(SecurityAssertion.class);
SecurityToken securityToken = mock(SecurityToken.class);
when(securityAssertion.getSecurityToken()).thenReturn(securityToken);
PrincipalCollection collection = mock(PrincipalCollection.class);
Iterator iter = mock(Iterator.class);
when(iter.hasNext()).thenReturn(true, false);
when(iter.next()).thenReturn(securityAssertion);
when(collection.iterator()).thenReturn(iter);
when(subject.getPrincipals()).thenReturn(collection);
UPAuthenticationToken token = new UPAuthenticationToken(username, password, realm);
when(securityManager.getSubject(argThat(new UsernamePasswordTokenMatcher(token)))).thenReturn(subject);
}
use of ddf.security.Subject 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.Subject in project ddf by codice.
the class SendEvent method send.
private boolean send(String operation, CswRecordCollection recordCollection) {
WebClient webClient = cxfClientFactory.getWebClient();
try {
Response response = webClient.invoke(operation, recordCollection);
Subject pingSubject = (Subject) response.getHeaders().getFirst(Subject.class.toString());
if (pingSubject == null && ip != null) {
subject = security.getGuestSubject(ip);
} else {
subject = pingSubject;
}
lastPing = System.currentTimeMillis();
retryCount.set(0);
return true;
} catch (Exception e) {
LOGGER.debug("Error contacting event callback url {}", callbackUrl, e);
lastPing = System.currentTimeMillis();
retryCount.incrementAndGet();
}
return false;
}
use of ddf.security.Subject in project ddf by codice.
the class AuthorizationFilterTest method testAuthorizedSubject.
@Test
public void testAuthorizedSubject() {
FilterConfig filterConfig = mock(FilterConfig.class);
ContextPolicyManager contextPolicyManager = new TestPolicyManager();
contextPolicyManager.setContextPolicy(PATH, getMockContextPolicy());
AuthorizationFilter loginFilter = new AuthorizationFilter(contextPolicyManager);
try {
loginFilter.init(filterConfig);
} catch (ServletException e) {
fail(e.getMessage());
}
Subject subject = mock(Subject.class);
when(subject.isPermitted(any(CollectionPermission.class))).thenReturn(true);
ThreadContext.bind(subject);
HttpServletRequest servletRequest = getMockServletRequest();
HttpServletResponse servletResponse = mock(HttpServletResponse.class);
FilterChain filterChain = (request, response) -> sucess = true;
try {
loginFilter.doFilter(servletRequest, servletResponse, filterChain);
if (!sucess) {
fail("Should have called doFilter with a valid Subject");
}
} catch (IOException | ServletException e) {
fail(e.getMessage());
}
ThreadContext.unbindSubject();
}
Aggregations