Example usage for org.springframework.security.core Authentication getPrincipal

List of usage examples for org.springframework.security.core Authentication getPrincipal

Introduction

In this page you can find the example usage for org.springframework.security.core Authentication getPrincipal.

Prototype

Object getPrincipal();

Source Link

Document

The identity of the principal being authenticated.

Usage

From source file:org.jblogcms.core.security.service.SecurityServiceImpl.java

@Override
public Long getCurrentAccountId() {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    try {//  w ww .j a  va 2 s . c  om
        if (!auth.getName().equals("anonymousUser")) {
            return ((AccountDetails) auth.getPrincipal()).getId();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.artivisi.belajar.restful.ui.controller.HomepageController.java

@RequestMapping("/homepage/userinfo")
@ResponseBody//from   w  w  w .  j  a v a  2 s .com
public Map<String, String> userInfo() {
    Map<String, String> hasil = new HashMap<String, String>();

    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (auth != null) {
        Object principal = auth.getPrincipal();
        if (principal != null && User.class.isAssignableFrom(principal.getClass())) {
            User u = (User) principal;
            hasil.put("user", u.getUsername());
            com.artivisi.belajar.restful.domain.User ux = belajarRestfulService
                    .findUserByUsername(u.getUsername());
            if (ux != null || ux.getRole() != null || ux.getRole().getName() != null) {
                hasil.put("group", ux.getRole().getName());
            } else {
                hasil.put("group", "undefined");
            }
        }
    }

    return hasil;
}

From source file:com.netflix.spinnaker.gate.ratelimit.RateLimitingInterceptor.java

private Object getPrincipal(HttpServletRequest request) {
    SecurityContext context = SecurityContextHolder.getContext();
    Authentication authentication = context.getAuthentication();

    if (authentication == null) {
        return UNKNOWN_PRINCIPAL;
    }/* w w w .  jav  a2 s.c o  m*/

    if (authentication.getPrincipal() instanceof User) {
        return ((User) authentication.getPrincipal()).getEmail();
    }

    log.warn("Unknown principal type, assuming anonymous");
    return "anonymous-" + sourceIpAddress(request);
}

From source file:com.web.mavenproject6.controller.MainController.java

@RequestMapping(value = { "/self_profile" })
public String profileXS(Model model, @RequestParam(required = false) String message) {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    UserDetails ud = (UserDetails) auth.getPrincipal();
    System.out.println("!!!!!!12345" + ud.getUsername());
    Users u = userService.getRepository().findUserByEmail(ud.getUsername());
    if (u == null) {
        u = userService.getRepository().findUserByLogin(ud.getUsername());
    }//from  w  w w.  java2 s .c o m
    System.out.println("!!!!!!123456");
    if (u == null) {
        return "thy/error/404";
    }
    System.out.println("!!!!!!123457");
    model.addAttribute("propId", u.getPerson().getAccessNumber());
    return "thy/personal/profile";
}

From source file:nl.ctrlaltdev.harbinger.evidence.Evidence.java

public Evidence(Evidence src, Authentication auth) {
    this(src);//from w w  w  .  ja va  2  s . c o m
    Object principal = auth.getPrincipal();
    if (principal instanceof UserDetails) {
        user = ((UserDetails) principal).getUsername();
    } else {
        user = auth.getName();
    }
}

From source file:ch.entwine.weblounge.kernel.security.RoleBasedLoginSuccessHandler.java

/**
 * {@inheritDoc}/*  w w  w .ja va 2 s . c o  m*/
 * 
 * @see org.springframework.security.web.authentication.AuthenticationSuccessHandler#onAuthenticationSuccess(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse,
 *      org.springframework.security.core.Authentication)
 */
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
        Authentication authentication) throws IOException, ServletException {

    Object principal = authentication.getPrincipal();
    if (!(principal instanceof SpringSecurityUser)) {
        super.onAuthenticationSuccess(request, response, authentication);
        return;
    }

    // Try to process login based on the user's role
    User user = ((SpringSecurityUser) principal).getUser();
    boolean isEditor = SecurityUtils.userHasRole(user, SystemRole.EDITOR);

    logger.info("User '{}' logged in", user);

    // Try to redirect the user to the initial url
    HttpSession session = request.getSession(false);
    if (session != null) {
        SavedRequest savedRequest = (SavedRequest) session.getAttribute(SAVED_REQUEST);
        if (savedRequest != null) {
            response.sendRedirect(addTimeStamp(savedRequest.getRedirectUrl()));
            return;
        }
    }

    // If the user was intending to edit a page, let him do just that
    if (isEditor && StringUtils.isNotBlank(request.getParameter("edit"))) {
        super.onAuthenticationSuccess(request, response, authentication);
        return;
    }

    // Try to send users to an appropriate welcome page based on their roles
    for (Map.Entry<String, String> entry : welcomePages.entrySet()) {
        String roleId = entry.getKey();
        String welcomePage = entry.getValue();
        if (SecurityUtils.userHasRole(user, new RoleImpl(roleId))) {
            response.sendRedirect(addTimeStamp(welcomePage));
            return;
        }
    }

    // No idea what the user wants or who he/she is. Send them back
    response.sendRedirect(addTimeStamp(defaultWelcomePage));

}

From source file:com.linuxbox.enkive.permissions.SpringContextPermissionService.java

/**
 * If the security principal is an EnkiveUserDetails, can test directly if
 * user is an enkive admin. Otherwise we have to search through the granted
 * authorities one by one.//from w  w  w . j  a va2  s . c o m
 */
public boolean isAdmin() throws CannotGetPermissionsException {
    final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

    final Object detailsObj = authentication.getPrincipal();
    if (detailsObj instanceof EnkiveUserDetails) {
        final boolean isAdmin = ((EnkiveUserDetails) detailsObj).isEnkiveAdmin();
        return isAdmin;
    }

    for (GrantedAuthority a : authentication.getAuthorities()) {
        if (a.getAuthority().equals(ROLE_ADMIN)) {
            return true;
        }
    }

    return false;
}

From source file:eea.eprtr.cms.controller.FileOpsController.java

/**
 * Helper method to get authenticated userid.
 *//* w  w w .  j a  v  a2 s . com*/
private String getUserName() {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    Object principal = auth.getPrincipal();
    if (principal instanceof UserDetails) {
        return ((UserDetails) principal).getUsername();
    } else {
        return principal.toString();
    }
}

From source file:org.musicrecital.webapp.listener.UserCounterListener.java

/**
 * When user's logout, remove their name from the hashMap
 *
 * @param event the session binding event
 * @see javax.servlet.http.HttpSessionAttributeListener#attributeRemoved(javax.servlet.http.HttpSessionBindingEvent)
 *///  w  w w .  java 2s  .c  o  m
public void attributeRemoved(HttpSessionBindingEvent event) {
    if (event.getName().equals(EVENT_KEY) && !isAnonymous()) {
        SecurityContext securityContext = (SecurityContext) event.getValue();
        Authentication auth = securityContext.getAuthentication();
        if (auth != null && (auth.getPrincipal() instanceof User)) {
            User user = (User) auth.getPrincipal();
            removeUsername(user);
        }
    }
}

From source file:com.restfiddle.controller.rest.UserController.java

@RequestMapping(value = "/api/users/change-password", method = RequestMethod.POST, headers = "Accept=application/json")
public @ResponseBody void changePassword(@RequestBody PasswordResetDTO passwordResetDTO) {

    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    Object principal = authentication.getPrincipal();

    if (principal != null && principal instanceof User) {
        User loggedInUser = (User) principal;
        User user = userRepository.findOne(loggedInUser.getId());
        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        user.setPassword(passwordEncoder.encode(passwordResetDTO.getRetypedPassword()));
        userRepository.save(user);/*from  w w w . j  ava  2s . c  om*/
    }

}