Example usage for org.apache.shiro.util ThreadContext getSubject

List of usage examples for org.apache.shiro.util ThreadContext getSubject

Introduction

In this page you can find the example usage for org.apache.shiro.util ThreadContext getSubject.

Prototype

public static Subject getSubject() 

Source Link

Document

Convenience method that simplifies retrieval of a thread-bound Subject.

Usage

From source file:com.stormpath.shiro.servlet.event.LogoutEventListener.java

License:Apache License

/**
 * Logs out the current Subject (if any) when a {@link LogoutRequestEvent} is published.
 * @param event The logout event./*w  ww .  j  a  v a 2s  . c  o m*/
 */
@Subscribe
public void onLogout(LogoutRequestEvent event) {
    Subject subject = ThreadContext.getSubject();
    if (subject != null) {
        subject.logout();
    }
}

From source file:ddf.security.common.audit.SecurityLogger.java

License:Open Source License

private static String getUser(Subject subject) {
    try {/*w  w  w .  java 2 s  . c om*/
        if (subject == null) {
            subject = ThreadContext.getSubject();
        }
        if (subject == null) {
            javax.security.auth.Subject javaSubject = javax.security.auth.Subject
                    .getSubject(AccessController.getContext());
            if (javaSubject != null) {
                Set<UserPrincipal> userPrincipal = javaSubject.getPrincipals(UserPrincipal.class);
                if (userPrincipal != null && !userPrincipal.isEmpty()) {
                    return userPrincipal.toArray(new UserPrincipal[1])[0].getName();
                }
            }
        } else {
            return SubjectUtils.getName(subject, NO_USER);
        }
    } catch (Exception e) {
        // ignore and return NO_USER
    }
    return NO_USER;
}

From source file:ddf.security.common.audit.SecurityLogger.java

License:Open Source License

/**
 * Appends any additional attributes as defined in the comma-delimited system property {@link
 * #EXTRA_ATTRIBUTES_PROP}.// www  .  ja  va  2s . co m
 *
 * @param subject the subject of the logging request
 * @param messageBuilder buffer to which to append attribute text, if any
 */
private static void appendConditionalAttributes(Subject subject, StringBuilder messageBuilder) {
    String attributes = System.getProperty(EXTRA_ATTRIBUTES_PROP);
    if (attributes == null) {
        return;
    }

    if (subject == null) {
        subject = ThreadContext.getSubject();
    }

    List<String> attributeList = Arrays.asList(attributes.split(","));
    for (String attribute : attributeList) {
        List<String> attributeValueList = SubjectUtils.getAttribute(subject, attribute);
        if (CollectionUtils.isNotEmpty(attributeValueList)) {
            messageBuilder.append(" ").append(attribute).append(" : ");
            if (attributeValueList.size() > 1) {
                messageBuilder.append(attributeValueList);
            } else {
                messageBuilder.append(attributeValueList.get(0));
            }
        }
    }
}

From source file:ddf.security.common.util.Security.java

License:Open Source License

/**
 * Returns true if the current subject is implied by the action/permissions passed in. Otherwise
 * returns false. Requires there to be a shiro subject in the current ThreadContext
 *
 * @param action//from   w w  w .  j  a va2  s .  c o  m
 * @param permissions
 * @return
 */
public static boolean authorizeCurrentUser(String action, List<KeyValuePermission> permissions) {
    if (ThreadContext.getSubject() != null || ThreadContext.getSecurityManager() != null) {
        org.apache.shiro.subject.Subject subject = SecurityUtils.getSubject();
        KeyValueCollectionPermission kvcp = new KeyValueCollectionPermission(action, permissions);
        return (subject != null && subject.isPermitted(kvcp));
    }
    return false;
}

From source file:ddf.security.config.impl.ConfigurationSecurityLogger.java

License:Open Source License

@Override
public final void configurationEvent(ConfigurationEvent event) {
    AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
        String type = getType(event);

        // check if there is a subject associated with the configuration change
        if (ThreadContext.getSubject() != null || Subject.getSubject(AccessController.getContext()) != null) {
            SecurityLogger.audit("Configuration {} for {}.", type, event.getPid());
        } else {//from w  w  w. j av a2s  .  com
            // there was no subject change was caused by an update to the config file on the
            // filesystem
            SecurityLogger.auditWarn("Configuration {} via filesystem for {}.", type, event.getPid());
        }
        return null;
    });
}

From source file:ddf.security.interceptor.SecurityLoggerInInterceptor.java

License:Open Source License

@Override
public void handleMessage(Message message) throws Fault {
    if (!MessageUtils.isRequestor(message)) {
        Subject subject = ThreadContext.getSubject();
        if (subject != null) {
            String username = SubjectUtils.getName(subject);
            SecurityLogger.audit("{} is making an inbound request to {}.", username,
                    message.get(Message.REQUEST_URL));
        } else {// ww  w  .  j  a v a 2 s. c o m
            SecurityLogger.audit("No subject associated with inbound request to {}.",
                    message.get(Message.REQUEST_URL));
        }
    }
}

From source file:ddf.security.interceptor.SecurityLoggerOutInterceptor.java

License:Open Source License

@Override
public void handleMessage(Message message) throws Fault {
    if (MessageUtils.isRequestor(message)) {
        Subject subject = ThreadContext.getSubject();
        if (subject != null) {
            String username = SubjectUtils.getName(subject);
            SecurityLogger.audit("{} is making an outbound request.", username);
        } else {// w  w  w .  j ava 2s  . co  m
            SecurityLogger.audit("No subject associated with outbound request.");
        }
    }
}

From source file:io.bootique.shiro.ShiroModuleIT.java

License:Apache License

@Test
public void testFullStack_SecurityUtils() {
    Realm mockRealm = mockRealm();//w w  w. j  av a2s  .com

    BQRuntime runtime = testFactory.app().module(b -> ShiroModule.extend(b).addRealm(mockRealm))
            .autoLoadModules().createRuntime();

    Subject subject = new Subject.Builder(runtime.getInstance(SecurityManager.class)).buildSubject();

    assertNull(ThreadContext.getSubject());

    // testing Shiro idiom of wrapping lambda in a subject...
    subject.execute(() -> {
        assertSame("Unexpected subject, thread state is disturbed", subject, SecurityUtils.getSubject());
    });
}

From source file:org.apache.aries.jax.rs.shiro.authc.impl.SecurityManagerAssociatingFilter.java

License:Apache License

/**
 * Clean up after the request/* w ww.j  av  a  2  s  .c  o m*/
 */
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
        throws IOException {
    _LOG.debug("Cleaning up the Shiro Security Context");
    Subject subject = ThreadContext.getSubject();
    ThreadContext.unbindSecurityManager();
    ThreadContext.unbindSubject();

    if (subject != null && !subject.isAuthenticated()) {
        // Not authenticated. Check for incoming session cookie
        Cookie cookie = requestContext.getCookies().get(SESSION_COOKIE_NAME);

        // If we have a session cookie then it should be deleted
        if (cookie != null) {
            _LOG.debug(
                    "The subject associated with this request is not authenticated, removing the session cookie");
            responseContext.getHeaders().add(SET_COOKIE, getDeletionCookie(requestContext));
        }
    }

}

From source file:org.codice.ddf.security.handler.cas.CasLogoutService.java

License:Open Source License

@GET
@Path("/logout")
public void sendLogoutRequest(@Context HttpServletRequest request, @Context HttpServletResponse response) {
    response.setHeader("Cache-Control", "no-cache, no-store");
    response.setHeader("Pragma", "no-cache");
    response.setContentType("text/html");

    UriBuilder redirectPage = UriBuilder.fromUri(casServerLogoutUrl);
    HttpSession session = request.getSession(false);
    if (session != null) {
        SecurityTokenHolder savedToken = (SecurityTokenHolder) session
                .getAttribute(SecurityConstants.SAML_ASSERTION);
        if (savedToken != null) {
            Subject subject = ThreadContext.getSubject();
            if (subject != null) {
                boolean hasSecurityAuditRole = Arrays
                        .stream(System.getProperty("security.audit.roles", "").split(","))
                        .filter(subject::hasRole).findFirst().isPresent();
                if (hasSecurityAuditRole) {
                    SecurityLogger.audit("Subject with admin privileges has logged out", subject);
                }//from   w w w. j  a v  a2  s  . c  om
            }
            savedToken.removeAll();
        }
        session.invalidate();
    }

    try {
        response.sendRedirect(redirectPage.build().toString());
    } catch (IOException e) {
        LOGGER.warn("Failed to send redirect: ", e);
    }
}