下面列出了怎么用org.springframework.security.authentication.CredentialsExpiredException的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
JWTAuthentication jwtAuthentication = (JWTAuthentication) authentication;
JwtClaims claims = jwtAuthentication.getClaims();
Long referenceTime = System.currentTimeMillis();
Long expiryTime = claims.getExpiryTime();
if (expiryTime == null || (expiryTime * 1000L) < referenceTime) {
dataAccessor.removeExpired(claims.getTokenId());
throw new CredentialsExpiredException("JWT is expired");
}
Long notBefore = claims.getNotBefore();
if (notBefore == null || (notBefore * 1000L) > referenceTime) {
throw new CredentialsExpiredException("JWT not valid yet");
}
jwtAuthentication.setAuthenticated(true);
return jwtAuthentication;
}
@Override
protected UserDetails loadUserDetails(Assertion assertion) {
if (assertion == null) {
throw new CredentialsExpiredException("bad assertion");
}
ManagedUser user = parseUserDetails(assertion);
// create user if not exists
KylinUserManager kylinUserManager = KylinUserManager.getInstance(KylinConfig.getInstanceFromEnv());
ManagedUser existUser = kylinUserManager.get(user.getUsername());
if (existUser == null) {
kylinUserManager.update(user);
}
return kylinUserManager.get(user.getUsername());
}
@Override
public void check(UserDetails user) {
if (!user.isCredentialsNonExpired()) {
log.debug("User account credentials have expired");
throw new CredentialsExpiredException(AbstractUserDetailsAuthenticationProvider.this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.credentialsExpired", "User credentials have expired"));
}
}
@DataProvider
public static List<List<Throwable>> unauthorized401ExceptionsDataProvider() {
return Stream.<Throwable>of(
new BadCredentialsException("foo"),
new InsufficientAuthenticationException("foo"),
new AuthenticationCredentialsNotFoundException("foo"),
new LockedException("foo"),
new DisabledException("foo"),
new CredentialsExpiredException("foo"),
new AccountExpiredException("foo"),
new UsernameNotFoundException("foo"),
new RemoteAuthenticationException("foo")
).map(Collections::singletonList)
.collect(Collectors.toList());
}
/**
* Simple login check on cart object.
*
* @throws org.springframework.security.core.AuthenticationException thrown if user is not logged in or login expired
*/
public void throwSecurityExceptionIfNotLoggedIn() throws AuthenticationException {
final int state = getCurrentCart().getLogonState();
if (state != ShoppingCart.LOGGED_IN) {
if (state == ShoppingCart.SESSION_EXPIRED) {
throw new CredentialsExpiredException("Session expired");
}
throw new BadCredentialsException("User not logged in");
}
}
public JWTAuthenticationFilter() {
super(new AntPathRequestMatcher(JWTUtil.AUTH_LOGIN_URL, "POST"));
this.setAuthenticationSuccessHandler((request, response, auth) -> {
final long now = System.currentTimeMillis();
final long expiry = now + this.getExpiryMs();
final String secret = this.getSecret();
JWTUtil.sendSuccessJWT(
this.systemName,
this.systemName,
auth.getName(),
auth.getAuthorities().stream()
.map(GrantedAuthority::getAuthority).collect(Collectors.toList()),
now,
expiry,
secret,
response
);
});
this.setAuthenticationFailureHandler((request, response, failed) -> {
if (failed instanceof CredentialsExpiredException) {
JWTUtil.sendFailureJWT(JWTUtil.CredentialsState.AUTH_CREDENTAILS_EXPIRED.name(), response);
} else {
JWTUtil.sendFailureJWT(JWTUtil.CredentialsState.AUTH_CREDENTAILS_INVALID.name(), response);
}
});
}
@Override
public SecurityContext loadContext(HttpRequestResponseHolder requestResponseHolder) {
/*HttpServletRequest request = WebHolder.getRequest().get();
String url = request.getMethod() + "|" + request.getRequestURL();
System.out.println("url:" +url);*/
String token = authStore.getToken(requestResponseHolder.getRequest(), authHeaderName);
if(logger.isDebugEnabled()){
logger.debug("load context user token : {}", token);
}
if(StringUtils.isBlank(token)){
return SecurityContextHolder.createEmptyContext();
}
SecurityContext context = SecurityContextHolder.getContext();
Authentication authentication = null;
try {
authentication = jwtTokenService.createAuthentication(token);
} catch(CredentialsExpiredException e){
cookieStorer.clear(requestResponseHolder.getRequest(), requestResponseHolder.getResponse(), authHeaderName);
}
if(authentication!=null){
context.setAuthentication(authentication);
}
return context;
}
@Override
protected UserDetails loadUserDetails(Assertion assertion) {
if (assertion == null) {
throw new CredentialsExpiredException("bad assertion");
}
ManagedUser user = parseUserDetails(assertion);
// create user if not exists
KylinUserManager kylinUserManager = KylinUserManager.getInstance(KylinConfig.getInstanceFromEnv());
ManagedUser existUser = kylinUserManager.get(user.getUsername());
if (existUser == null) {
kylinUserManager.update(user);
}
return kylinUserManager.get(user.getUsername());
}
@Override
protected void additionalAuthenticationChecks(UserDetails userDetails,
UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
if (authentication.getCredentials() == null) {
logger.debug("Authentication failed: no credentials provided");
throw new BadCredentialsException(messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
}
String presentedPassword = authentication.getCredentials().toString();
String encoderSpecialization = (authentication.getCredentials() instanceof SaltToken)
? SALT_TOKEN_MECHANISM_SPECIALIZATION
: "";
if (!UserDetail.class.isAssignableFrom(userDetails.getClass())) {
throw new InternalAuthenticationServiceException("Retrieved user does not match expected class");
}
UserDetail userDetail = (UserDetail) userDetails;
Optional<UserCredential> matchedCred = userDetail.getCredentials().parallelStream()
.filter(c -> getPasswordEncoder().matches(presentedPassword, "{" + c.getEncoder() + encoderSpecialization + "}" + c.getCredential()))
.findAny();
if (!matchedCred.isPresent()) {
logger.debug("Authentication failed: password does not match any stored values");
throw new BadCredentialsException(messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
}
Instant expiration = matchedCred.map(UserCredential::getExpiration).orElse(null);
if (expiration != null && expiration.isBefore(Instant.now())) {
logger.debug("User account credentials have expired");
throw new CredentialsExpiredException(messages.getMessage("AbstractUserDetailsAuthenticationProvider.credentialsExpired", "User credentials have expired"));
}
// perform upgrade if needed for password-based auth
if ("".equals(encoderSpecialization) && getPasswordEncoder().upgradeEncoding("{" + matchedCred.get().getEncoder() + "}" + matchedCred.get().getCredential())) {
UserCredential upgraded = new UserCredential(matchedCred.get());
upgraded.setCredential(authentication.getCredentials().toString());
if (!securityService.updateCredentials(matchedCred.get(), upgraded, upgraded.getComment() + " | Automatically upgraded by system", true)) {
logger.debug("Password needs to be upgraded, but failed");
}
}
}
@Override
protected void doFilterInternal(final HttpServletRequest request,
final HttpServletResponse response,
final FilterChain chain) throws ServletException, IOException {
if (requiresChangePwdRequestMatcher.matches(request)) {
final boolean debug = this.logger.isDebugEnabled();
try {
LoginData creds = objectMapper
.readValue(request.getInputStream(), LoginData.class);
if (debug) {
this.logger
.info("Change password for user '"
+ (creds != null ? creds.getUsername() : "N/A") + "'");
}
if (creds != null && StringUtils.isNotBlank(creds.getUsername()) && StringUtils.isNotBlank(creds.getPassword())) {
try {
final Authentication auth = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(creds.getUsername(), creds.getPassword()));
if (!auth.isAuthenticated()) {
this.logger
.info("Change password for user '"
+ creds.getUsername() + "' bad credentials");
sendResponse(response, JWTUtil.CredentialsState.AUTH_CREDENTAILS_INVALID.name());
return;
}
this.logger
.info("Change password for user '"
+ creds.getUsername() + "' still valid old credentials");
} catch (CredentialsExpiredException cee) {
// OK this is what we are here for
this.logger
.info("Change password for user '"
+ creds.getUsername() + "' old credentials expired ");
} catch (AuthenticationException ae) {
sendResponse(response, JWTUtil.CredentialsState.AUTH_CREDENTAILS_INVALID.name());
return;
}
final String pass2 = creds.getNpassword();
final String pass2c = creds.getCpassword();
if (creds.getPassword().equalsIgnoreCase(pass2)) {
this.logger
.info("Change password for user '"
+ creds.getUsername() + "' cannot use previous password ");
sendResponse(response, JWTUtil.CredentialsState.AUTH_CHANGEPWD_SAMEASOLD.name());
return;
} else if (StringUtils.isBlank(pass2) || StringUtils.isBlank(pass2c) || !pass2.equals(pass2c)) {
this.logger
.info("Change password for user '"
+ creds.getUsername() + "' new and confirm don't match ");
sendResponse(response, JWTUtil.CredentialsState.AUTH_CHANGEPWD_NOMATCH.name());
return;
} else {
try {
managementService.updatePassword(creds.getUsername(), pass2, request.getLocale().getLanguage());
new SecurityContextLogoutHandler().logout(request, null, null);
this.logger
.info("Change password for user '"
+ creds.getUsername() + "' changed successfully ");
sendResponse(response, null);
return;
} catch (BadCredentialsException bce) {
this.logger
.info("Change password for user '"
+ creds.getUsername() + "' new credentials invalid ");
sendResponse(response, bce.getMessage());
return;
}
}
}
} catch (AuthenticationException failed) {
SecurityContextHolder.clearContext();
if (debug) {
this.logger.debug("Change password failed: " + failed);
}
sendResponse(response, failed.getMessage());
return;
}
}
chain.doFilter(request, response);
}
@Override
public String changePassword(final HttpServletRequest request) {
String user = request.getParameter("j_username");
final String pass = request.getParameter("j_password");
request.setAttribute("j_username", user);
if (StringUtils.isNotBlank(user) && StringUtils.isNotBlank(pass)) {
boolean changePass = false;
try {
final Authentication auth = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(user, pass));
if (!auth.isAuthenticated()) {
request.setAttribute("error", "auth");
} else {
changePass = true;
}
} catch (CredentialsExpiredException cee) {
// OK this is what we are here for
request.setAttribute("expired", "expired");
changePass = true;
} catch (AuthenticationException ae) {
request.setAttribute("error", "auth");
}
if (changePass) {
final String pass2 = request.getParameter("j_password2");
final String pass2c = request.getParameter("j_password2c");
if (pass.equals(pass2)) {
request.setAttribute("error", "sameasold");
} else if (StringUtils.isBlank(pass2) || StringUtils.isBlank(pass2c) || !pass2.equals(pass2c)) {
request.setAttribute("error", "nomatch");
} else {
try {
managementService.updatePassword(user, pass2, request.getLocale().getLanguage());
new SecurityContextLogoutHandler().logout(request, null, null);
return "redirect:login.jsp?newpass";
} catch (BadCredentialsException bce) {
request.setAttribute("error", bce.getMessage());
}
}
}
}
return "changepassword";
}