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:com.rockagen.gnext.service.spring.security.extension.BasicRequestAwareAuthenticationSuccessHandler.java

/**
 * Handler locked.//from  www . jav a 2 s  .  c  o m
 * 
 * @param userId
 *            the user id
 */
protected void handlerLocked(Authentication authentication) {

    String latestIp = ((BasicWebAuthenticationDetails) authentication.getDetails()).getRemoteAddress();
    String username = ((UserDetails) authentication.getPrincipal()).getUsername();
    AuthUser user = authUserServ.load(username);
    // error count clean
    user.setErrorCount(0);
    user.setStateTime(new Date());
    user.setLatestIp(latestIp);
    authUserServ.add(user);
}

From source file:ar.com.zauber.commons.auth.acegi.AbstractAcegiAuthenticationUserMapper.java

/** @return the username of the current session */
protected String getUsername() {
    final SecurityContext context = SecurityContextHolder.getContext();
    String ret = null;/*  w  w w  . j  a  v a  2s  .c  o  m*/

    final Authentication auth = context.getAuthentication();
    if (auth != null) {
        if (auth.isAuthenticated()) {
            final Object o = auth.getPrincipal();
            if (o instanceof String) {
                ret = (String) o;
            } else {
                ret = ((UserDetails) auth.getPrincipal()).getUsername();
            }
            Validate.notNull(ret);
        } else {
            throw new IllegalStateException("someone didn't " + "authenticate the user. Shame on ...!!");
        }
    }
    return ret;
}

From source file:com.blackducksoftware.tools.appedit.web.auth.AppEditAuthenticationProvider.java

/**
 * Attempt to authenticate the given user.
 *///from w w  w.  ja v a 2  s.  c  o m
@Override
public Authentication authenticate(Authentication authentication) {
    try {
        // User provided data from login page
        String username = (String) authentication.getPrincipal();
        String password = (String) authentication.getCredentials();

        validateInput(username, password);

        UsernamePasswordAuthenticationToken auth = generateAuthenticationToken(username, password);

        return auth;
    } catch (Exception e) {
        throw new AuthenticationServiceException(e.getMessage(), e);
    }
}

From source file:com.epam.cme.storefront.interceptors.beforecontroller.SecurityUserCheckBeforeControllerHandler.java

@Override
public boolean beforeController(final HttpServletRequest request, final HttpServletResponse response)
        throws IOException {
    // Skip this security check when run from within the WCMS Cockpit
    if (isPreviewDataModelValid(request)) {
        return true;
    }//from  ww w  .  ja  v a 2s .c  om
    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() + "/");
                response.sendRedirect(encodedRedirectUrl);
                return false;
            }
        }
    }
    return true;
}

From source file:org.meruvian.yama.webapi.config.oauth.UserTokenConverter.java

public Map<String, ?> convertUserAuthentication(Authentication authentication) {
    Map<String, Object> response = new LinkedHashMap<String, Object>();
    response.put(USERNAME, authentication.getName());

    if (authentication.getPrincipal() instanceof DefaultUserDetails) {
        DefaultUserDetails details = (DefaultUserDetails) authentication.getPrincipal();
        response.put(USER_ID, details.getId());
    }//  w  w  w.  ja v a  2 s.  c  om

    if (authentication.getAuthorities() != null && !authentication.getAuthorities().isEmpty()) {
        response.put(AUTHORITIES, AuthorityUtils.authorityListToSet(authentication.getAuthorities()));
    }

    return response;
}

From source file:de.iew.services.impl.UserDetailsServiceImpl.java

/**
 * {@inheritDoc}//from w w  w .j  av a 2  s  .c o m
 * <p>
 * Die Implementierung wurde von Spring bernommen.
 * </p>
 *
 * @see org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestWrapper#isGranted(String)
 */
public boolean isAuthenticatedUserInRole(String role) {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (auth == null || auth.getPrincipal() == null) {
        return false;
    }

    Collection<? extends GrantedAuthority> authorities = auth.getAuthorities();

    if (authorities == null) {
        return false;
    }

    for (GrantedAuthority grantedAuthority : authorities) {
        if (role.equals(grantedAuthority.getAuthority())) {
            return true;
        }
    }

    return false;
}

From source file:org.ihtsdo.otf.refset.api.authentication.UserController.java

@RequestMapping(method = RequestMethod.POST, value = "/getUserDetails", produces = "application/json", consumes = "application/json")
@ApiOperation(value = "Authenticate a user for given username and password provided in request header and returns user details ", notes = "This api call authenticate a user and also authorize a user for Refset app access. Pre-Auth tokens(X-REFSET-PRE-AUTH-USERNAME & X-REFSET-PRE-AUTH-TOKEN)"
        + " supplied in request header, are being used for authentication/authorization. If successful"
        + " it returns an User details object and a authentication token X-REFSET-AUTH-TOKEN as part of response header"
        + " to be used in header of subsequent requests for API handshake")
@PreAuthorize("hasRole('ROLE_USER')")
public ResponseEntity<Result<Map<String, Object>>> login() throws Exception {

    logger.debug("authenticating user {}");

    Result<Map<String, Object>> r = Utility.getResult();
    Map<String, Object> data = new HashMap<String, Object>();
    User u = org.ihtsdo.otf.refset.common.Utility.getUserDetails();
    if (StringUtils.isEmpty(u.getGivenname())) {

        Authentication authentication = new UsernamePasswordAuthenticationToken(u, u.getPassword());
        provider.authenticate(authentication);
        u = (User) authentication.getPrincipal();

    }/*from  ww w .  j a v  a2  s.co  m*/
    u.setPassword(null);//make it empty before sending it in response
    data.put("user", u);
    r.setData(data);

    r.getMeta().setMessage(SUCCESS);
    r.getMeta().setStatus(HttpStatus.OK);

    return new ResponseEntity<Result<Map<String, Object>>>(r, HttpStatus.OK);
}

From source file:org.smartplatforms.oauth2.LaunchOrchestrationEndpoint.java

@RequestMapping(value = "/Launch", method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
public void handleLaunchRequest(HttpServletRequest request, HttpServletResponse response,
        @RequestBody String jsonString) {
    Map<String, Object> jsonMap = new HashMap<String, Object>();
    try {/*from  w w  w.j a v a 2s  .com*/

        HttpSession sessionObj = request.getSession();

        JsonObject json = new JsonParser().parse(jsonString).getAsJsonObject();
        JsonObject jsonParams = json.get("parameters").getAsJsonObject();

        JsonElement jsonLaunchId = jsonParams.get("launch_id");
        String launchId = null;
        if (jsonLaunchId != null) {
            launchId = jsonLaunchId.getAsString();
        }

        Map<String, Object> launchContextParams = buildLaunchContextParamsMap(jsonParams);

        LaunchContext launchContext = createLaunchContext(launchId, launchContextParams);
        LaunchContextHolder.addLaunchContext(launchContext);

        SecurityContext securityContext = (SecurityContext) sessionObj.getAttribute("SPRING_SECURITY_CONTEXT");
        if (securityContext != null) {
            Authentication authentication = securityContext.getAuthentication();
            User user = (User) authentication.getPrincipal();
            jsonMap.put("username", user.getUsername());
        } else { //TODO this shouldn't happen when we turn authentication back on
            jsonMap.put("username", "none");
        }

        //TODO: get actual values
        jsonMap.put("created_by", "hspc_platform");
        jsonMap.put("launch_id", launchContext.getLaunchId());
        jsonMap.put("created_at", new Date().toString());
        Map<String, Object> retMap = new Gson().fromJson(json.get("parameters"),
                new TypeToken<HashMap<String, Object>>() {
                }.getType());
        jsonMap.put("parameters", retMap);

    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }

    response.setHeader("Content-Type", "application/json;charset=utf-8");
    try {
        response.getWriter().write(new Gson().toJson(jsonMap));
    } catch (IOException io_ex) {
        throw new RuntimeException(io_ex);
    }
}

From source file:com.acc.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;
    }// w w w.jav  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() + "/");
                response.sendRedirect(encodedRedirectUrl);
                return false;
            }
        }
    }
    return true;
}

From source file:org.jtalks.jcommune.service.nontransactional.SecurityServiceImpl.java

/**
 * {@inheritDoc}/*from w ww .  ja v a 2 s.  c o  m*/
 */
@Override
public String getCurrentUserUsername() {
    Authentication auth = securityContextFacade.getContext().getAuthentication();

    if (null == auth) {
        return null;
    }

    Object obj = auth.getPrincipal();
    String username = "";

    if (obj instanceof UserDetails) {
        username = ((UserDetails) obj).getUsername();
    } else {
        username = obj.toString();
    }

    return username;
}