Search in sources :

Example 71 with Subject

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);
    }
}
Also used : PersistentItem(org.codice.ddf.persistence.PersistentItem) HashMap(java.util.HashMap) ServerMessage(org.cometd.bayeux.server.ServerMessage) Subject(ddf.security.Subject) JSONContext(org.cometd.common.JSONContext) ServerMessageImpl(org.cometd.server.ServerMessageImpl) StringReader(java.io.StringReader) PersistenceException(org.codice.ddf.persistence.PersistenceException) ParseException(java.text.ParseException) Jackson1JSONContextServer(org.cometd.server.Jackson1JSONContextServer) Jackson1JSONContextClient(org.cometd.common.Jackson1JSONContextClient) HashMap(java.util.HashMap) Map(java.util.Map) Listener(org.cometd.annotation.Listener)

Example 72 with Subject

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);
}
Also used : SecurityToken(org.apache.cxf.ws.security.tokenstore.SecurityToken) Iterator(java.util.Iterator) UPAuthenticationToken(org.codice.ddf.security.handler.api.UPAuthenticationToken) PrincipalCollection(org.apache.shiro.subject.PrincipalCollection) SecurityAssertion(ddf.security.assertion.SecurityAssertion) Subject(ddf.security.Subject)

Example 73 with 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();
}
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 74 with Subject

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;
}
Also used : QueryResponse(ddf.catalog.operation.QueryResponse) Response(javax.ws.rs.core.Response) WebClient(org.apache.cxf.jaxrs.client.WebClient) Subject(ddf.security.Subject) InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException) CswException(org.codice.ddf.spatial.ogc.csw.catalog.common.CswException) MalformedURLException(java.net.MalformedURLException) StopProcessingException(ddf.catalog.plugin.StopProcessingException) UnknownHostException(java.net.UnknownHostException)

Example 75 with Subject

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();
}
Also used : FilterChain(javax.servlet.FilterChain) ServletException(javax.servlet.ServletException) ContextPolicy(org.codice.ddf.security.policy.context.ContextPolicy) CollectionPermission(ddf.security.permission.CollectionPermission) Collection(java.util.Collection) KeyValuePermission(ddf.security.permission.KeyValuePermission) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) HashMap(java.util.HashMap) Test(org.junit.Test) Subject(ddf.security.Subject) Mockito.when(org.mockito.Mockito.when) Matchers.anyString(org.mockito.Matchers.anyString) Matchers.any(org.mockito.Matchers.any) HttpServletRequest(javax.servlet.http.HttpServletRequest) ThreadContext(org.apache.shiro.util.ThreadContext) Map(java.util.Map) FilterConfig(javax.servlet.FilterConfig) SecurityConstants(ddf.security.SecurityConstants) Assert.fail(org.junit.Assert.fail) Collections(java.util.Collections) ContextPolicyManager(org.codice.ddf.security.policy.context.ContextPolicyManager) Mockito.mock(org.mockito.Mockito.mock) Before(org.junit.Before) FilterChain(javax.servlet.FilterChain) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) Subject(ddf.security.Subject) ContextPolicyManager(org.codice.ddf.security.policy.context.ContextPolicyManager) ServletException(javax.servlet.ServletException) HttpServletRequest(javax.servlet.http.HttpServletRequest) FilterConfig(javax.servlet.FilterConfig) CollectionPermission(ddf.security.permission.CollectionPermission) Test(org.junit.Test)

Aggregations

Subject (ddf.security.Subject)94 Test (org.junit.Test)47 SecurityAssertion (ddf.security.assertion.SecurityAssertion)23 SecurityToken (org.apache.cxf.ws.security.tokenstore.SecurityToken)23 HashMap (java.util.HashMap)20 Metacard (ddf.catalog.data.Metacard)18 SecurityManager (ddf.security.service.SecurityManager)14 IOException (java.io.IOException)14 Serializable (java.io.Serializable)14 CollectionPermission (ddf.security.permission.CollectionPermission)13 ArrayList (java.util.ArrayList)12 Map (java.util.Map)12 CreateRequest (ddf.catalog.operation.CreateRequest)11 CreateRequestImpl (ddf.catalog.operation.impl.CreateRequestImpl)11 UnsupportedQueryException (ddf.catalog.source.UnsupportedQueryException)10 SecurityServiceException (ddf.security.service.SecurityServiceException)10 HashSet (java.util.HashSet)10 PrincipalCollection (org.apache.shiro.subject.PrincipalCollection)9 Before (org.junit.Before)9 HttpServletRequest (javax.servlet.http.HttpServletRequest)8