List of usage examples for org.springframework.security.authentication UsernamePasswordAuthenticationToken getPrincipal
public Object getPrincipal()
From source file:com.telefonica.euro_iaas.paasmanager.rest.auth.OpenStackAuthenticationProvider.java
/** * Add PaasManagerUser to claudiaData./*from ww w. j a v a 2 s .c om*/ * * @param claudiaData */ public static void addCredentialsToClaudiaData(ClaudiaData claudiaData) { PaasManagerUser paasManagerUser = new PaasManagerUser("unknown", "unknown"); if (SecurityContextHolder.getContext().getAuthentication() != null) { UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = (UsernamePasswordAuthenticationToken) SecurityContextHolder .getContext().getAuthentication(); if (usernamePasswordAuthenticationToken != null) { paasManagerUser.setToken(usernamePasswordAuthenticationToken.getPrincipal().toString()); paasManagerUser.setTenantId(usernamePasswordAuthenticationToken.getCredentials().toString()); } } claudiaData.setUser(paasManagerUser); }
From source file:se.omegapoint.facepalm.client.security.DbAuthenticationProvider.java
@Override public Authentication authenticate(final Authentication authentication) throws AuthenticationException { final UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication; final String username = (String) token.getPrincipal(); final String password = (String) token.getCredentials(); final Optional<User> user = userRepository.findByNameAndPassword(username, password); return user.map( u -> new UsernamePasswordAuthenticationToken(new AuthenticatedUser(u.username), null, emptyList())) .orElse(null);/*from w w w .j av a 2s . c o m*/ }
From source file:security.MyAuthenticationProvider.java
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { UsernamePasswordAuthenticationToken auth = (UsernamePasswordAuthenticationToken) authentication; String username = String.valueOf(auth.getPrincipal()); String password = String.valueOf(auth.getCredentials()); // 1. Use the username to load the data for the user, including authorities and password. User user = (User) userRepository.findOneByUsername(username); if (user == null) throw new BadCredentialsException("Bad Credentials"); String saltPassword = Hashing.sha512().hashString(password + user.getSalt(), Charsets.UTF_8).toString(); System.out.println("Salted pass: " + saltPassword); // 2. Check the passwords match. if (!user.getPassword().equals(saltPassword)) { throw new BadCredentialsException("Bad Credentials"); }/*from ww w.j ava 2 s .c om*/ // 3. Preferably clear the password in the user object before storing in authentication object //user.clearPassword(); // 4. Return an authenticated token, containing user data and authorities List<GrantedAuthority> authorities = new ArrayList<>(); authorities.add(new SimpleGrantedAuthority("ROLE_USER")); Authentication token = new UsernamePasswordAuthenticationToken(user, saltPassword, authorities); return token; }
From source file:com.hp.autonomy.frontend.find.idol.test.IdolMvcIntegrationTestUtils.java
@Override protected Authentication createAuthentication(final Collection<GrantedAuthority> authorities) { final CommunityPrincipal communityPrincipal = mock(CommunityPrincipal.class); when(communityPrincipal.getId()).thenReturn(1L); when(communityPrincipal.getUsername()).thenReturn("user"); final UsernamePasswordAuthenticationToken authentication = mock(UsernamePasswordAuthenticationToken.class); when(authentication.isAuthenticated()).thenReturn(true); when(authentication.getPrincipal()).thenReturn(communityPrincipal); when(authentication.getAuthorities()).thenReturn(authorities); return authentication; }
From source file:com.denimgroup.threadfix.service.CustomHttpSessionSecurityContextRepository.java
@Override public void saveContext(SecurityContext context, HttpServletRequest request, HttpServletResponse response) { super.saveContext(context, request, response); if (context.getAuthentication() == null || seenIds.contains(context.getAuthentication().hashCode())) { return;/* www . j av a 2 s. c o m*/ } Authentication authentication = context.getAuthentication(); if (authentication instanceof UsernamePasswordAuthenticationToken) { UsernamePasswordAuthenticationToken principal = (UsernamePasswordAuthenticationToken) authentication; Object threadfixPrincipal = principal.getPrincipal(); if (threadfixPrincipal instanceof ThreadFixUserDetails) { Integer userId = ((ThreadFixUserDetails) threadfixPrincipal).getUserId(); if (userId == 0) { // LDAP user return; } User user = userService.loadUser(userId); if (user == null) { LOG.error("Unable to look up user"); return; } LOG.debug("Adding SecurityContext for user " + user.getName()); contextMap.put(user.getId(), context); seenIds.add(context.getAuthentication().hashCode()); } } }
From source file:br.com.gerenciapessoal.security.Seguranca.java
@Produces @UsuarioLogado// w ww . ja v a 2s . com public UsuarioSistema getUsuarioLogado() { UsuarioSistema usuario = null; UsernamePasswordAuthenticationToken auth = (UsernamePasswordAuthenticationToken) FacesContext .getCurrentInstance().getExternalContext().getUserPrincipal(); if (auth != null && auth.getPrincipal() != null) { usuario = (UsuarioSistema) auth.getPrincipal(); } return usuario; }
From source file:org.glassmaker.spring.oauth.OAuth2AuthenticationProvider.java
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { if (!supports(authentication.getClass())) { return null; }/*from ww w. ja v a 2s. com*/ if (authentication instanceof UsernamePasswordAuthenticationToken) { UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication; UserDetails userDetails = userDetailsService.loadUserByUsername((String) token.getPrincipal()); UsernamePasswordAuthenticationToken newToken = new UsernamePasswordAuthenticationToken( token.getPrincipal(), token.getCredentials(), userDetails.getAuthorities()); newToken.setDetails(token.getDetails()); return newToken; } return null; }
From source file:com.sun.identity.provider.springsecurity.OpenSSOAuthenticationProvider.java
/** * authenticate the access request./*from w w w . ja v a 2 s. co m*/ * * Note by this point the user has already been granted an sso token * (i.e. they have already authenticated because they were redirected * to opensso). * * If the user has any group membership we turn those into * GrantedAuthortities (roles in Spring terminolgy). * @see OpenSSOSimpleAuthoritiesPopulator * * Note that a failure to retrieve OpenSSO roles does not result in * an non revcoverable exception (but we should revist this decision). In theory * we can continue with authentication only. The user will have no * GrantedAuthorities. * * @param authentication * @return authentication token - possibly withe ROLE_* authorities. * * @throws org.springframework.security.core.AuthenticationException */ public Authentication authenticate(Authentication authentication) throws AuthenticationException { OpenSSOSimpleAuthoritiesPopulator populator = new OpenSSOSimpleAuthoritiesPopulator(); if (debug.messageEnabled()) debug.message("Authentication: " + authentication); UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication; String principal = (String) token.getPrincipal(); // hack alert // We pass in the SSOToken as the credential (.e.g the password) // this is probably confusing - and we should refactor to use a // proper OpenSSOAuthenitcationToken. SSOToken ssoToken = (SSOToken) token.getCredentials(); try { Collection<? extends GrantedAuthority> ga = populator.getGrantedAuthorities(ssoToken); UserDetails u = new User(principal, "secret", true, true, true, true, ga); authentication = new UsernamePasswordAuthenticationToken(u, "secret", ga); } catch (Exception ex) { //throw new AuthenticationServiceException("Exception trying to get AMIdentity", ex); // Note: We eat the exception // The authentication can still succeed - but there will be no // granted authorities (i.e. no roles granted). // This is arguably the right thing to do here debug.error("Exception Trying to get AMIdentity", ex); } return authentication; }
From source file:com.amediamanager.service.UserServiceImpl.java
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { UsernamePasswordAuthenticationToken auth = (UsernamePasswordAuthenticationToken) authentication; String username = String.valueOf(auth.getPrincipal()); String password = String.valueOf(auth.getCredentials()); User user = find(username);//from w w w. j a v a2 s. c o m if (null == user || (!BCrypt.checkpw(password, user.getPassword()))) { throw new BadCredentialsException("Invalid username or password"); } List<GrantedAuthority> grantedAuths = new ArrayList<GrantedAuthority>(); grantedAuths.add(new SimpleGrantedAuthority("ROLE_USER")); // Create new auth token auth = new UsernamePasswordAuthenticationToken(username, null, grantedAuths); auth.setDetails(user); return auth; }
From source file:com.haulmont.restapi.auth.CubaUserAuthenticationProvider.java
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder .currentRequestAttributes(); HttpServletRequest request = attributes.getRequest(); String ipAddress = request.getRemoteAddr(); if (authentication instanceof UsernamePasswordAuthenticationToken) { RestApiConfig config = configuration.getConfig(RestApiConfig.class); if (!config.getStandardAuthenticationEnabled()) { log.debug(//from w w w . j a v a 2 s. com "Standard authentication is disabled. Property cuba.rest.standardAuthenticationEnabled is false"); throw new InvalidGrantException("Authentication disabled"); } UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication; String login = (String) token.getPrincipal(); UserSession session; try { String passwordHash = passwordEncryption.getPlainHash((String) token.getCredentials()); LoginPasswordCredentials credentials = new LoginPasswordCredentials(login, passwordHash); credentials.setIpAddress(ipAddress); credentials.setClientType(ClientType.REST_API); credentials.setClientInfo(makeClientInfo(request.getHeader(HttpHeaders.USER_AGENT))); //if the locale value is explicitly passed in the Accept-Language header then set its value to the //credentials. Otherwise, the locale of the user should be used Locale locale = restAuthUtils.extractLocaleFromRequestHeader(request); if (locale != null) { credentials.setLocale(locale); credentials.setOverrideLocale(true); } else { credentials.setOverrideLocale(false); } session = authenticationService.login(credentials).getSession(); } catch (AccountLockedException le) { log.info("Blocked user login attempt: login={}, ip={}", login, ipAddress); throw new LockedException("User temporarily blocked"); } catch (RestApiAccessDeniedException ex) { log.info("User is not allowed to use the REST API {}", login); throw new BadCredentialsException("User is not allowed to use the REST API"); } catch (LoginException e) { log.info("REST API authentication failed: {} {}", login, ipAddress); throw new BadCredentialsException("Bad credentials"); } AppContext.setSecurityContext(new SecurityContext(session)); UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken( authentication.getPrincipal(), authentication.getCredentials(), getRoleUserAuthorities(authentication)); @SuppressWarnings("unchecked") Map<String, String> details = (Map<String, String>) authentication.getDetails(); details.put(SESSION_ID_DETAILS_ATTRIBUTE, session.getId().toString()); result.setDetails(details); return result; } return null; }