实现 org.springframework.context.ApplicationListener 接口就可监听到认证失败的事件。
package com.uinte.auth.validator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.security.authentication.event.AuthenticationFailureBadCredentialsEvent;
import org.springframework.stereotype.Component;
import lombok.extern.slf4j.Slf4j;
@Component
public class AuthenticationFailureListener implements ApplicationListener<AuthenticationFailureBadCredentialsEvent> {
@Override
public void onApplicationEvent(AuthenticationFailureBadCredentialsEvent e) {
//在这里记录登陆失败的次数
String username = e.getAuthentication().getPrincipal().toString();
}
}
实现 org.springframework.security.oauth2.provider.OAuth2RequestValidator 接口可以在认证之前对请求进行校验
将UinteRequestValidator 注入到 AuthorizationServerEndpointsConfigurer 的属性(requestValidator)中
package com.uinte.auth.validator;
@Service("requestValidator")
public class UinteRequestValidator implements OAuth2RequestValidator {
@Override
public void validateScope(TokenRequest tokenRequest, ClientDetails client) throws InvalidScopeException {
//在这里检查用户的登陆失败次数
Map<String, String> requestParameters = tokenRequest.getRequestParameters();
String username = requestParameters.get("username");
}
}