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:org.georchestra.security.SecurityRequestHeaderProvider.java

@Override
protected Collection<Header> getCustomRequestHeaders(HttpSession session, HttpServletRequest originalRequest) {

    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
    List<Header> headers = new ArrayList<Header>();
    if (authentication.getName().equals("anonymousUser"))
        return headers;
    headers.add(new BasicHeader(HeaderNames.SEC_USERNAME, authentication.getName()));
    StringBuilder roles = new StringBuilder();
    for (GrantedAuthority grantedAuthority : authorities) {
        if (roles.length() != 0)
            roles.append(";");

        roles.append(grantedAuthority.getAuthority());
    }//from   w  w  w.  ja  v a 2s  .  com
    headers.add(new BasicHeader(HeaderNames.SEC_ROLES, roles.toString()));

    return headers;
}

From source file:com.parking.rest.resources.VehicleResource.java

@GET
@Linkable(LinkableIds.VEHICLES_LIST_ID)/*from   w  ww. j  a v a  2s .c o  m*/
@Produces(MediaType.APPLICATION_JSON)
public Response list() {
    Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    if (principal instanceof UserDetails) {
        UserDetails details = (UserDetails) principal;
        Account loggedAccount = accountService.findByName(details.getUsername());
        try {
            List<Vehicle> allEntries = this.vehicleService.findAllVehicleByAccount(loggedAccount);
            return HateoasResponse.ok(VehicleDto.fromBeanCollection(allEntries))
                    .selfLink(LinkableIds.VEHICLE_NEW_ID).selfEach(LinkableIds.VEHICLE_DETAILS_ID, "id")
                    .build();
        } catch (AccountDoesNotExistException exception) {
            throw new NotFoundException();
        }
    } else {
        throw new ForbiddenException();
    }
}

From source file:com.greglturnquist.payroll.SpringDataRestEventHandler.java

@HandleBeforeCreate
public void applyUserInformationUsingSecurityContext(Employee employee) {

    String name = SecurityContextHolder.getContext().getAuthentication().getName();
    Manager manager = this.managerRepository.findByName(name);
    if (manager == null) {
        Manager newManager = new Manager();
        newManager.setName(name);//from   w  ww. ja va  2  s  . c  o  m
        newManager.setRoles(new String[] { "ROLE_MANAGER" });
        manager = this.managerRepository.save(newManager);
    }
    employee.setManager(manager);
}

From source file:cs544.blog.controller.MainController.java

@RequestMapping(value = "/mainPage", method = RequestMethod.GET)
public String getMainPage(Model model) {
    String username = SecurityContextHolder.getContext().getAuthentication().getName();
    System.err.println("username " + username);
    //        boolean isLogged = true;
    //        if (username.equals("anonymousUser")){
    //            isLogged =false;
    //        }// ww w .  j av a2  s. co m
    model.addAttribute("posts", blogService.getAllPost());
    //        System.err.println(userService.getAllUser() );
    //model.addAttribute("isLogged",isLogged);
    model.addAttribute("username", username);
    return "mainPage";
}

From source file:be.bittich.quote.service.impl.SecurityServiceImpl.java

@Override
public User getUserFromSecurityContext() {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    checkNotNull(auth, "Erreur: Utilisateur non connect");
    return userService.findOneByUsername(auth.getPrincipal().toString());
}

From source file:seava.j4e.web.controller.ui.extjs.UiExtjsMainController.java

@RequestMapping(value = "*", method = RequestMethod.GET)
protected ModelAndView home(HttpServletRequest request, HttpServletResponse response) throws Exception {

    try {/*from   w  w  w  .  j a  va  2 s .  c om*/
        ISessionUser su = (ISessionUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        if (su.isSessionLocked()) {
            throw new BusinessException(ErrorCode.SEC_SESSION_LOCKED, "Session has been locked.");
        }
    } catch (Exception e) {
        response.sendRedirect(this.getSettings().get(Constants.PROP_LOGIN_PAGE));
        return null;
    }

    Map<String, Object> model = new HashMap<String, Object>();
    this._prepare(model, request, response);

    /* ========== extensions =========== */

    model.put("extensions", getExtensionFiles(IExtensions.UI_EXTJS_MAIN, uiExtjsSettings.getUrlCore()));

    model.put("extensionsContent", getExtensionContent(IExtensions.UI_EXTJS_MAIN));

    String logo = this.getSettings().getParam(SysParam.CORE_LOGO_URL_EXTJS.name());

    if (logo != null && !logo.equals("")) {
        model.put("logo", logo);
    }
    return new ModelAndView(this.viewName, model);
}

From source file:com.github.cherimojava.orchidae.security.authenticator.PictureAccessAuthenticator.java

/**
 * performs the access validation. Returns true if the picture is owned by the current user or is public
 * //from   w  w w.  ja  v  a  2s. c  o  m
 * @param id
 * @return
 */
public boolean hasAccess(String id) {
    String user = (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    Picture pic = factory.load(Picture.class, id);
    return pic != null && (pic.getUser().getUsername().equals(user) || Access.PUBLIC.equals(pic.getAccess()));
}

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

@Override
@Transactional(readOnly = true)/*from  w w  w .j av  a2s.c  o  m*/
public User getCurrentUser() {
    SecurityContext securityContext = SecurityContextHolder.getContext();
    if (securityContext != null) {
        String email = securityContext.getAuthentication().getName();
        return userRepos.findByEmail(email);
    }

    return null;
}

From source file:org.unidle.repository.AuditorAwareImpl.java

@Override
public User getCurrentAuditor() {

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

    if (authentication == null) {
        return null;
    }/*from   w w  w  .  j  a va  2s. co m*/

    final String uuid = authentication.getName();

    return "".equals(uuid) ? null : userRepository.findOne(UUID.fromString(uuid));
}

From source file:org.softdays.mandy.web.security.AuthService.java

/**
 * Gets the current token.//  w  w  w  .j  a  v  a  2s.  co  m
 * 
 * @return the current token
 */
public ResourceDto getCurrentToken() {
    final SecurityContext ctx = SecurityContextHolder.getContext();
    final MyUser user = (MyUser) ctx.getAuthentication().getPrincipal();

    return user == null ? null : user.getResource();
}