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:eu.openanalytics.rsb.security.ApplicationPermissionEvaluator.java

private String getUserName(final Authentication authentication) {
    if (authentication.getPrincipal() instanceof UserDetails) {
        return ((UserDetails) authentication.getPrincipal()).getUsername();
    } else {/*from   ww w.  ja v a2 s.  c o  m*/
        return null;
    }
}

From source file:com.github.cherimojava.orchidae.security.MongoAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    LOG.info(AUTH, "login attempt for user {}", authentication.getName());
    UserDetails details = userDetailsService.loadUserByUsername((String) authentication.getPrincipal());

    if (details == null
            || !pwEncoder.matches((String) authentication.getCredentials(), details.getPassword())) {
        LOG.info(AUTH, "failed to authenticate user {}", authentication.getName());
        throw new BadCredentialsException(ERROR_MSG);
    }// w ww . jav a2s  .  co m

    LOG.info(AUTH, "login attempt for user {}", authentication.getName());

    return new UsernamePasswordAuthenticationToken(authentication.getPrincipal(),
            authentication.getCredentials(), details.getAuthorities());
}

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

@RequestMapping(value = "/api/users/current-user", method = RequestMethod.GET)
public @ResponseBody UserDTO getCurrentUser() {
    UserDTO userDTO = new UserDTO();

    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());
        userDTO.setName(user.getName());
        userDTO.setDescription(user.getDescription());
        userDTO.setEmail(user.getEmail());
    }/*from  w  ww  .  j a v a2  s .c o m*/
    return userDTO;
}

From source file:eu.supersede.dm.rest.ProcessActivitiesRest.java

@RequestMapping(value = "/list", method = RequestMethod.GET)
public List<ActivityDetails> getActivityList(Authentication auth) {
    List<ActivityDetails> list = new ArrayList<>();
    List<HActivity> activities = DMGame.get()
            .getPendingActivities(((DatabaseUser) auth.getPrincipal()).getUserId());

    for (HActivity a : activities) {
        ActivityDetails d = new ActivityDetails();
        ProcessManager mgr = DMGame.get().getProcessManager(a.getProcessId());
        DMMethod m = DMLibrary.get().getMethod(a.getMethodName());
        d.setActivityId(a.getId());//from   ww  w . j ava2s.c o m
        d.setMethodName(m.getLabel(mgr));
        d.setProcessId(a.getProcessId());
        d.setUserId(a.getUserId());

        if (m != null) {
            d.setUrl(m.getPage(mgr));
            d.setDescription(m.getDescription(mgr));
            list.add(d);
        }

        PropertyBag bag = mgr.getProperties(a);

        for (HProperty p : bag.getProperties()) {
            d.setProperty(p.getKey(), p.getValue());
        }
    }

    return list;
}

From source file:io.galeb.core.entity.security.SpringSecurityAuditorAware.java

@Override
public String getCurrentAuditor() {

    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    String currentUser = "anonymousUser";

    if (authentication != null && authentication.isAuthenticated()) {
        Object principal = authentication.getPrincipal();
        if (principal instanceof UserDetails) {
            currentUser = ((UserDetails) principal).getUsername();
        } else {//  w  w  w. j a va  2 s. c  om
            currentUser = principal.toString();
        }
    }

    return currentUser;
}

From source file:gov.nih.nci.ncicb.tcga.dcc.common.security.impl.SecurityUtilImpl.java

/**
 * @return the login of the authenticated principal. If not authenticated then it will return the default value <code>not_authenticated</code>
 *//*from   w  w  w.  ja va 2s . co m*/
public String getAuthenticatedPrincipalLoginName() {

    String result = NOT_AUTHENTICATED;

    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication != null) {
        if (authentication.getPrincipal() instanceof UserDetails) {
            result = ((UserDetails) authentication.getPrincipal()).getUsername();
        } else {
            result = authentication.getPrincipal().toString();
        }
    }

    return result;
}

From source file:org.apigw.appmanagement.revision.ApplicationManagementRevisionListener.java

@Override
public void newRevision(Object revisionEntity) {
    boolean isAdmin = false;
    String editor = "unknown";
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication != null) {
        logger.debug("changed by: {}", authentication);
        Object principal = authentication.getPrincipal();
        if (principal instanceof UserDetails) {
            UserDetails userDetails = (UserDetails) principal;
            for (GrantedAuthority grantedAuthority : userDetails.getAuthorities()) {
                if (adminPattern.matcher(grantedAuthority.getAuthority()).find()) {
                    isAdmin = true;//from w  w  w  .  j av a 2 s  .  c o m
                    break;
                }
            }
            editor = userDetails.getUsername();
        }
    }
    ApplicationManagementRevision applicationManagementRevision = (ApplicationManagementRevision) revisionEntity;
    applicationManagementRevision.setEditor(editor);
    applicationManagementRevision.setEditorAdmin(isAdmin);
}

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

@RequestMapping(value = "/api/users/{id}", method = RequestMethod.PUT, headers = "Accept=application/json")
public @ResponseBody UserDTO update(@PathVariable("id") Long id, @RequestBody UserDTO updated) {
    logger.debug("Updating user with information: " + updated);

    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());

        user.setName(updated.getName());
        user.setDescription(updated.getDescription());
        user.setEmail(updated.getEmail());
        userRepository.save(user);//ww  w  . ja v a 2s .  c o m
    }

    return updated;
}

From source file:eu.supersede.dm.rest.UserRest.java

/**
 * Return all the users with the given profile.
 * @param authentication/* w ww .j a  v  a2s.co  m*/
 * @param profile
 */
@RequestMapping(value = "", method = RequestMethod.GET)
public List<User> getUsers(Authentication authentication, @RequestParam(required = false) String profile) {
    DatabaseUser currentUser = (DatabaseUser) authentication.getPrincipal();
    List<eu.supersede.integration.api.datastore.fe.types.User> proxyUsers = null;

    try {
        proxyUsers = proxy.getFEDataStoreProxy().getUsers(currentUser.getTenantId(), false,
                currentUser.getToken());
    } catch (URISyntaxException e) {
        throw new InternalServerErrorException(e.getMessage());
    }

    List<User> us = new ArrayList<>();

    if (profile != null) {
        for (eu.supersede.integration.api.datastore.fe.types.User proxyUser : proxyUsers) {
            if (hasProfile(proxyUser, profile)) {
                us.add(new User(new Long(proxyUser.getUser_id()),
                        proxyUser.getFirst_name() + " " + proxyUser.getLast_name(), proxyUser.getEmail()));
            }
        }
    } else {
        for (eu.supersede.integration.api.datastore.fe.types.User proxyUser : proxyUsers) {
            us.add(new User(new Long(proxyUser.getUser_id()),
                    proxyUser.getFirst_name() + " " + proxyUser.getLast_name(), proxyUser.getEmail()));
        }
    }

    return us;
}

From source file:com.mitre.storefront.interceptors.beforecontroller.SecurityUserCheckBeforeControllerHandler.java

@Override
public boolean beforeController(final HttpServletRequest request, final HttpServletResponse response,
        final HandlerMethod handler) throws IOException {
    // Skip this security check when run from within the WCMS Cockpit
    if (isPreviewDataModelValid(request)) {
        return true;
    }/*from w w  w . j  av  a 2  s  .com*/

    final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication != null) {
        final Object principal = authentication.getPrincipal();
        if (principal instanceof String) {
            final String springSecurityUserId = (String) principal;

            final String hybrisUserId = userService.getCurrentUser().getUid();
            if (!springSecurityUserId.equals(hybrisUserId)) {
                LOG.error("User miss-match springSecurityUserId [" + springSecurityUserId
                        + "] hybris session user [" + hybrisUserId + "]. Invalidating session.");

                // Invalidate session and redirect to the root page
                request.getSession().invalidate();

                final String encodedRedirectUrl = response.encodeRedirectURL(request.getContextPath() + "/");

                final String ajaxHeader = request.getHeader(ajaxRequestHeaderKey);
                if (ajaxRequestHeaderValue.equals(ajaxHeader)) {
                    response.addHeader("redirectUrl", encodedRedirectUrl);
                    response.sendError(Integer.parseInt(ajaxRedirectErrorCode));
                } else {
                    response.sendRedirect(encodedRedirectUrl);
                }
                return false;
            }
        }
    }
    return true;
}