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:com.boundlessgeo.geoserver.api.controllers.LoginController.java

/**
 * API endpoint for determining if a user is logged in
 * //from ww w.  j av a  2 s .  c  o m
 * @param req HTTP request
 * @param res HTTP response
 * @return JSON object containing the session id, the session timeout interval, 
 * and the GeoServer user, if applicable.
 */
@RequestMapping()
public @ResponseBody JSONObj handle(HttpServletRequest req, HttpServletResponse res) {
    JSONObj obj = new JSONObj();

    HttpSession session = req.getSession(false);
    if (session != null) {
        obj.put("session", session.getId());
        obj.put("timeout", session.getMaxInactiveInterval());
    }

    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    Object principal = auth.getPrincipal();
    if (principal instanceof GeoServerUser) {
        GeoServerUser user = (GeoServerUser) principal;
        obj.put("user", user.getUsername());
        //PKI Authentication
    } else if (auth instanceof PreAuthenticatedAuthenticationToken && principal instanceof String) {
        obj.put("user", principal);
    }

    return obj;
}

From source file:com.restfiddle.controller.AppController.java

@RequestMapping("/")
public String home(Map<String, Object> model) {
    model.put("time", new Date());
    model.put("message", this.message);
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    model.put("currentUser", (authentication == null) ? null : (UserDetails) authentication.getPrincipal());
    return "home";
}

From source file:hu.bme.iit.quiz.controller.QuizController.java

/**
 * *************************************************
 * URL: /quiz/start/{innerkey}//  w  ww .  j a va  2  s  .c  o  m
 * **************************************************
 */
@Secured(value = { "isAuthenticated()" })
@RequestMapping(value = "/quiz/start/{innerkey}", method = RequestMethod.GET)
public String startQuiz(@PathVariable String innerkey) {
    try {
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        int quizPresentationID = quizService.startQuizByInnerKeyForUser(innerkey, user.getUsername());

        return "redirect:/quiz/room/" + quizPresentationID;
    } catch (Exception e) {
        logger.error(e);
        e.printStackTrace();
        return "redirect:/my-quizzes?start-error";
    }
}

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

@WithUserDetails(value = "testuser")
@Test//w  w  w .  j  ava 2  s  .  c om
public void testWithNameOverridenWithUserDetails() {
    assertEquals("testuser", SecurityContextHolder.getContext().getAuthentication().getName());
}

From source file:fm.lastify.web.LastifyFmMeController.java

private String getAuthenticatedUserName() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    return authentication == null ? null : authentication.getName();
}

From source file:no.dusken.aranea.admin.control.WelcomeController.java

protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    Map<String, Object> map = new HashMap<String, Object>();
    map.put("contextPath", request.getRequestURI());
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    String username = authentication.getName();
    Person p = personService.getPersonByUsername(username);
    if (p != null) {
        map.put("loggedInUser", p);
    }// w  w w  . ja v  a 2  s.  c o m

    return new ModelAndView("no/dusken/aranea/base/admin/common/welcome", map);
}

From source file:org.wallride.web.support.AuthorizedUserMethodArgumentResolver.java

@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
        NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    AuthorizedUser authorizedStaff = null;
    if (auth != null && auth.getPrincipal() instanceof AuthorizedUser) {
        authorizedStaff = (AuthorizedUser) auth.getPrincipal();
    }//from   w ww .  ja  va  2s . c  o m
    return authorizedStaff;
}

From source file:org.apigw.authserver.web.viewsupport.HeaderPreparer.java

@Override
public void execute(TilesRequestContext tilesContext, AttributeContext attributeContext) {

    UserDetails user = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

    String fullname = (user instanceof User) ? ((User) user).getFullName() : "";

    Map<String, Object> requestScope = tilesContext.getRequestScope();
    requestScope.put("loggedInAs", user.getUsername());
    requestScope.put("fullname", fullname);
    requestScope.put("relativeLogoutUrl", relativeLogoutUrl);

}

From source file:ru.mera.samples.infrastructure.aop.BeforeAfterLogAdvice.java

@Before("inImageRepositoryEndpoint()")
public void before(JoinPoint joinPoint) {
    final String[] principals = new String[1];
    Optional.of(SecurityContextHolder.getContext())
            .ifPresent(securityContext -> Optional.of(securityContext.getAuthentication())
                    .ifPresent(authentication -> Optional.of(authentication.getPrincipal())
                            .ifPresent(o -> principals[0] = o.toString())));
    logger.info("Before method: " + joinPoint.getSignature().getName() + " by user " + principals);
}

From source file:org.camelcookbook.security.springsecurity.SecurityContextLoader.java

@Override
public void process(Exchange exchange) throws Exception {
    Message in = exchange.getIn();// w  ww.j  a v  a 2 s  .  co  m
    String username = in.getHeader("username", String.class);
    String password = in.getHeader("password", String.class);

    Authentication authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
    SecurityContextHolder.getContext().setAuthentication(authenticationToken);
}