Example usage for org.springframework.security.core.context SecurityContextHolder getContext

List of usage examples for org.springframework.security.core.context SecurityContextHolder getContext

Introduction

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

Prototype

public static SecurityContext getContext() 

Source Link

Document

Obtain the current SecurityContext.

Usage

From source file:utilities.AbstractTest.java

public void authenticate(final String username) {
    UserDetails userDetails;//from   w w w.j  a  v  a  2 s . c o  m
    TestingAuthenticationToken authenticationToken;
    SecurityContext context;

    if (username == null)
        authenticationToken = null;
    else {
        userDetails = this.loginService.loadUserByUsername(username);
        authenticationToken = new TestingAuthenticationToken(userDetails, null);
    }

    context = SecurityContextHolder.getContext();
    context.setAuthentication(authenticationToken);
}

From source file:com.mastercard.test.spring.security.WithUserDetailsWith2BeansTests.java

@Test
@WithUserDetails(userDetailsServiceBeanName = "getUserDetailsService1")
public void testWithDefaultWithUserDetails() {
    assertEquals("user", SecurityContextHolder.getContext().getAuthentication().getName());
}

From source file:net.prasenjit.auth.controller.UiController.java

/**
 * <p>dashboard.</p>/*from  w  w w  .j a  v a 2s. c  o  m*/
 *
 * @param model a {@link org.springframework.ui.Model} object.
 * @return a {@link java.lang.String} object.
 */
@RequestMapping("/profile")
public String dashboard(Model model) {
    String userName = SecurityContextHolder.getContext().getAuthentication().getName();
    User user = userService.getUserByName(userName);
    user.getClients().size();
    model.addAttribute("user", user);
    return "profile";
}

From source file:com.github.carlomicieli.nerdmovies.security.SpringSecurityService.java

@Override
public MailUserDetails getCurrentUser() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    return authentication == null ? null : (MailUserDetails) authentication.getPrincipal();
}

From source file:br.com.saude.controle.LoginControle.java

public String logar() {
    usuario = usuarioFacade.buscarUsuario(email, senha);
    if (usuario != null) {
        List<GrantedAuthority> roles = new ArrayList<>();
        roles.add(new GrantedAuthorityImpl(usuario.getPermissaoUsuario().toString()));

        SecurityContext context = SecurityContextHolder.getContext();

        context.setAuthentication(new UsernamePasswordAuthenticationToken(email, senha, roles));
        if (context.getAuthentication().isAuthenticated()) {
            return "/Home?faces-redirect=true";
        } else {//from  www . ja v  a  2s.  com
            //message de erro
            FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Erro", "");
            FacesContext.getCurrentInstance().addMessage(null, message);
            return "Login";
        }
    } else {
        //message de usuario invalido
        FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Usurio Invlido", "");
        FacesContext.getCurrentInstance().addMessage(null, message);
        return "Login";
    }

}

From source file:oobbit.orm.Users.java

public ArrayList<String> getCurrentUserRoles() {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    ArrayList<String> asStrings = new ArrayList<>();

    for (GrantedAuthority authority : auth.getAuthorities()) {
        asStrings.add(authority.getAuthority());
    }/*from w  w w. jav  a  2s.co  m*/

    return asStrings;
}

From source file:cn.org.once.cstack.utils.SecurityContextUtil.java

public UserDetails getPrincipal() {
    logger.debug("Getting principal from the security context");

    UserDetails principal = null;//from   www.jav  a  2  s.c o m

    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

    if (authentication != null) {
        Object currentPrincipal = authentication.getPrincipal();
        if (currentPrincipal instanceof UserDetails) {
            principal = (UserDetails) currentPrincipal;
        }
    }

    return principal;
}

From source file:psiprobe.controllers.apps.AjaxToggleContextController.java

@Override
protected ModelAndView handleContext(String contextName, Context context, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    if (!request.getContextPath().equals(contextName) && context != null) {
        try {//  ww w  .  jav  a2s .  co  m
            // Logging action
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            String name = auth.getName(); // get username logger
            if (context.getState().isAvailable()) {
                logger.info("{} requested STOP of {}", request.getRemoteAddr(), contextName);
                getContainerWrapper().getTomcatContainer().stop(contextName);
                logger.info(getMessageSourceAccessor().getMessage("probe.src.log.stop"), name, contextName);
            } else {
                logger.info("{} requested START of {}", request.getRemoteAddr(), contextName);
                getContainerWrapper().getTomcatContainer().start(contextName);
                logger.info(getMessageSourceAccessor().getMessage("probe.src.log.start"), name, contextName);
            }
        } catch (Exception e) {
            logger.error("Error during ajax request to START/STOP of '{}'", contextName, e);
        }
    }
    return new ModelAndView(getViewName(), "available",
            context != null && getContainerWrapper().getTomcatContainer().getAvailable(context));
}

From source file:org.client.one.service.UserIdentityDetailsService.java

/**
* Returns the domain User object for the currently logged in user, or null
* if no User is logged in./* w w  w. ja va2  s.co m*/
* 
* @return User object for the currently logged in user, or null if no User
*         is logged in.
*/
public static UserIdentity getCurrentUser() {
    SecurityContext sc = SecurityContextHolder.getContext();
    if (sc == null)
        return null;
    if (sc.getAuthentication() == null)
        return null;
    Object principal = sc.getAuthentication().getPrincipal();

    if (principal instanceof UserIdentity)
        return ((UserIdentity) principal);

    // principal object is either null or represents anonymous user -
    // neither of which our domain User object can represent - so return null
    return null;
}

From source file:com.mastercard.test.spring.security.WithMockUserTests.java

@Test
@WithMockUser//www . ja v a  2  s  . co  m
public void testWithDefaultWithMockUser() {
    assertEquals("user", SecurityContextHolder.getContext().getAuthentication().getName());
    assertEquals("password",
            SecurityContextHolder.getContext().getAuthentication().getCredentials().toString());
    assertEquals(1, SecurityContextHolder.getContext().getAuthentication().getAuthorities().size());
    assertEquals("ROLE_USER", SecurityContextHolder.getContext().getAuthentication().getAuthorities().iterator()
            .next().getAuthority());
}