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.supersede.fe.rest.GadgetRest.java

@RequestMapping(value = "/panel", method = RequestMethod.PUT)
public void setNumPanels(Authentication auth, @RequestBody Long numPanels) {
    DatabaseUser user = (DatabaseUser) auth.getPrincipal();
    Long userId = user.getUserId();

    UserDashboard ud = userDashboards.findOne(userId);

    if (ud == null) {
        ud = new UserDashboard();
        ud.setUserId(userId);//from  ww  w. j  a v a  2s  .c om
    }

    ud.setPanels(numPanels);
    userDashboards.save(ud);

    List<UserGadget> gadgets = userGadgets.findByUserIdOrderByGadgetIdAsc(user.getUserId());

    for (UserGadget g : gadgets) {
        if (g.getPanel() > (numPanels - 1L)) {
            g.setPanel(0L);
            userGadgets.save(g);
        }
    }
}

From source file:ar.com.zauber.commons.social.oauth.examples.web.controllers.WelcomeController.java

/**
 * @throws IOException/*from w  ww.ja v a 2  s.co m*/
 */
@RequestMapping(method = RequestMethod.GET)
@ResponseStatus(value = HttpStatus.OK)
public ModelAndView getIndex() throws IOException {
    ModelAndView out;

    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    ExampleUserDetails principal = (ExampleUserDetails) auth.getPrincipal();

    String username = principal.getUsername();
    if (username == null) {
        out = new ModelAndView("newuser");
        out.addObject("twitterUsername", principal.getAccessToken().getScreenName());
    } else {
        out = new ModelAndView("welcome");
        out.addObject("username", username);
    }

    return out;
}

From source file:com.epam.trade.storefront.security.AcceleratorAuthenticationProvider.java

@Override
public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
    final String username = (authentication.getPrincipal() == null) ? "NONE_PROVIDED"
            : authentication.getName();//from w w  w  .j  av a2 s.  c o  m

    if (getBruteForceAttackCounter().isAttack(username)) {
        try {
            final UserModel userModel = getUserService().getUserForUID(StringUtils.lowerCase(username));
            userModel.setLoginDisabled(true);
            getModelService().save(userModel);
            bruteForceAttackCounter.resetUserCounter(userModel.getUid());
        } catch (final UnknownIdentifierException e) {
            LOG.warn("Brute force attack attempt for non existing user name " + username);
        } finally {
            throw new BadCredentialsException(
                    messages.getMessage("CoreAuthenticationProvider.badCredentials", "Bad credentials"));
        }
    }

    return super.authenticate(authentication);

}

From source file:org.moserp.common.security.SpringSecurityAuditorAware.java

public String getCurrentAuditor() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication == null || !authentication.isAuthenticated()) {
        return null;
    }// ww  w .j  a va2s .com
    if (authentication.getPrincipal() instanceof String) {
        return ((String) authentication.getPrincipal());
    }
    if (authentication.getPrincipal() instanceof User) {
        return ((User) authentication.getPrincipal()).getUsername();
    }
    return authentication.getPrincipal().toString();
}

From source file:fr.gael.dhus.spring.security.authentication.DefaultAuthenticationProvider.java

@Override
@Transactional(propagation = Propagation.REQUIRED)
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    String username = (String) authentication.getPrincipal();
    String password = (String) authentication.getCredentials();
    String ip = "unknown";
    if (authentication.getDetails() instanceof WebAuthenticationDetails) {
        ip = ((WebAuthenticationDetails) authentication.getDetails()).getRemoteAddress();
    }/*from www .  ja  va2 s  . c  om*/
    LOGGER.info("Connection attempted by '" + authentication.getName() + "' from " + ip);
    arwDao.loginStart(username);

    User user = userService.getUserNoCheck(username);
    if (user == null || user.isDeleted()) {
        throw new BadCredentialsException(errorMessage);
    }

    PasswordEncryption encryption = user.getPasswordEncryption();
    if (!encryption.equals(PasswordEncryption.NONE)) {
        MessageDigest md;
        try {
            md = MessageDigest.getInstance(encryption.getAlgorithmKey());
            password = new String(Hex.encode(md.digest(password.getBytes("UTF-8"))));
        } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
            arwDao.loginEnd(user, false);
            throw new BadCredentialsException("Authentication process failed", e);
        }
    }

    if (!user.getPassword().equals(password)) {
        LOGGER.warn(new Message(MessageType.USER, "Connection refused for '" + username + "' from " + ip
                + " : error in login/password combination"));
        arwDao.loginEnd(user, false);
        throw new BadCredentialsException(errorMessage);
    }

    for (AccessRestriction restriction : user.getRestrictions()) {
        LOGGER.warn("Connection refused for '" + username + "' from " + ip + " : account is locked ("
                + restriction.getBlockingReason() + ")");
        arwDao.loginEnd(user, false);
        throw new LockedException(restriction.getBlockingReason());
    }

    LOGGER.info("Connection success for '" + username + "' from " + ip);
    arwDao.loginEnd(user, true);
    return new ValidityAuthentication(user, user.getAuthorities());
}

From source file:cz.muni.fi.editor.services.commons.impl.SecurityServiceImpl.java

@Override
@Transactional(readOnly = true)//from  ww w .j ava 2  s  . co m
public void refresh(Long userID) {
    if (SecurityContextHolder.getContext().getAuthentication() != null
            && SecurityContextHolder.getContext().getAuthentication().getPrincipal() != null) {
        Authentication current = SecurityContextHolder.getContext().getAuthentication();
        UserDTO principal = (UserDTO) current.getPrincipal();
        if (principal.getId().equals(userID)) {
            User dao = new User();
            dao.setId(principal.getId());

            List<OrganizationDTO> member = organizationDAO.getOrganizationForUser(dao, true).stream().map(o -> {
                OrganizationDTO dto = new OrganizationDTO();
                dto.setId(o.getId());
                return dto;
            }).collect(Collectors.toList());

            List<OrganizationDTO> owner = organizationDAO.ownedBy(dao).stream().map(o -> {
                OrganizationDTO dto = new OrganizationDTO();
                dto.setId(o.getId());
                return dto;
            }).collect(Collectors.toList());

            principal.init(owner, member);

            SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(
                    principal, current.getCredentials(), principal.getAuthorities()));
        }
    }
}

From source file:no.dusken.momus.authentication.UserLoginServiceImpl.java

public AuthUserDetails getLoggedInUserDetails() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (isAuthenticated(authentication)) {
        return (AuthUserDetails) authentication.getPrincipal();
    }//from w  ww  .j ava2  s . com
    return null;
}

From source file:com.acc.storefront.security.AcceleratorRememberMeServices.java

@Override
protected String retrievePassword(final Authentication authentication) {
    return getUserService().getUserForUID(authentication.getPrincipal().toString()).getEncodedPassword();
}

From source file:nl.surfnet.mujina.spring.SAMLResponseAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication submitted) throws AuthenticationException {

    logger.debug("attempting to authenticate: {}", submitted);

    User user = assertionConsumer.consume((Response) submitted.getPrincipal());

    SAMLAuthenticationToken authenticated = new SAMLAuthenticationToken(user,
            (String) submitted.getCredentials(), user.getAuthorities());

    authenticated.setDetails(submitted.getDetails());

    logger.debug("Returning with authentication token of {}", authenticated);

    return authenticated;

}

From source file:com.github.lynxdb.server.api.http.handlers.EpPut.java

@RequestMapping(path = "", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity put(Authentication _authentication, @RequestBody @Valid List<Metric> _request,
        BindingResult _bindingResult) {/*from  w  w  w .  ja v  a 2  s  . c om*/

    User user = (User) _authentication.getPrincipal();

    if (_bindingResult.hasErrors()) {
        ArrayList<String> errors = new ArrayList();
        _bindingResult.getFieldErrors().forEach((FieldError t) -> {
            errors.add(t.getField() + ": " + t.getDefaultMessage());
        });
        return new ErrorResponse(mapper, HttpStatus.BAD_REQUEST, errors.toString(), null).response();
    }

    List<com.github.lynxdb.server.core.Metric> metricList = new ArrayList<>();
    _request.stream().forEach((m) -> {
        metricList.add(new com.github.lynxdb.server.core.Metric(m));
    });

    try {
        entries.insertBulk(vhosts.byId(user.getVhost()), metricList);
    } catch (Exception ex) {
        throw ex;
    }
    return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
}