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:dicky.controlleradmin.MainController.java

@RequestMapping(value = "/403", method = RequestMethod.GET)
public String accessDenied(ModelMap modelMap) {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (!(auth instanceof AnonymousAuthenticationToken)) {
        UserDetails userDetails = (UserDetails) auth.getPrincipal();
        modelMap.addAttribute("username", userDetails.getUsername());
    }//from  ww  w.  j  av  a  2  s.  c om
    return "admin.main.403";
}

From source file:com.vaadinspring.components.CustomAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    String name = authentication.getName();
    String password = authentication.getCredentials().toString();
    Users user = userPresenter.getUser(name);
    if (user.getLogin() != null && password.equals(user.getPassword())) {
        List<GrantedAuthority> grantedAuths = new ArrayList<GrantedAuthority>(1);
        grantedAuths.add(new SimpleGrantedAuthority(user.getRole().getRole_name()));
        Authentication auth = new UsernamePasswordAuthenticationToken(name, password, grantedAuths);
        SecurityContextHolder.getContext().setAuthentication(auth);
        return auth;
    } else {/* w  ww.j  a v  a2  s. c  om*/
        return null;
    }
}

From source file:org.ff4j.security.test.FlipSecurityTests.java

@Before
public void setUp() throws Exception {
    securityCtx = SecurityContextHolder.getContext();
    // Init SpringSecurity Context
    SecurityContext context = new SecurityContextImpl();
    List<GrantedAuthority> listOfRoles = new ArrayList<GrantedAuthority>();
    listOfRoles.add(new SimpleGrantedAuthority("ROLE_USER"));
    User u1 = new User("user1", "user1", true, true, true, true, listOfRoles);
    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(u1.getUsername(),
            u1.getPassword(), u1.getAuthorities());
    token.setDetails(u1);//from   www.ja  va 2s  . c o  m
    context.setAuthentication(token);
    SecurityContextHolder.setContext(context);
    // <--

    ff4j = new FF4j("test-ff4j-security-spring.xml");
    ff4j.setAuthorizationsManager(new SpringSecurityAuthorisationManager());
}

From source file:org.watterssoft.appsupport.user.ui.AuthenicatedUserController.java

@RequestMapping(value = "/retrieve", method = RequestMethod.GET, produces = "application/json")
public @ResponseBody UserRoles authenticatedUser() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

    if (authentication == null || !(authentication.getPrincipal() instanceof UserDetails)) {
        return null;
    }//from  w  ww .  j  a va  2  s  . c  o  m
    UserDetails userDetails = (UserDetails) authentication.getPrincipal();
    Collection<? extends GrantedAuthority> authorities = userDetails.getAuthorities();
    ArrayList<GrantedAuthority> grantedRoles = new ArrayList<GrantedAuthority>(authorities);
    UserRoles userRoles = new UserRoles(userDetails.getUsername(), grantedRoles);
    return userRoles;
}

From source file:fr.mycellar.interfaces.web.security.CurrentUserService.java

/**
 * @return/* w w w . jav a 2s.c om*/
 */
public String getCurrentUserEmail() {
    String email = null;
    SecurityContext context = SecurityContextHolder.getContext();
    if (context != null) {
        Authentication auth = context.getAuthentication();
        if ((auth != null) && auth.isAuthenticated() && !(auth instanceof AnonymousAuthenticationToken)) {
            email = auth.getName();
        }
    }
    return email;
}

From source file:org.apache.cxf.fediz.service.idp.service.jpa.ConfigServiceJPA.java

@Override
public Idp getIDP(String realm) {
    Authentication currentAuthentication = SecurityContextHolder.getContext().getAuthentication();
    try {//w ww . ja  v a2  s.  c om
        final Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();

        if (realm == null || realm.length() == 0) {
            authorities.add(new SimpleGrantedAuthority("IDP_LIST"));
            UsernamePasswordAuthenticationToken technicalUser = new UsernamePasswordAuthenticationToken(
                    "IDP_TEST", "N.A", authorities);

            SecurityContextHolder.getContext().setAuthentication(technicalUser);

            return idpService.getIdps(0, 1, Arrays.asList("all"), null).getIdps().iterator().next();
        } else {
            authorities.add(new SimpleGrantedAuthority("IDP_READ"));
            UsernamePasswordAuthenticationToken technicalUser = new UsernamePasswordAuthenticationToken(
                    "IDP_TEST", "N.A", authorities);

            SecurityContextHolder.getContext().setAuthentication(technicalUser);

            return idpService.getIdp(realm, Arrays.asList("all"));
        }
    } finally {
        SecurityContextHolder.getContext().setAuthentication(currentAuthentication);
        LOG.info("Old Spring security context restored");
    }
}

From source file:com.gsr.myschool.server.security.SecurityContextProviderImpl.java

@Override
@Transactional(readOnly = true)/* ww  w .j av  a 2 s  . c o  m*/
public AdminUser getCurrentAdmin() {
    SecurityContext securityContext = SecurityContextHolder.getContext();
    if (securityContext != null) {
        String email = securityContext.getAuthentication().getName();
        return adminUserRepos.findByEmail(email);
    }

    return null;
}

From source file:de.hska.ld.content.events.document.DocumentEventsPublisher.java

private String extractAuthenticationInformation() {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    OIDCAuthenticationToken token = (OIDCAuthenticationToken) auth;
    return token.getAccessTokenValue();
}

From source file:eu.trentorise.smartcampus.permissionprovider.authority.CASAuthorityHandler.java

@SuppressWarnings("unchecked")
@Override//w w  w .j  a va  2s .  c  o m
public Map<String, String> extractAttributes(HttpServletRequest request, Map<String, String> map,
        AuthorityMapping mapping) {
    Map<String, String> attrs = new HashMap<String, String>();

    CasAuthenticationToken token = (CasAuthenticationToken) SecurityContextHolder.getContext()
            .getAuthentication();
    String username = token.getName();
    Map<String, Object> tokenAttrs = token.getAssertion().getAttributes();
    if (tokenAttrs == null) {
        tokenAttrs = new HashMap<String, Object>();
    }
    tokenAttrs.put(USERNAME, username);

    for (String key : mapping.getIdentifyingAttributes()) {
        Object value = readAttribute(key, tokenAttrs);
        if (value != null) {
            attrs.put(key, value.toString());
        }
    }
    for (Attributes attribute : mapping.getAttributes()) {
        // used alias if present to set attribute in map
        String key = (attribute.getAlias() != null && !attribute.getAlias().isEmpty()) ? attribute.getAlias()
                : attribute.getValue();
        Object value = readAttribute(attribute.getValue(), tokenAttrs);
        if (value != null) {
            attrs.put(key, value.toString());
        }
    }
    return attrs;
}

From source file:io.syndesis.rest.v1.handler.user.UserHandler.java

@Path("~")
@GET//ww w  . j  av  a2 s  . c om
@Produces(MediaType.APPLICATION_JSON)
public User whoAmI() {
    String token = String.valueOf(SecurityContextHolder.getContext().getAuthentication().getCredentials());
    io.fabric8.openshift.api.model.User openShiftUser = this.openShiftService.whoAmI(token);
    Assert.notNull(openShiftUser, "A valid user is required");
    return new User.Builder().username(openShiftUser.getMetadata().getName())
            .fullName(Optional.ofNullable(openShiftUser.getFullName()))
            .name(Optional.ofNullable(openShiftUser.getFullName())).build();
}