Example usage for org.springframework.security.core.context SecurityContext getAuthentication

List of usage examples for org.springframework.security.core.context SecurityContext getAuthentication

Introduction

In this page you can find the example usage for org.springframework.security.core.context SecurityContext getAuthentication.

Prototype

Authentication getAuthentication();

Source Link

Document

Obtains the currently authenticated principal, or an authentication request token.

Usage

From source file:alpha.portal.webapp.listener.UserCounterListener.java

/**
 * Needed for Acegi Security 1.0, as it adds an anonymous user to the
 * session and then replaces it after authentication.
 * http://forum.springframework.org/showthread.php?p=63593
 * //from  w  w w.j a va2s .c o  m
 * @param event
 *            the session binding event
 * @see javax.servlet.http.HttpSessionAttributeListener#attributeReplaced(javax.servlet.http.HttpSessionBindingEvent)
 */
public void attributeReplaced(final HttpSessionBindingEvent event) {
    if (event.getName().equals(UserCounterListener.EVENT_KEY) && !this.isAnonymous()) {
        final SecurityContext securityContext = (SecurityContext) event.getValue();
        if ((securityContext.getAuthentication() != null)
                && (securityContext.getAuthentication().getPrincipal() instanceof User)) {
            final User user = (User) securityContext.getAuthentication().getPrincipal();
            this.addUsername(user);
        }
    }
}

From source file:org.musicrecital.webapp.listener.UserCounterListener.java

private boolean isAnonymous() {
    AuthenticationTrustResolver resolver = new AuthenticationTrustResolverImpl();
    SecurityContext ctx = SecurityContextHolder.getContext();
    if (ctx != null) {
        Authentication auth = ctx.getAuthentication();
        return resolver.isAnonymous(auth);
    }/*  www  . j  a v  a2  s . co  m*/
    return true;
}

From source file:fr.treeptik.cloudunit.users.UserControllerTestIT.java

@Test
public void test00_userAuthenticatesSuccess() throws Exception {

    logger.info("test00_userAuthenticates");

    final String username = "johndoe";
    mockMvc.perform(post("/user/authentication").param("j_username", username).param("j_password", "abc2015"))
            .andExpect(new ResultMatcher() {
                public void match(MvcResult mvcResult) throws Exception {
                    HttpSession session = mvcResult.getRequest().getSession();
                    SecurityContext securityContext = (SecurityContext) session.getAttribute(SEC_CONTEXT_ATTR);
                    Assert.assertEquals(securityContext.getAuthentication().getName(), username);
                }/*from ww  w .j  av a  2 s .c o  m*/
            });
}

From source file:com.sibvisions.rad.server.security.spring.logout.DestroySessionApplicationListener.java

/**
 * {@inheritDoc}/*from   ww w  . j a v a  2s.c om*/
 */
@Override
public void onApplicationEvent(SessionDestroyedEvent pEvent) {
    List<SecurityContext> securityContexts = pEvent.getSecurityContexts();

    if (securityContexts != null) {
        SecurityContext securityContext = null;

        for (int i = 0, ic = securityContexts.size(); i < ic; i++) {
            securityContext = securityContexts.get(i);

            if (securityContext != null) {
                doLogout(securityContext.getAuthentication());
            }
        }
    }
}

From source file:com.vdenotaris.spring.boot.security.saml.web.CommonTestSupport.java

public MockHttpSession mockAnonymousHttpSession() {
    MockHttpSession mockSession = new MockHttpSession();
    SecurityContext mockSecurityContext = mock(SecurityContext.class);

    AnonymousAuthenticationToken principal = new AnonymousAuthenticationToken(ANONYMOUS_USER_KEY,
            ANONYMOUS_USER_PRINCIPAL, AUTHORITIES);

    when(mockSecurityContext.getAuthentication()).thenReturn(principal);

    SecurityContextHolder.setContext(mockSecurityContext);
    mockSession.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
            mockSecurityContext);//from  w  w  w. j  a va 2  s  .  c  o m

    return mockSession;
}

From source file:com.cfitzarl.cfjwed.core.security.SecurityContextLoader.java

/**
 * This method is responsible for handling post-request context changes. On each request, we reset the TTL of the
 * authentication data in redis./*from  www. j  a va2s  . co m*/
 *
 * @param context the context to save
 * @param request the request
 * @param response the response
 */
@Override
public void saveContext(SecurityContext context, HttpServletRequest request, HttpServletResponse response) {
    String tokenParam = request.getParameter(SessionConstant.AUTH_TOKEN_HEADER);
    if ((context.getAuthentication() != null) && (tokenParam != null)) {
        redisService.expire(tokenParam, AuthenticationProcessingFilter.SESSION_EXPIRY_SECONDS);
    }
}

From source file:org.jasig.springframework.security.portlet.context.PortletSessionSecurityContextRepositoryTests.java

@Test
public void nonSecurityContextInSessionIsIgnored() throws Exception {
    PortletSessionSecurityContextRepository repo = new PortletSessionSecurityContextRepository();
    MockPortletRequest request = new MockPortletRequest();
    SecurityContextHolder.getContext().setAuthentication(testToken);
    request.getPortletSession().setAttribute(SPRING_SECURITY_CONTEXT_KEY, "NotASecurityContextInstance",
            PortletSession.APPLICATION_SCOPE);
    MockPortletResponse response = new MockPortletResponse();
    PortletRequestResponseHolder holder = new PortletRequestResponseHolder(request, response);
    SecurityContext context = repo.loadContext(holder);
    assertNotNull(context);/*from w w w.  j av  a 2  s  . com*/
    assertNull(context.getAuthentication());
}

From source file:com.sibvisions.rad.server.security.spring.authentication.SecurityManagerPreparer.java

/**
 * Sets additional parameters to the session and authentication object.
 * //from w w w  . j av  a  2  s . c  om
 * @param pRequest the request which is used to get the current session
 */
public void doPrepareParameters(HttpServletRequest pRequest) {
    String absoluteLogoutProcessUrl = buildAbsoluteLogoutProcessUrl(pRequest);

    HttpSession session = pRequest.getSession(false);

    if (session != null) {
        if (session.getAttribute(JVX_SPRINGSECURITY_INITIALIZED) == null) {
            session.setAttribute(SpringSecurityManager.LOGOUT_PROCESS_URL, absoluteLogoutProcessUrl);
            session.setAttribute(JVX_SPRINGSECURITY_INITIALIZED, Boolean.TRUE);
        }
    }

    SecurityContext context = SecurityContextHolder.getContext();

    if (context != null) {
        Authentication authentication = context.getAuthentication();

        if (authentication != null) {
            if (!(authentication instanceof WrappedAuthentication)) {
                authentication = new WrappedAuthentication(authentication);
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }

            if (((WrappedAuthentication) authentication).getProperty(JVX_SPRINGSECURITY_INITIALIZED) == null) {
                ((WrappedAuthentication) authentication).setProperty(SpringSecurityManager.LOGOUT_PROCESS_URL,
                        absoluteLogoutProcessUrl);
                ((WrappedAuthentication) authentication).setProperty(JVX_SPRINGSECURITY_INITIALIZED,
                        Boolean.TRUE);
            }
        }
    }
}

From source file:uk.ac.ebi.emma.manager.AbstractManager.java

protected Session getCurrentSession() {
    if (username == null) {
        SecurityContext securityContext = SecurityContextHolder.getContext();
        if (securityContext == null)
            throw new RuntimeException("AbstractManager.getCurrentSession(): securityContext is null.");
        Authentication authentication = securityContext.getAuthentication();
        if (authentication == null)
            throw new RuntimeException("AbstractManager.getCurrentSession(): authentication is null.");
        String name = authentication.getName();
        if (name == null)
            throw new RuntimeException("AbstractManager.getCurrentSession(): name is null.");
        username = name;// w w  w  . j av  a2 s  .  c  om
    }

    return sessionFactory.getCurrentSession();
}

From source file:cherry.foundation.springmvc.OperationLogHandlerInterceptor.java

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

    Principal principal = request.getUserPrincipal();
    if (principal == null) {
        SecurityContext context = SecurityContextHolder.getContext();
        if (context != null) {
            principal = context.getAuthentication();
        }// ww w. j  av  a 2s  .co m
    }
    if (principal != null) {
        MDC.put(LOGIN_ID, principal.getName());
    }

    StringBuilder builder = createBasicInfo(request);

    builder.append(" {");
    boolean first = true;
    for (Map.Entry<String, String[]> entry : request.getParameterMap().entrySet()) {

        String key = entry.getKey();
        String lkey = key.toLowerCase();
        String[] val = entry.getValue();

        if (!first) {
            builder.append(", ");
        }
        first = false;
        builder.append(key).append(": ");
        if (lkey.contains("password")) {
            builder.append("<MASKED>");
        } else {
            builder.append(ToStringBuilder.reflectionToString(val, ToStringStyle.SIMPLE_STYLE));
        }

        for (int i = 0; i < paramPattern.size(); i++) {
            if (paramPattern.get(i).matcher(lkey).matches()) {
                if (val != null && val.length == 1) {
                    MDC.put(paramMdcKey.get(i), val[0]);
                } else {
                    MDC.put(paramMdcKey.get(i),
                            ToStringBuilder.reflectionToString(val, ToStringStyle.SIMPLE_STYLE));
                }
            }
        }
    }
    builder.append("}");

    loggerEnter.info(builder.toString());

    return true;
}