下面列出了org.springframework.security.core.Authentication#getCredentials ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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);
}
}
@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;
}
@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));
}
}
@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;
}
/**
* 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;
}
@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);
}
@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());
}
}
@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;
}
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);
}
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;
}
}
/**
* 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;
}
@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.");
}
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();
}
@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;
}
@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.");
}
@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"));
}
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;
}
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;
}
}
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;
}
@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;
}