List of usage examples for org.springframework.security.core Authentication getClass
@HotSpotIntrinsicCandidate public final native Class<?> getClass();
From source file:org.axonframework.samples.trader.webui.security.TraderAuthenticationProvider.java
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { if (!supports(authentication.getClass())) { return null; }/*w w w. jav a 2 s . c o m*/ UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication; String username = token.getName(); String password = String.valueOf(token.getCredentials()); FutureCallback<UserAccount> accountCallback = new FutureCallback<UserAccount>(); AuthenticateUserCommand command = new AuthenticateUserCommand(username, password.toCharArray()); try { commandBus.dispatch(new GenericCommandMessage<AuthenticateUserCommand>(command), accountCallback); // the bean validating interceptor is defined as a dispatch interceptor, meaning it is executed before // the command is dispatched. } catch (StructuralCommandValidationFailedException e) { return null; } UserAccount account; try { account = accountCallback.get(); if (account == null) { throw new BadCredentialsException("Invalid username and/or password"); } } catch (InterruptedException e) { throw new AuthenticationServiceException("Credentials could not be verified", e); } catch (ExecutionException e) { throw new AuthenticationServiceException("Credentials could not be verified", e); } UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(account, authentication.getCredentials(), userAuthorities); result.setDetails(authentication.getDetails()); return result; }
From source file:com.ai.bss.webui.security.AiBssAuthenticationProvider.java
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { if (!supports(authentication.getClass())) { return null; }/* w w w . j a v a 2 s. c om*/ UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication; String username = token.getName(); String password = String.valueOf(token.getCredentials()); FutureCallback<UserAccount> accountCallback = new FutureCallback<UserAccount>(); AuthenticateUserCommand command = new AuthenticateUserCommand(username, password.toCharArray()); try { // commandBus.dispatch(new GenericCommandMessage<AuthenticateUserCommand>(command), accountCallback); // the bean validating interceptor is defined as a dispatch interceptor, meaning it is executed before // the command is dispatched. } catch (StructuralCommandValidationFailedException e) { e.printStackTrace(); return null; } UserAccount account; try { account = accountCallback.get(); if (account == null) { throw new BadCredentialsException("Invalid username and/or password"); } } catch (InterruptedException e) { throw new AuthenticationServiceException("Credentials could not be verified", e); } catch (ExecutionException e) { throw new AuthenticationServiceException("Credentials could not be verified", e); } UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(account, authentication.getCredentials(), userAuthorities); result.setDetails(authentication.getDetails()); return result; }
From source file:org.mitre.openid.connect.client.OIDCAuthenticationProvider.java
@Override public Authentication authenticate(final Authentication authentication) throws AuthenticationException { if (!supports(authentication.getClass())) { return null; }/*from www .ja va 2 s . c o m*/ if (authentication instanceof PendingOIDCAuthenticationToken) { PendingOIDCAuthenticationToken token = (PendingOIDCAuthenticationToken) authentication; // get the ID Token value out JWT idToken = token.getIdToken(); // load the user info if we can UserInfo userInfo = userInfoFetcher.loadUserInfo(token); if (userInfo == null) { // user info not found -- could be an error, could be fine } else { // if we found userinfo, double check it if (!Strings.isNullOrEmpty(userInfo.getSub()) && !userInfo.getSub().equals(token.getSub())) { // the userinfo came back and the user_id fields don't match what was in the id_token throw new UsernameNotFoundException("user_id mismatch between id_token and user_info call: " + token.getSub() + " / " + userInfo.getSub()); } } return createAuthenticationToken(token, authoritiesMapper.mapAuthorities(idToken, userInfo), userInfo); } return null; }
From source file:org.pac4j.springframework.security.authentication.ClientAuthenticationProvider.java
@SuppressWarnings({ "unchecked", "rawtypes" }) public Authentication authenticate(final Authentication authentication) throws AuthenticationException { logger.debug("authentication : {}", authentication); if (!supports(authentication.getClass())) { logger.debug("unsupported authentication class : {}", authentication.getClass()); return null; }/*from w ww . j a v a2 s. c om*/ final ClientAuthenticationToken token = (ClientAuthenticationToken) authentication; // get the credentials final Credentials credentials = (Credentials) authentication.getCredentials(); logger.debug("credentials : {}", credentials); // get the right client final String clientName = token.getClientName(); final Client client = this.clients.findClient(clientName); // get the user profile final UserProfile userProfile = client.getUserProfile(credentials, null); logger.debug("userProfile : {}", userProfile); // by default, no authorities Collection<? extends GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(); // get user details and check them if (this.userDetailsService != null) { final ClientAuthenticationToken tmpToken = new ClientAuthenticationToken(credentials, clientName, userProfile, null); final UserDetails userDetails = this.userDetailsService.loadUserDetails(tmpToken); logger.debug("userDetails : {}", userDetails); if (userDetails != null) { this.userDetailsChecker.check(userDetails); authorities = userDetails.getAuthorities(); logger.debug("authorities : {}", authorities); } } // new token with credentials (like previously) and user profile and // authorities final ClientAuthenticationToken result = new ClientAuthenticationToken(credentials, clientName, userProfile, authorities); result.setDetails(authentication.getDetails()); logger.debug("result : {}", result); return result; }
From source file:com.katropine.oauth.CustomUserAuthenticationProvider.java
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { LOGGER.warning("!!!Authenticate: " + authentication.getPrincipal().toString() + ":" + authentication.getCredentials().toString()); if (!supports(authentication.getClass())) { return null; }// w w w .j a va2s.co m if (authentication.getCredentials() == null) { LOGGER.warning("No credentials found in request."); boolean throwExceptionWhenTokenRejected = false; if (throwExceptionWhenTokenRejected) { throw new BadCredentialsException("No pre-authenticated credentials found in request."); } return null; } User user = userDAO.getByEmail(authentication.getPrincipal().toString()); BCryptPasswordEncoder enc = new BCryptPasswordEncoder(); if (!enc.matches(authentication.getCredentials().toString(), user.getPassword())) { throw new BadCredentialsException("Bad User Credentials."); } List<GrantedAuthority> grantedAuthorities = new ArrayList<>(); CustomUserPasswordAuthenticationToken auth = new CustomUserPasswordAuthenticationToken( authentication.getPrincipal(), authentication.getCredentials(), grantedAuthorities); return auth; }
From source file:eu.freme.broker.security.SecurityConfig.java
@Bean public AuthenticationManager authenticationManager() { return new AuthenticationManager() { @Autowired/*from w w w . j ava 2s . co m*/ AuthenticationProvider[] authenticationProviders; @Override public Authentication authenticate(Authentication authentication) throws ProviderNotFoundException { for (AuthenticationProvider auth : authenticationProviders) { if (auth.supports(authentication.getClass())) { return auth.authenticate(authentication); } } throw new ProviderNotFoundException( "No AuthenticationProvider found for " + authentication.getClass()); } }; }
From source file:eu.freme.common.security.SecurityConfig.java
@Override @Bean//from w w w . j av a2 s . c om public AuthenticationManager authenticationManager() { return new AuthenticationManager() { @Autowired AuthenticationProvider[] authenticationProviders; @Override public Authentication authenticate(Authentication authentication) throws ProviderNotFoundException { for (AuthenticationProvider auth : authenticationProviders) { if (auth.supports(authentication.getClass())) { return auth.authenticate(authentication); } } throw new ProviderNotFoundException( "No AuthenticationProvider found for " + authentication.getClass()); } }; }
From source file:com.gfactor.web.wicket.context.ProviderManager.java
/** * Attempts to authenticate the passed {@link Authentication} object. * <p>/*from w w w . j av a 2s. com*/ * The list of {@link AuthenticationProvider}s will be successively tried until an * <code>AuthenticationProvider</code> indicates it is capable of authenticating the type of * <code>Authentication</code> object passed. Authentication will then be attempted with that * <code>AuthenticationProvider</code>. * <p> * If more than one <code>AuthenticationProvider</code> supports the passed <code>Authentication</code> * object, only the first <code>AuthenticationProvider</code> tried will determine the result. No subsequent * <code>AuthenticationProvider</code>s will be tried. * * @param authentication the authentication request object. * * @return a fully authenticated object including credentials. * * @throws AuthenticationException if authentication fails. */ public Authentication doAuthentication(Authentication authentication) throws AuthenticationException { Class<? extends Authentication> toTest = authentication.getClass(); AuthenticationException lastException = null; Authentication result = null; for (AuthenticationProvider provider : getProviders()) { if (!provider.supports(toTest)) { continue; } logger.debug("Authentication attempt using " + provider.getClass().getName()); try { result = provider.authenticate(authentication); if (result != null) { copyDetails(authentication, result); break; } } catch (AccountStatusException e) { // SEC-546: Avoid polling additional providers if auth failure is due to invalid account status eventPublisher.publishAuthenticationFailure(e, authentication); throw e; } catch (AuthenticationException e) { lastException = e; } } if (result == null && parent != null) { // Allow the parent to try. try { result = parent.authenticate(authentication); } catch (ProviderNotFoundException e) { // ignore as we will throw below if no other exception occurred prior to calling parent and the parent // may throw ProviderNotFound even though a provider in the child already handled the request } catch (AuthenticationException e) { lastException = e; } } if (result != null) { if (eraseCredentialsAfterAuthentication && (result instanceof CredentialsContainer)) { // Authentication is complete. Remove credentials and other secret data from authentication ((CredentialsContainer) result).eraseCredentials(); } eventPublisher.publishAuthenticationSuccess(result); return result; } // Parent was null, or didn't authenticate (or throw an exception). if (lastException == null) { lastException = new ProviderNotFoundException(messages.getMessage("ProviderManager.providerNotFound", new Object[] { toTest.getName() }, "No AuthenticationProvider found for {0}")); } eventPublisher.publishAuthenticationFailure(lastException, authentication); throw lastException; }
From source file:edu.utah.further.security.impl.services.DatasourceAuthenticatedUserDetailsService.java
@Override @Transactional// w w w . j ava2s . c om public EnhancedUserDetails loadUserDetails(final Authentication token) throws UsernameNotFoundException { Validate.isTrue(FederatedAuthenticationToken.class.isAssignableFrom(token.getClass()), "Only FederatedAuthenticationTokens are supported"); Validate.notNull(getContext(), "A context is required to load the user details"); // Load the user details based on the datasource at hand Long federatedUsername = null; try { federatedUsername = Long.valueOf(token.getName()); } catch (final Exception e) { throw new ApplicationException("Expected a federated username but received " + token.getName()); } final Query query = sessionFactory.getCurrentSession() .createQuery("from UserEntity where id = :federatedUsername"); query.setParameter("federatedUsername", federatedUsername); final User user = (User) query.uniqueResult(); if (user == null) { throw new UsernameNotFoundException("User " + federatedUsername + " does not exist."); } final DefaultUserDetailsImpl userDetails = new DefaultUserDetailsImpl(); // Load the roles final Collection<UserRole> roles = user.getRoles(); final Collection<GrantedAuthority> authorities = CollectionUtil.newList(); if (roles != null && roles.size() > 0) { for (final UserRole role : roles) { authorities.add(new GrantedAuthorityImpl(rolePrefix + role.getRole().getName())); } userDetails.setAuthorities(authorities); } // Load the properties final Collection<UserProperty> properties = user.getProperties(); final Map<String, String> userProperties = newMap(); if (properties != null && properties.size() > 0) { for (final UserProperty property : properties) { // Only populate the user details with properties from this namespace if (property.getProperty().getNamespace().intValue() == getContext().intValue()) { userProperties.put(property.getProperty().getName(), property.getPropertyValue()); } } userDetails.setProperties(userProperties); } userDetails.setUsername(String.valueOf(federatedUsername)); userDetails.setEnabled(true); userDetails.setCredentialsNonExpired(true); userDetails.setAccountNonExpired(true); userDetails.setAccountNonLocked(true); return userDetails; }
From source file:org.brekka.pegasus.core.services.impl.AccessorContextImpl.java
private static AccessorContext accessorContext(final boolean useStub) { AccessorContext accessorContext = null; SecurityContext context = SecurityContextHolder.getContext(); Authentication authentication = context.getAuthentication(); if (authentication != null) { Object principal = authentication.getPrincipal(); if (principal instanceof PegasusPrincipalAware) { PegasusPrincipal pegasusPrincipal = ((PegasusPrincipalAware) principal).getPegasusPrincipal(); MemberContext memberContext = pegasusPrincipal.getMemberContext(); if (memberContext == null) { throw new PegasusException(PegasusErrorCode.PG623, "No AccessorContext available for authentication: %s", authentication); }//from w ww.j a v a 2 s. c o m accessorContext = memberContext.getAccessorContext(); } if (principal instanceof AccessorContextAware) { accessorContext = ((AccessorContextAware) principal).getAccessorContext(); } } if (accessorContext == null) { if (useStub) { accessorContext = new AccessorContextImpl(); } else { throw new PegasusException(PegasusErrorCode.PG623, "No AccessorContext available for the current security context '%s'", authentication != null ? authentication.getClass().getName() : null); } } return accessorContext; }