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.callistasoftware.netcare.core.spi.impl.ServiceSupport.java

/**
 * Get the current logged in user/*from   ww  w .j a v  a2s.co  m*/
 * @return
 */
protected UserEntity getCurrentUser() {
    this.log.debug("Get current logged in user...");
    final UserBaseView user = (UserBaseView) SecurityContextHolder.getContext().getAuthentication()
            .getPrincipal();
    if (user != null) {
        this.log.debug("Logged in user found. Fetch from repository {}", user.getUsername());
        final UserEntity u = this.repo.findOne(user.getId());
        if (u == null) {
            throw new IllegalStateException("User with username: " + user.getUsername()
                    + " claimed to be logged in. But the user was not found in persistent storage.");
        } else {
            return u;
        }
    }

    this.log.debug("No currently logged in user. Return null");
    return null;
}

From source file:net.nan21.dnet.core.web.controller.ui.extjs.UiExtjsMainController.java

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

    // if (this.setupParticipants != null) {
    // for (ISetupParticipant sp : setupParticipants) {
    // if (sp.hasWorkToDo()) {
    // response.sendRedirect("/nan21.dnet.core.setup");
    // return null;
    // }//w w w . j  a  va  2 s  .c  o m
    // }
    // }

    try {
        @SuppressWarnings("unused")
        ISessionUser su = (ISessionUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

    } catch (java.lang.ClassCastException e) {
        // TODO: parameterize
        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(SysParams_Core.CORE_LOGO_URL_EXTJS);

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

From source file:org.cloudfoundry.identity.uaa.authentication.LoginServerTokenEndpointFilter.java

@Override
protected void onSuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
        Authentication authResult) throws IOException {
    super.onSuccessfulAuthentication(request, response, authResult);
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (auth instanceof OAuth2Authentication) {
        ((OAuth2Authentication) auth).setAuthenticated(true);
    }/*from w ww.  j a  va2  s .co m*/
}

From source file:ph.fingra.statisticsweb.security.CurrentUserHandlerMethodArgumentResolver.java

@Override
public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer mavContainer,
        NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {

    if (this.supportsParameter(methodParameter)) {

        //Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        //if(!principal.getClass().equals(FingraphUser.class))
        return (FingraphUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    } else {/* w ww.  ja  v a 2s .c om*/
        return WebArgumentResolver.UNRESOLVED;
    }
}

From source file:com.acc.oauth2.HybrisOauth2UserFilter.java

@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
        throws IOException, ServletException {
    final Authentication auth = SecurityContextHolder.getContext().getAuthentication();

    if (containsRole(auth, ROLE_ANONYMOUS) || containsRole(auth, ROLE_CUSTOMERGROUP)
            || containsRole(auth, ROLE_CUSTOMERMANAGERGROUP)) {
        final UserModel userModel = userService.getUserForUID((String) auth.getPrincipal());
        userService.setCurrentUser(userModel);
    }//from   w w w .  j av a  2  s.  c  om
    chain.doFilter(request, response);
}

From source file:com.mothsoft.alexis.security.CurrentUserUtil.java

public static void setSystemUserAuthentication() {
    final UserAuthenticationDetails systemUser = new UserAuthenticationDetails(true);
    SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(systemUser,
            null, UserAuthenticationDetails.ADMIN_AUTHORITIES));
}

From source file:net.nan21.dnet.core.web.controller.ui.extjs.UiExtjsFrameController.java

/**
 * Handler for a frame html page.//from  www.  ja v  a  2  s  . c o  m
 * 
 * @param frame
 * @param request
 * @param response
 * @return
 * @throws Exception
 */
@RequestMapping(value = "/{bundle}/{frameFQN}", method = RequestMethod.GET)
protected ModelAndView home(@PathVariable("frameFQN") String frame, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    try {
        @SuppressWarnings("unused")
        ISessionUser su = (ISessionUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    } catch (java.lang.ClassCastException e) {
        throw new NotAuthorizedRequestException("Not authenticated");
    }

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

    String[] tmp = request.getPathInfo().split("/");
    String frameFQN = tmp[tmp.length - 1];
    String bundle = tmp[tmp.length - 2];
    String[] t = frameFQN.split("\\.");
    String frameName = t[t.length - 1];

    model.put("item", frameFQN);
    model.put("itemSimpleName", frameName);
    model.put("bundle", bundle);

    // get extensions
    model.put("extensions", getExtensionFiles(frameFQN, uiExtjsSettings.getUrlModules()));

    model.put("extensionsContent", getExtensionContent(frameFQN));

    if (Constants.PROP_WORKING_MODE_DEV.equalsIgnoreCase(this.getSettings().get(Constants.PROP_WORKING_MODE))) {

        List<String> listCmp = new ArrayList<String>();
        List<String> listTrl = new ArrayList<String>();

        DependencyLoader loader = this.getDependencyLoader();
        loader.resolveFrameDependencies(bundle, frameName, (String) model.get("shortLanguage"), listCmp,
                listTrl);

        model.put("frameDependenciesCmp", listCmp);
        model.put("frameDependenciesTrl", listTrl);

    } else {
        if (this.cacheFolderWritable == null) {
            synchronized (this) {
                if (this.cacheFolderWritable == null) {

                    if (this.cacheFolder == null) {
                        this.cacheFolder = this.getUiExtjsSettings().getCacheFolder();
                    }

                    File cf = new File(this.cacheFolder);
                    if (!cf.exists()) {

                        if (!cf.mkdirs()) {
                            throw new Exception("Cache folder " + this.cacheFolder
                                    + " does not exist and could not be created.");
                        }
                    }

                    if (!cf.isDirectory() || !cf.canWrite()) {
                        throw new Exception("Cache folder " + this.cacheFolder
                                + " is not writeable. Cannot pack and cache the frame dependencies for the configured `prod` working mode. ");
                    }
                    this.cacheFolderWritable = true;
                }
            }
        }
    }
    return new ModelAndView(this.jspName, model);
}

From source file:de.sainth.recipe.backend.rest.controller.RecipeController.java

@Secured({ "ROLE_USER", "ROLE_ADMIN" })
@RequestMapping()//from  w ww  .j av  a2  s.  c  om
HttpEntity<List<Recipe>> getAll() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication instanceof RecipeManagerAuthenticationToken) {
        RecipeManagerAuthenticationToken token = (RecipeManagerAuthenticationToken) authentication;
        if (ROLE_ADMIN.name().equals(token.getRole())) {
            return new ResponseEntity<>(repository.findAll(), HttpStatus.OK);
        } else {
            return new ResponseEntity<>(repository.findAllFor(token.getPrincipal()), HttpStatus.OK);
        }
    }
    return new ResponseEntity<>(HttpStatus.FORBIDDEN);
}

From source file:mx.edu.um.mateo.general.test.BaseTest.java

public Authentication authenticate(UserDetails principal, String credentials,
        List<GrantedAuthority> authorities) {
    Authentication authentication = new TestingAuthenticationToken(principal, credentials, authorities);
    authentication.setAuthenticated(true);
    SecurityContextHolder.getContext().setAuthentication(authentication);
    return authentication;
}

From source file:com.epam.ta.reportportal.ws.BaseMvcTest.java

@Before
public void setup() {
    this.mvcMock = MockMvcBuilders.webAppContextSetup(this.wac).build();
    SecurityContextHolder.getContext().setAuthentication(authentication());
}