Java Code Examples for org.springframework.security.core.Authentication#getCredentials()

The following examples show how to use org.springframework.security.core.Authentication#getCredentials() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RestAuthenticationProvider.java    From iotplatform with Apache License 2.0 6 votes vote down vote up
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
  Assert.notNull(authentication, "No authentication data provided");

  Object principal = authentication.getPrincipal();
  if (!(principal instanceof UserPrincipal)) {
    throw new BadCredentialsException("Authentication Failed. Bad user principal.");
  }

  UserPrincipal userPrincipal = (UserPrincipal) principal;
  if (userPrincipal.getType() == UserPrincipal.Type.USER_NAME) {
    String username = userPrincipal.getValue();
    String password = (String) authentication.getCredentials();
    return authenticateByUsernameAndPassword(userPrincipal, username, password);
  } else {
    String publicId = userPrincipal.getValue();
    return authenticateByPublicId(userPrincipal, publicId);
  }
}
 
Example 2
Source File: RemoteIdmAuthenticationProvider.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    RemoteUser user = remoteIdmService.authenticateUser(authentication.getPrincipal().toString(), authentication.getCredentials().toString());
    if (user == null) {
        throw new FlowableException("user not found " + authentication.getPrincipal());
    }

    Collection<GrantedAuthority> grantedAuthorities = new ArrayList<>();
    for (String privilege : user.getPrivileges()) {
        grantedAuthorities.add(new SimpleGrantedAuthority(privilege));
    }

    Authentication auth = new UsernamePasswordAuthenticationToken(authentication.getPrincipal(),
            authentication.getCredentials(), grantedAuthorities);
    return auth;
}
 
Example 3
Source File: DomainUsernamePasswordAuthenticationProvider.java    From spring-boot-security-example with MIT License 6 votes vote down vote up
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    Optional<String> username = (Optional) authentication.getPrincipal();
    Optional<String> password = (Optional) authentication.getCredentials();

    if (!username.isPresent() || !password.isPresent()) {
        throw new BadCredentialsException("Invalid Domain User Credentials");
    }

    AuthenticationWithToken resultOfAuthentication = externalServiceAuthenticator.authenticate(username.get(), password.get());
    String newToken = tokenService.generateNewToken();
    resultOfAuthentication.setToken(newToken);
    tokenService.store(newToken, resultOfAuthentication);

    return resultOfAuthentication;
}
 
Example 4
Source File: CustomAuthenticationProvider.java    From batch-scheduler with MIT License 6 votes vote down vote up
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    // 获取认证的用户名 & 密码
    String name = authentication.getName();
    Object pd = authentication.getCredentials();
    if (pd == null) {
        return new UsernamePasswordAuthenticationToken(name, "", new ArrayList<>());
    }
    String password = pd.toString();
    UserLoginEntity userLoginEntity = loginService.loginValidator(name, password);
    // 认证逻辑
    if (userLoginEntity.isFlag()) {
        return getRole(name, password);
    } else {
        logger.info("登录失败,原因是:账号 {}: {}", userLoginEntity.getUsername(), userLoginEntity.getMessage());
        throw new BadCredentialsException(new GsonBuilder().create().toJson(userLoginEntity));
    }
}
 
Example 5
Source File: RefreshTokenAuthenticationProvider.java    From IOT-Technical-Guide with Apache License 2.0 5 votes vote down vote up
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    Assert.notNull(authentication, "No authentication data provided");
    RawAccessJwtToken rawAccessToken = (RawAccessJwtToken) authentication.getCredentials();
    SecurityUser unsafeUser = tokenFactory.parseRefreshToken(rawAccessToken);
    UserPrincipal principal = unsafeUser.getUserPrincipal();
    SecurityUser securityUser;
    if (principal.getType() == UserPrincipal.Type.USER_NAME) {
        securityUser = authenticateByUserId(unsafeUser.getId());
    } else {
        securityUser = authenticateByPublicId(1L);
    }
    return new RefreshAuthenticationToken(securityUser);
}
 
Example 6
Source File: ApiTokenAuthenticationProvider.java    From galeb with Apache License 2.0 5 votes vote down vote up
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    if (authentication.getPrincipal() == null) {
        String errMsg = "principal is NULL";
        LOGGER.error(errMsg);
        throw new SecurityException(errMsg);
    }

    UserDetails userDetails = retrieveUser(authentication.getName(), null);
    if (((Account) userDetails).getApitoken().equals(authentication.getCredentials())) {
        return new UsernamePasswordAuthenticationToken(userDetails, authentication.getCredentials(), userDetails.getAuthorities());
    }

    throw new BadCredentialsException(this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
}
 
Example 7
Source File: LoginAuthenticationProvider.java    From learning-code with Apache License 2.0 5 votes vote down vote up
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    String username = authentication.getName();
    String password = (String) authentication.getCredentials();
    UserDetails user = userDetailsService.loadUserByUsername(username);
    if (passwordEncoder.matches(password, user.getPassword())) {
        Collection<? extends GrantedAuthority> authorities = user.getAuthorities();
        return new UsernamePasswordAuthenticationToken(username, password, authorities);
    }
    throw new BadCredentialsException("The password is not correct.");
}
 
Example 8
Source File: PreAuthenticatedProfileProvider.java    From engine with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
    if (authentication.getPrincipal() instanceof ProfileUser) {
        ProfileUser principal = (ProfileUser) authentication.getPrincipal();
        return new PreAuthenticatedAuthenticationToken(
            new ProfileUser(authenticationManager.authenticateUser(principal.getProfile())),
            authentication.getCredentials(),
            principal.getAuthorities());
    }
    return null;
}
 
Example 9
Source File: AuthenticationPerformer.java    From blackduck-alert with Apache License 2.0 5 votes vote down vote up
public final Optional<Authentication> performAuthentication(Authentication authentication) {
    Authentication authenticationResult = authenticateWithProvider(authentication);
    if (authenticationResult.isAuthenticated()) {
        Collection<? extends GrantedAuthority> authorities = isAuthorized(authenticationResult) ? authenticationResult.getAuthorities() : List.of();
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(authenticationResult.getPrincipal(), authenticationResult.getCredentials(), authorities);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        authenticationEventManager.sendAuthenticationEvent(authenticationToken, getAuthenticationType());
        return Optional.of(authenticationToken);
    }
    return Optional.empty();
}
 
Example 10
Source File: DefaultAuthenticationProvider.java    From oauth2-blog with MIT License 5 votes vote down vote up
@Override
public Authentication authenticate(final Authentication authentication) throws AuthenticationException {

    if (authentication.getName() == null || authentication.getCredentials() == null) {
        return null;
    }

    if (authentication.getName().isEmpty() || authentication.getCredentials().toString().isEmpty()) {
        return null;
    }

    final Optional<AppUser> appUser = this.appUserRepository.findById(authentication.getName());

    if (appUser.isPresent()) {
        final AppUser user = appUser.get();
        final String providedUserEmail = authentication.getName();
        final Object providedUserPassword = authentication.getCredentials();

        if (providedUserEmail.equalsIgnoreCase(user.getUserEmail())
                && providedUserPassword.equals(user.getUserPass())) {
            return new UsernamePasswordAuthenticationToken(
                    user.getUserEmail(),
                    user.getUserPass(),
                    Collections.singleton(new SimpleGrantedAuthority(user.getUserRole())));
        }
    }

    throw new UsernameNotFoundException("Invalid username or password.");
}
 
Example 11
Source File: SSOAuthProcessingFilter.java    From ods-provisioning-app with Apache License 2.0 5 votes vote down vote up
/**
 * If the authentication has been done via crowd, a cookie is written, because crowd uses the
 * cookie to authenticate
 *
 * @param request
 * @param response
 * @param authResult
 */
boolean storeTokenIfCrowd(
    HttpServletRequest request, HttpServletResponse response, Authentication authResult) {
  if (authResult instanceof CrowdSSOAuthenticationToken && authResult.getCredentials() != null) {
    try {
      httpAuthenticator.setPrincipalToken(
          request, response, authResult.getCredentials().toString());
      return true;
    } catch (Exception e) {
      logger.error("Unable to set Crowd SSO token", e);
      return false;
    }
  }
  return false;
}
 
Example 12
Source File: AtlasADAuthenticationProvider.java    From atlas with Apache License 2.0 5 votes vote down vote up
private Authentication getADAuthentication(Authentication authentication) {
     try {
         String userName = authentication.getName();
         String userPassword = "";
         if (authentication.getCredentials() != null) {
             userPassword = authentication.getCredentials().toString();
         }

         ActiveDirectoryLdapAuthenticationProvider adAuthenticationProvider =
                 new ActiveDirectoryLdapAuthenticationProvider(adDomain, adURL);
         adAuthenticationProvider.setConvertSubErrorCodesToExceptions(true);
adAuthenticationProvider.setUseAuthenticationRequestCredentials(true);
         adAuthenticationProvider.setSearchFilter(adUserSearchFilter);

         if (userName != null && userPassword != null
                 && !userName.trim().isEmpty()
                 && !userPassword.trim().isEmpty()) {
             final List<GrantedAuthority> grantedAuths = getAuthorities(userName);
             final UserDetails principal = new User(userName, userPassword,
                     grantedAuths);
             final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(
                     principal, userPassword, grantedAuths);
             authentication = adAuthenticationProvider.authenticate(finalAuthentication);
             if(groupsFromUGI) {
                 authentication = getAuthenticationWithGrantedAuthorityFromUGI(authentication);
             }
             return authentication;
         } else {
             LOG.error("AD Authentication Failed userName or userPassword is null or empty");
             return null;
         }
     } catch (Exception e) {
         LOG.error("AD Authentication Failed:", e);
         return null;
     }
 }
 
Example 13
Source File: AuthContextUtils.java    From syncope with Apache License 2.0 5 votes vote down vote up
public static void updateUsername(final String newUsername) {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();

    UsernamePasswordAuthenticationToken newAuth = new UsernamePasswordAuthenticationToken(
            new User(newUsername, FAKE_PASSWORD, auth.getAuthorities()),
            auth.getCredentials(), auth.getAuthorities());
    newAuth.setDetails(auth.getDetails());
    SecurityContextHolder.getContext().setAuthentication(newAuth);
}
 
Example 14
Source File: UserController.java    From spring-cloud-study with Apache License 2.0 5 votes vote down vote up
@GetMapping(value = "jwt")
@PreAuthorize("hasAnyRole('ROLE_ADMIN')")
public Object jwtParser(Authentication authentication){
    authentication.getCredentials();
    OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails)authentication.getDetails();
    String jwtToken = details.getTokenValue();
    Claims claims = Jwts.parser()
            .setSigningKey("dev".getBytes(StandardCharsets.UTF_8))
            .parseClaimsJws(jwtToken)
            .getBody();
    return claims;
}
 
Example 15
Source File: TokenAuthProvider.java    From haven-platform with Apache License 2.0 5 votes vote down vote up
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    final TokenData tokenData = fetchToken(authentication);
    if (tokenData != null) {
        final UserDetails userDetails = userDetailsService.loadUserByUsername(tokenData.getUserName());
        LOG.debug("Token {} is valid; userDetails is {}", tokenData, userDetails);
        return authProcessor.createSuccessAuth(authentication, userDetails);
    } else {
        throw new UsernameNotFoundException("User not found" + authentication.getCredentials());
    }
}
 
Example 16
Source File: SecurityUtils.java    From jhipster-microservices-example with Apache License 2.0 5 votes vote down vote up
/**
 * Get the JWT of the current user.
 *
 * @return the JWT of the current user
 */
public static String getCurrentUserJWT() {
    SecurityContext securityContext = SecurityContextHolder.getContext();
    Authentication authentication = securityContext.getAuthentication();
    if (authentication != null && authentication.getCredentials() instanceof String) {
        return (String) authentication.getCredentials();
    }
    return null;
}
 
Example 17
Source File: AtlasADAuthenticationProvider.java    From atlas with Apache License 2.0 4 votes vote down vote up
private Authentication getADBindAuthentication (Authentication authentication) {
     try {
         String userName = authentication.getName();
         String userPassword = "";
         if (authentication.getCredentials() != null) {
             userPassword = authentication.getCredentials().toString();
         }

         LdapContextSource ldapContextSource = new DefaultSpringSecurityContextSource(adURL);
         ldapContextSource.setUserDn(adBindDN);
         ldapContextSource.setPassword(adBindPassword);
         ldapContextSource.setReferral(adReferral);
         ldapContextSource.setCacheEnvironmentProperties(true);
         ldapContextSource.setAnonymousReadOnly(false);
         ldapContextSource.setPooled(true);
         ldapContextSource.afterPropertiesSet();

         FilterBasedLdapUserSearch userSearch=new FilterBasedLdapUserSearch(adBase, adUserSearchFilter,ldapContextSource);
         userSearch.setSearchSubtree(true);

         BindAuthenticator bindAuthenticator = new BindAuthenticator(ldapContextSource);
         bindAuthenticator.setUserSearch(userSearch);
         bindAuthenticator.afterPropertiesSet();

LdapAuthenticationProvider ldapAuthenticationProvider = new LdapAuthenticationProvider(bindAuthenticator);

         if (userName != null && userPassword != null
                 && !userName.trim().isEmpty()
                 && !userPassword.trim().isEmpty()) {
             final List<GrantedAuthority> grantedAuths = getAuthorities(userName);
             final UserDetails principal = new User(userName, userPassword,
                     grantedAuths);
             final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(
                     principal, userPassword, grantedAuths);
             authentication = ldapAuthenticationProvider.authenticate(finalAuthentication);
             if (groupsFromUGI) {
                 authentication = getAuthenticationWithGrantedAuthorityFromUGI(authentication);
             }
             return authentication;
         } else {
             LOG.error("AD Authentication Failed userName or userPassword is null or empty");
             return null;
         }
     } catch (Exception e) {
         LOG.error("AD Authentication Failed:", e);
         return null;
     }
 }
 
Example 18
Source File: AtlasLdapAuthenticationProvider.java    From atlas with Apache License 2.0 4 votes vote down vote up
private Authentication getLdapBindAuthentication(
        Authentication authentication) {
    try {
        if (isDebugEnabled) {
            LOG.debug("==> AtlasLdapAuthenticationProvider getLdapBindAuthentication");
        }
        String userName = authentication.getName();
        String userPassword = "";
        if (authentication.getCredentials() != null) {
            userPassword = authentication.getCredentials().toString();
        }

        LdapContextSource ldapContextSource = getLdapContextSource();

        DefaultLdapAuthoritiesPopulator defaultLdapAuthoritiesPopulator = getDefaultLdapAuthoritiesPopulator(ldapContextSource);

        if (ldapUserSearchFilter == null
                || ldapUserSearchFilter.trim().isEmpty()) {
            ldapUserSearchFilter = "(uid={0})";
        }

        FilterBasedLdapUserSearch userSearch = new FilterBasedLdapUserSearch(
                ldapBase, ldapUserSearchFilter, ldapContextSource);
        userSearch.setSearchSubtree(true);

        BindAuthenticator bindAuthenticator = getBindAuthenticator(
                userSearch, ldapContextSource);

        LdapAuthenticationProvider ldapAuthenticationProvider = new LdapAuthenticationProvider(
                bindAuthenticator, defaultLdapAuthoritiesPopulator);

        if (userName != null && userPassword != null
                && !userName.trim().isEmpty()
                && !userPassword.trim().isEmpty()) {
            final List<GrantedAuthority> grantedAuths = getAuthorities(userName);
            final UserDetails principal = new User(userName, userPassword,
                    grantedAuths);
            final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(
                    principal, userPassword, grantedAuths);
            authentication = ldapAuthenticationProvider.authenticate(finalAuthentication);
            if(groupsFromUGI) {
                authentication = getAuthenticationWithGrantedAuthorityFromUGI(authentication);
            }
            return authentication;
        } else {
            LOG.error("LDAP Authentication::userName or userPassword is null or empty for userName "
                    + userName);
        }
    } catch (Exception e) {
        LOG.error(" getLdapBindAuthentication LDAP Authentication Failed:", e);
    }
    if (isDebugEnabled) {
        LOG.debug("<== AtlasLdapAuthenticationProvider getLdapBindAuthentication");
    }
    return authentication;
}
 
Example 19
Source File: RangerAuthenticationProvider.java    From ranger with Apache License 2.0 4 votes vote down vote up
public Authentication getUnixAuthentication(Authentication authentication) {

		try {
			String rangerLdapDefaultRole = PropertiesUtil.getProperty(
					"ranger.ldap.default.role", "ROLE_USER");
			DefaultJaasAuthenticationProvider jaasAuthenticationProvider = new DefaultJaasAuthenticationProvider();
			String loginModuleName = "org.apache.ranger.authentication.unix.jaas.RemoteUnixLoginModule";
			LoginModuleControlFlag controlFlag = LoginModuleControlFlag.REQUIRED;
			Map<String, String> options = PropertiesUtil.getPropertiesMap();
			AppConfigurationEntry appConfigurationEntry = new AppConfigurationEntry(
					loginModuleName, controlFlag, options);
			AppConfigurationEntry[] appConfigurationEntries = new AppConfigurationEntry[] { appConfigurationEntry };
			Map<String, AppConfigurationEntry[]> appConfigurationEntriesOptions = new HashMap<String, AppConfigurationEntry[]>();
			appConfigurationEntriesOptions.put("SPRINGSECURITY",
					appConfigurationEntries);
			Configuration configuration = new InMemoryConfiguration(
					appConfigurationEntriesOptions);
			jaasAuthenticationProvider.setConfiguration(configuration);
			RoleUserAuthorityGranter authorityGranter = new RoleUserAuthorityGranter();
			RoleUserAuthorityGranter[] authorityGranters = new RoleUserAuthorityGranter[] { authorityGranter };
			jaasAuthenticationProvider.setAuthorityGranters(authorityGranters);
			jaasAuthenticationProvider.afterPropertiesSet();
			String userName = authentication.getName();
			String userPassword = "";
			if (authentication.getCredentials() != null) {
				userPassword = authentication.getCredentials().toString();
			}

			// getting user authenticated
			if (userName != null && userPassword != null
					&& !userName.trim().isEmpty()
					&& !userPassword.trim().isEmpty()) {
				final List<GrantedAuthority> grantedAuths = new ArrayList<>();
				grantedAuths.add(new SimpleGrantedAuthority(
						rangerLdapDefaultRole));
				final UserDetails principal = new User(userName, userPassword,
						grantedAuths);
				final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(
						principal, userPassword, grantedAuths);
				authentication = jaasAuthenticationProvider
						.authenticate(finalAuthentication);
				authentication=getAuthenticationWithGrantedAuthority(authentication);
				return authentication;
			} else {
				return authentication;
			}
		} catch (Exception e) {
			logger.debug("Unix Authentication Failed:", e);
		}

		return authentication;
	}
 
Example 20
Source File: MobileTokenAuthenticationProvider.java    From Taroco with Apache License 2.0 4 votes vote down vote up
@Override
protected Authentication createSuccessAuthentication(final Object principal, final Authentication authentication, final UserDetails user) {
    final MobileTokenAuthenticationToken token = new MobileTokenAuthenticationToken(principal, authentication.getCredentials(), user.getAuthorities());
    token.setDetails(authentication.getDetails());
    return token;
}