如何在grails中创建自定义UsernamePasswordAuthenticationFilter?我想自定义以下方法。
1. attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
2. successfulAuthentication(HttpServletRequest request,HttpServletResponse response, Authentication authResult)
3. unsuccessfulAuthentication(HttpServletRequest request,HttpServletResponse response, AuthenticationException failed)
答案 0 :(得分:1)
您需要实现自己的扩展AbstractAuthenticationProcessingFilter
(或其中一个子类)的类,然后通过在authenticationProcessingFilter
中定义名为conf/spring/resources.groovy
的spring bean来替换默认的身份验证处理过滤器。
以下是使用X509证书进行身份验证的示例,而不是用户名和密码。
class AuthenticationProcessingFilter extends RequestHolderAuthenticationFilter {
@Override
Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException {
X509Certificate[] clientCertificates = request.getAttribute('javax.servlet.request.X509Certificate')
X509Certificate clientCertificate = clientCertificates ? clientCertificates[0] : null
Authentication authentication = new X509Authentication(clientCertificate)
authenticationManager.authenticate(authentication)
}
}
authenticationProcessingFilter(AuthenticationProcessingFilter) {
authenticationManager = ref('authenticationManager')
sessionAuthenticationStrategy = ref('sessionAuthenticationStrategy')
authenticationSuccessHandler = ref('authenticationSuccessHandler')
authenticationFailureHandler = ref('authenticationFailureHandler')
rememberMeServices = ref('rememberMeServices')
authenticationDetailsSource = ref('authenticationDetailsSource')
filterProcessesUrl = conf.apf.filterProcessesUrl
usernameParameter = conf.apf.usernameParameter
passwordParameter = conf.apf.passwordParameter
continueChainBeforeSuccessfulAuthentication = conf.apf.continueChainBeforeSuccessfulAuthentication
allowSessionCreation = conf.apf.allowSessionCreation
postOnly = conf.apf.postOnly
}
如果你覆盖authenticationProcessingFilter
bean,你很可能也需要覆盖默认的daoAuthenticationProvider
bean。
authenticationProcessingFilter
bean负责读取身份验证数据(通常来自HTTP请求),从中创建Authentication
实例,并触发身份验证过程,但它是daoAuthenticationProvider
实际上执行身份验证。