List of usage examples for org.springframework.security.core Authentication getPrincipal
Object getPrincipal();
From source file:net.thewaffleshop.nimbus.security.ForwardingAuthenticationHandler.java
@Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { // extract account and password String password = (String) authentication.getCredentials(); AccountUser accountUser = (AccountUser) authentication.getPrincipal(); Account account = accountUser.getAccount(); // decode the secret key SecretKey secretKey = accountAPI.getSecretKey(account, password); // store the account and secret key in the session HttpSession session = request.getSession(); session.setAttribute("account", account); session.setAttribute("secretKey", secretKey); // forward request to success MVC method request.getRequestDispatcher("/authenticationSuccess").forward(request, response); }
From source file:fr.gael.dhus.service.SecurityService.java
/** * Get currently connected User./*from www . j av a 2 s.co m*/ * * @return Current User. */ public User getCurrentUser() { SecurityContext context = SecurityContextHolder.getContext(); if (context == null) { logger.error("No security context"); return null; } Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (auth == null) { logger.error("No auth in security context"); return null; } Object principal = auth.getPrincipal(); if (principal instanceof User) { return (User) principal; } logger.debug("Principal class : " + principal.getClass()); return null; }
From source file:binky.reportrunner.service.impl.AuthenticationServiceImpl.java
public Authentication authenticate(Authentication authentication) throws AuthenticationException { logger.info("authenticate service invoked"); if (StringUtils.isBlank((String) authentication.getPrincipal()) || StringUtils.isBlank((String) authentication.getCredentials())) { logger.debug("userName blank is " + StringUtils.isBlank((String) authentication.getPrincipal() + " password blank is " + StringUtils.isBlank((String) authentication.getCredentials()))); throw new BadCredentialsException("Invalid username/password"); }//w w w .ja v a2 s. co m String userName = (String) authentication.getPrincipal(); String password = (String) authentication.getCredentials(); RunnerUser user = userDao.get(userName); EncryptionUtil enc = new EncryptionUtil(); List<GrantedAuthority> authorities = new LinkedList<GrantedAuthority>(); try { if (user != null && user.getPassword().equals(enc.hashString(password))) { if (user.getIsAdmin()) { logger.info("admin login for user: " + userName); authorities.add(new GrantedAuthorityImpl("ROLE_ADMIN")); } else { logger.info("user login for user: " + userName); } authorities.add(new GrantedAuthorityImpl("ROLE_USER")); } else { logger.warn("login fail for user: " + userName); throw new BadCredentialsException("Invalid username/password"); } } catch (Exception e) { logger.fatal(e.getMessage(), e); throw new AuthenticationServiceException(e.getMessage(), e); } return new UsernamePasswordAuthenticationToken(userName, authentication.getCredentials(), authorities); }
From source file:com.exxonmobile.ace.hybris.storefront.security.AcceleratorAuthenticationProvider.java
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { final String username = (authentication.getPrincipal() == null) ? "NONE_PROVIDED" : authentication.getName();/*from ww w. j a v a 2 s .c om*/ if (getBruteForceAttackCounter().isAttack(username)) { try { UserModel userModel = getUserService().getUserForUID(StringUtils.lowerCase(username)); userModel.setLoginDisabled(true); getModelService().save(userModel); bruteForceAttackCounter.resetUserCounter(userModel.getUid()); } catch (UnknownIdentifierException e) { LOG.warn("Brute force attack attempt for non existing user name " + username); } finally { throw new BadCredentialsException( messages.getMessage("CoreAuthenticationProvider.badCredentials", "Bad credentials")); } } // check if the user of the cart matches the current user and if the // user is not anonymous. If otherwise, remove delete the session cart as it might // be stolen / from another user String sessionCartUserId = getCartService().getSessionCart().getUser().getUid(); if (!username.equals(sessionCartUserId) && !sessionCartUserId.equals(userService.getAnonymousUser().getUid())) { getCartService().setSessionCart(null); } return super.authenticate(authentication); }
From source file:ch.wisv.areafiftylan.users.controller.CurrentUserRestController.java
/** * This mapping allows the user to change their password while logged in. This is different from the password reset * functionality which works with tokens. Users have to provide both their old and new password, and have to be * fully authenticated, meaning that they can't be coming from a "Remember me" session. * * @param auth The current user * @param passwordChangeDTO DTO containing oldPassword and newPassword * * @return Statusmessage//from ww w . j a v a 2 s. c o m */ @RequestMapping(value = "password", method = RequestMethod.PUT) public ResponseEntity<?> changeCurrentUserPassword(Authentication auth, @RequestBody @Validated PasswordChangeDTO passwordChangeDTO) { User currentUser = (User) auth.getPrincipal(); userService.changePassword(currentUser.getId(), passwordChangeDTO.getOldPassword(), passwordChangeDTO.getNewPassword()); return createResponseEntity(HttpStatus.OK, "Password successfully changed"); }
From source file:com.sentinel.rest.handlers.AuthSuccessHandler.java
@Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException { LOG.trace("Method: onAuthenticationSuccess called."); response.setStatus(HttpServletResponse.SC_OK); UserDetails userdetails = (UserDetails) authentication.getPrincipal(); LOG.info(userdetails.getUsername() + " got is connected "); PrintWriter writer = response.getWriter(); mapper.writeValue(writer, null);/* w w w. j a va 2 s . c o m*/ writer.flush(); LOG.trace("Method: onAuthenticationSuccess finished."); }
From source file:org.jtalks.common.service.nontransactional.SecurityServiceImplTest.java
private void mockCurrentUserPrincipal() { Principal user = new PrincipalImpl(USERNAME); Authentication auth = mock(Authentication.class); when(auth.getPrincipal()).thenReturn(user); when(securityContext.getAuthentication()).thenReturn(auth); }
From source file:org.duracloud.account.security.vote.BaseAccessDecisionVoter.java
protected DuracloudUser getCurrentUser(Authentication authentication) { Object principal = authentication.getPrincipal(); if (principal instanceof String) { log.trace("Unknown user {}", principal); DuracloudUser user = new DuracloudUser(); user.setUsername((String) principal); return user; } else {//from www . j a v a2 s.c om return (DuracloudUser) principal; } }
From source file:it.geosolutions.geostore.services.rest.BaseAuthenticationTest.java
protected void doAutoLogin(String username, String password, HttpServletRequest request) { try {//w w w .j av a 2 s .c o m // Must be called from request filtered by Spring Security, otherwise SecurityContextHolder is not updated UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password); // token.setDetails(new WebAuthenticationDetails(request)); Authentication authentication = ((AuthenticationProvider) context.getBean("geostoreLdapProvider")) .authenticate(token); LOGGER.info("Logging in with [{" + authentication.getPrincipal() + "}]"); SecurityContextHolder.getContext().setAuthentication(authentication); } catch (Exception e) { SecurityContextHolder.getContext().setAuthentication(null); LOGGER.error("Failure in autoLogin", e); } }
From source file:org.ligoj.app.http.security.RestAuthenticationProvider.java
@Override public Authentication authenticate(final Authentication authentication) { final String userpassword = StringUtils.defaultString(authentication.getCredentials().toString(), ""); final String userName = StringUtils.lowerCase(authentication.getPrincipal().toString()); // First get the cookie final HttpClientBuilder clientBuilder = HttpClientBuilder.create(); clientBuilder.setDefaultRequestConfig(RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build()); final HttpPost httpPost = new HttpPost(getSsoPostUrl()); // Do the POST try (CloseableHttpClient httpClient = clientBuilder.build()) { final String content = String.format(getSsoPostContent(), userName, userpassword); httpPost.setEntity(new StringEntity(content, StandardCharsets.UTF_8)); httpPost.setHeader("Content-Type", "application/json"); final HttpResponse httpResponse = httpClient.execute(httpPost); if (HttpStatus.SC_NO_CONTENT == httpResponse.getStatusLine().getStatusCode()) { // Succeed authentication, save the cookies data inside the authentication return newAuthentication(userName, userpassword, authentication, httpResponse); }/*from www. j av a 2s.c om*/ log.info("Failed authentication of {}[{}] : {}", userName, userpassword.length(), httpResponse.getStatusLine().getStatusCode()); httpResponse.getEntity().getContent().close(); } catch (final IOException e) { log.warn("Remote SSO server is not available", e); } throw new BadCredentialsException("Invalid user or password"); }