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:org.dataconservancy.ui.stripes.AddCollectionActionBeanTest.java

/**
 * Initialize the mock http session with authenticated user credentials. Tests that re-use this mock session will be
 * already logged in./*from ww w .ja v a2s  .  c  o  m*/
 */
@Before
public void setUpMockttpSessions() throws Exception {

    // Mock a session for a registered, authorized user.
    userSession = new MockHttpSession(servletCtx);
    MockRoundtrip rt = new MockRoundtrip(servletCtx, "/j_spring_security_check", userSession);
    rt.setParameter("j_username", user.getEmailAddress());
    rt.setParameter("j_password", user.getPassword());
    rt.execute();
    SecurityContext ctx = (SecurityContext) userSession
            .getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
    assertNotNull("Spring Security Context was null!", ctx);
    assertEquals(user.getEmailAddress(), ((UserDetails) ctx.getAuthentication().getPrincipal()).getUsername());

    // Mock a session for a system-wide admin user
    adminSession = new MockHttpSession(servletCtx);
    rt = new MockRoundtrip(servletCtx, "/j_spring_security_check", adminSession);
    rt.setParameter("j_username", admin.getEmailAddress());
    rt.setParameter("j_password", admin.getPassword());
    rt.execute();
    ctx = (SecurityContext) adminSession
            .getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
    assertNotNull("Spring Security Context was null!", ctx);
    assertEquals(admin.getEmailAddress(), ((UserDetails) ctx.getAuthentication().getPrincipal()).getUsername());

    modifiedCollection = new Collection();
    modifiedCollection.setId("collectionWithData:/1");
    modifiedCollection.setTitle("Star Wars 2.0");
    modifiedCollection.setSummary("In space...");
    modifiedCollection.setCitableLocator("Nowhere");
    modifiedCollection.setPublicationDate(DateTime.now());
    modifiedCollection.getAlternateIds().add("iWars");
    modifiedCollection.getAlternateIds().add("ID:/2");
    modifiedCollection.addContactInfo(contactInfoOne);
    modifiedCollection.addCreator(creatorOne);

    collectionOne.setId("newID");
    collectionOne.addContactInfo(contactInfoOne);
    collectionOne.addCreator(creatorOne);

    subCollection = new Collection();
    subCollection.setId("SubCollectionId");
    subCollection.setTitle("Child collection title");
    subCollection.setSummary("Child collection summary.");
    subCollection.addCreator(creatorOne);

    // Put the collection attribute on both sessions
    userSession.setAttribute("collection", new Collection(collectionOne));
    adminSession.setAttribute("collection", new Collection(collectionOne));
}

From source file:org.dataconservancy.ui.stripes.DepositActionBeanTest.java

@Before
public void setUpMockttpSessions() throws Exception {

    // Mock a session for a registered, authorized user.
    userSession = new MockHttpSession(servletCtx);
    MockRoundtrip rt = new MockRoundtrip(servletCtx, "/j_spring_security_check", userSession);
    rt.setParameter("j_username", user.getEmailAddress());
    rt.setParameter("j_password", user.getPassword());
    rt.execute();//  w w w.ja v  a 2  s. c om
    SecurityContext ctx = (SecurityContext) userSession
            .getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
    assertNotNull("Spring Security Context was null!", ctx);
    assertEquals(user.getEmailAddress(), ((UserDetails) ctx.getAuthentication().getPrincipal()).getUsername());

    // Mock a session for a system-wide admin user
    adminSession = new MockHttpSession(servletCtx);
    rt = new MockRoundtrip(servletCtx, "/j_spring_security_check", adminSession);
    rt.setParameter("j_username", admin.getEmailAddress());
    rt.setParameter("j_password", admin.getPassword());
    rt.execute();
    ctx = (SecurityContext) adminSession
            .getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
    assertNotNull("Spring Security Context was null!", ctx);
    assertEquals(admin.getEmailAddress(), ((UserDetails) ctx.getAuthentication().getPrincipal()).getUsername());

    // Fix up the collaborating Project
    Project project = new Project();
    project.setId("project:/1");
    project.setStartDate(DateTime.now());
    project.setEndDate(DateTime.now());
    projectDao.insertProject(project);

    adminSession.setAttribute("project_id", project.getId());
}

From source file:org.eclipse.hawkbit.ui.common.UserDetailsFormatter.java

public static UserDetails getCurrentUser() {
    final SecurityContext context = (SecurityContext) VaadinService.getCurrentRequest().getWrappedSession()
            .getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
    return (UserDetails) context.getAuthentication().getPrincipal();
}

From source file:org.mrgeo.services.SecurityUtils.java

public static Properties getProviderProperties() {
    Properties providerProperties = null;
    SecurityContext secCtx = SecurityContextHolder.getContext();
    if (secCtx != null) {
        Authentication a = secCtx.getAuthentication();
        if (a != null) {
            providerProperties = new Properties();
            java.util.Collection<? extends GrantedAuthority> auths = a.getAuthorities();
            String[] roles = new String[auths.size()];
            int i = 0;
            for (GrantedAuthority auth : auths) {
                roles[i] = auth.getAuthority();
                i++;//from   ww  w  .  j  a  v a2 s  .co m
            }
            DataProviderFactory.setProviderProperty(DataProviderFactory.PROVIDER_PROPERTY_USER_NAME,
                    a.getName(), providerProperties);
            DataProviderFactory.setProviderProperty(DataProviderFactory.PROVIDER_PROPERTY_USER_ROLES,
                    StringUtils.join(roles, ","), providerProperties);
        }
    }
    return providerProperties;
}

From source file:org.nimbustools.ctxbroker.rest.BrokerResource.java

private String getCallerDn() {
    final SecurityContext context = SecurityContextHolder.getContext();

    final Authentication auth = context.getAuthentication();
    final QueryUser principal = (QueryUser) auth.getPrincipal();

    return principal.getDn();
}

From source file:org.onehippo.forge.security.support.springsecurity.container.SpringSecurityValve.java

@Override
public void invoke(ValveContext context) throws ContainerException {
    HttpServletRequest request = context.getServletRequest();
    Principal userPrincipal = request.getUserPrincipal();

    // If user has not been authenticated yet by any mechanism, then simply move to the next valve chain.
    if (userPrincipal == null) {
        if (log.isDebugEnabled()) {
            log.debug("No user principal found. Skipping SpringSecurityValve...");
        }//from   ww  w . j  a  v a2s  . c o m
        context.invokeNext();
        return;
    }

    // Get the current subject from http session if exists.
    HttpSession session = request.getSession(false);
    Subject subject = (session != null ? (Subject) session.getAttribute(ContainerConstants.SUBJECT_ATTR_NAME)
            : null);

    // If a subject has been established already (normally by HST-2's SecurityValve), then simply move to the next valve chain.
    if (subject != null) {
        if (log.isDebugEnabled()) {
            log.debug("Already subject has been created somewhere before. Skipping SpringSecurityValve...");
        }
        context.invokeNext();
        return;
    }

    // Get Spring Security Context object from thread local.
    SecurityContext securityContext = SecurityContextHolder.getContext();

    // If there's no Spring Security Context object, then just move to next valve chain.
    if (securityContext == null) {
        if (log.isDebugEnabled()) {
            log.debug("Spring Security hasn't established security context. Skipping SpringSecurityValve...");
        }
        context.invokeNext();
        return;
    }

    // Get the Authentication object from the Spring Security context object.
    Authentication authentication = securityContext.getAuthentication();

    // If there's no Authentication object, it's really weird, so leave warning logs, and move to next valve chain.
    if (authentication == null) {
        if (log.isWarnEnabled()) {
            log.warn(
                    "Spring Security hasn't establish security context with authentication object. Skipping SpringSecurityValve...");
        }
        context.invokeNext();
        return;
    }

    // Get principal object from the Spring Security authentication object.
    Object springSecurityPrincipal = authentication.getPrincipal();

    // We expect the principal is instance of UserDetails. Otherwise, let's skip it and leave warning logs.
    if (!(springSecurityPrincipal instanceof UserDetails)) {
        if (log.isWarnEnabled()) {
            log.warn(
                    "Spring Security hasn't establish security context with UserDetails object. We don't support non UserDetails authentication. Skipping SpringSecurityValve...");
        }
        context.invokeNext();
        return;
    }

    // Cast principal instance to UserDetails 
    UserDetails userDetails = (UserDetails) springSecurityPrincipal;

    // Create HST-2 TransientUser principal from the user principal.
    User user = new TransientUser(userPrincipal.getName());

    // Add both the existing user principal and new HST-2 user transient user principal
    // just for the case when HST-2 can inspect the user principals for some reasons.
    Set<Principal> principals = new HashSet<Principal>();
    principals.add(userPrincipal);
    principals.add(user);

    // Retrieve all the granted authorities from the UserDetail instance
    // and convert it into HST-2 TransientRoles.
    for (GrantedAuthority authority : userDetails.getAuthorities()) {
        String authorityName = authority.getAuthority();
        if (!StringUtils.isEmpty(authorityName)) {
            principals.add(new TransientRole(authorityName));
        }
    }

    Set<Object> pubCred = new HashSet<Object>();
    Set<Object> privCred = new HashSet<Object>();

    // If the flag is turned on, then store JCR credentials as well
    // just for the case the site is expected to use session stateful JCR sessions per authentication.
    if (storeSubjectRepositoryCredentials) {
        Credentials subjectRepoCreds = null;

        // Note: password should be null by default from some moment after Spring Security version upgraded a while ago.
        //       if password is null, let's store a dummy password instead.

        if (userDetails.getPassword() != null) {
            subjectRepoCreds = new SimpleCredentials(userDetails.getUsername(),
                    userDetails.getPassword().toCharArray());
        } else {
            subjectRepoCreds = new SimpleCredentials(userDetails.getUsername(), DUMMY_CHARS);
        }

        privCred.add(subjectRepoCreds);
    }

    subject = new Subject(true, principals, pubCred, privCred);

    // Save the created subject as http session attribute which can be read by HST-2 SecurityValve in the next valve chain.
    request.getSession(true).setAttribute(ContainerConstants.SUBJECT_ATTR_NAME, subject);

    context.invokeNext();
}

From source file:org.openregistry.core.audit.SpringSecurityListener.java

public void newRevision(final Object o) {
    final SpringSecurityRevisionEntity entity = (SpringSecurityRevisionEntity) o;
    final SecurityContext context = SecurityContextHolder.getContext();
    final String comments = ChangeComments.getComments();

    //        entity.setUsername("anonymous");

    if (context != null) {
        if (context.getAuthentication() != null) {
            entity.setUsername(context.getAuthentication().getName());
        } else {/*  w  w w. ja  va  2  s  . c o m*/
            //for non secure interfaces e.g. batch
            entity.setUsername("anonymous");
        }
    }

    if (StringUtils.isNotBlank(comments)) {
        entity.setComments(comments);
    }
}

From source file:org.patientview.patientview.controller.lookinglocal.LookingLocalHomeController.java

/**
 * Deal with the URIs "/lookinglocal/auth", check POSTed credentials
 * @param request HTTP request/*w w w  . j a  va  2s . c om*/
 * @param response HTTP response
 * @param username User entered username
 * @param password User entered password
 */
@RequestMapping(value = Routes.LOOKING_LOCAL_AUTH)
@ResponseBody
public void getAuth(HttpServletRequest request,
        @RequestParam(value = "username", required = false) String username,
        @RequestParam(value = "password", required = false) String password, HttpServletResponse response) {
    LOGGER.debug("auth start");

    PatientViewPasswordEncoder encoder = new PatientViewPasswordEncoder();
    User user = securityUserManager.get(username);

    if (user != null) {
        if (user.getPassword().equals(encoder.encode(password))) {

            // Authenticate user manually
            SecurityUser userLogin = (SecurityUser) userDetailsService.loadUserByUsername(username);
            SecurityContext securityContext = SecurityContextHolder.getContext();
            securityContext.setAuthentication(new UsernamePasswordAuthenticationToken(userLogin,
                    userLogin.getPassword(), userLogin.getAuthorities()));

            // manage extra authentication success handlers manually (usually
            // managed by PatientViewAuthenticationSuccessHandler.onAuthenticationSuccess)
            SecurityUser securityUser = (SecurityUser) securityContext.getAuthentication().getPrincipal();
            List<SpecialtyUserRole> specialtyUserRoles = userManager.getSpecialtyUserRoles(user);

            if (CollectionUtils.isNotEmpty(specialtyUserRoles)) {
                Specialty specialty = specialtyUserRoles.get(0).getSpecialty();
                securityUser.setSpecialty(specialty);
                // manually add to session
                HttpSession session = request.getSession(true);
                session.setAttribute("SPRING_SECURITY_CONTEXT", securityContext);
                LOGGER.debug("auth passed");
                try {
                    LookingLocalUtils.getAuthXml(response);
                } catch (Exception e) {
                    LOGGER.error("Could not create home screen response output stream{}" + e);
                }

            } else {
                LOGGER.debug("auth failed, no specialties");
                try {
                    LookingLocalUtils.getErrorXml(response);
                } catch (Exception e) {
                    LOGGER.error("Could not create home screen response output stream{}" + e);
                }
            }
        } else {
            LOGGER.debug("auth failed, password");
            try {
                LookingLocalUtils.getErrorXml(response);
            } catch (Exception e) {
                LOGGER.error("Could not create home screen response output stream{}" + e);
            }
        }
    } else {
        LOGGER.debug("auth failed, user null");
        try {
            LookingLocalUtils.getErrorXml(response);
        } catch (Exception e) {
            LOGGER.error("Could not create home screen response output stream{}" + e);
        }
    }
}

From source file:org.slc.sli.api.service.BasicServiceTest.java

private void setPrincipalInContext(SLIPrincipal principal) {
    Authentication authentication = Mockito.mock(Authentication.class);
    Mockito.when(authentication.getPrincipal()).thenReturn(principal);
    SecurityContext context = Mockito.mock(SecurityContext.class);
    Mockito.when(context.getAuthentication()).thenReturn(authentication);
    SecurityContextHolder.setContext(context);
}

From source file:org.springframework.security.authentication.jaas.AbstractJaasAuthenticationProvider.java

/**
 * Handles the logout by getting the security contexts for the destroyed session and
 * invoking {@code LoginContext.logout()} for any which contain a
 * {@code JaasAuthenticationToken}./*  w ww.  j  a  va  2 s.c o  m*/
 *
 *
 * @param event the session event which contains the current session
 */
protected void handleLogout(SessionDestroyedEvent event) {
    List<SecurityContext> contexts = event.getSecurityContexts();

    if (contexts.isEmpty()) {
        this.log.debug("The destroyed session has no SecurityContexts");

        return;
    }

    for (SecurityContext context : contexts) {
        Authentication auth = context.getAuthentication();

        if ((auth != null) && (auth instanceof JaasAuthenticationToken)) {
            JaasAuthenticationToken token = (JaasAuthenticationToken) auth;

            try {
                LoginContext loginContext = token.getLoginContext();
                boolean debug = this.log.isDebugEnabled();
                if (loginContext != null) {
                    if (debug) {
                        this.log.debug("Logging principal: [" + token.getPrincipal() + "] out of LoginContext");
                    }
                    loginContext.logout();
                } else if (debug) {
                    this.log.debug("Cannot logout principal: [" + token.getPrincipal() + "] from LoginContext. "
                            + "The LoginContext is unavailable");
                }
            } catch (LoginException e) {
                this.log.warn("Error error logging out of LoginContext", e);
            }
        }
    }
}