如何在自定义筛选器中使用Java配置注入AuthenticationManager [英] How To Inject AuthenticationManager using Java Configuration in a Custom Filter
问题描述
我正在使用Spring Security 3.2和Spring 4.0.1
我正在努力将xml配置转换为Java配置。当我在我的过滤器中使用 @Autowired
注释 AuthenticationManager
时,我收到异常
由以下原因引起:org.springframework.beans.factory.NoSuchBeanDefinitionException:没有找到类型为[org.springframework.security.authentication.AuthenticationManager]的限定bean用于依赖:预计至少有1个bean可以作为此依赖项的autowire候选者。依赖注释:{}
我试过注入 AuthenticationManagerFactoryBean
但是也会因类似的异常而失败。
这是我正在使用的XML配置
< pre class =lang-xml prettyprint-override>
<?xml version =1.0encoding =UTF-8?> < beans ...>
< security:authentication-manager id =authenticationManager>
< security:authentication-provider user-service-ref =userDao>
< security:password-encoder ref =passwordEncoder/>
< / security:authentication-provider>
< / security:authentication-manager>
< security:http
realm =受保护的API
use-expressions =true
auto-config =false
create -session =无状态
entry-point-ref =unauthorizedEntryPoint
authentication-manager-ref =authenticationManager>
< security:access-denied-handler ref =accessDeniedHandler/>
< security:custom-filter ref =tokenAuthenticationProcessingFilterposition =FORM_LOGIN_FILTER/>
< security:custom-filter ref =tokenFilterposition =REMEMBER_ME_FILTER/>
< security:intercept-url method =GETpattern =/ rest / news / **access =hasRole('user')/>
< security:intercept-url method =PUTpattern =/ rest / news / **access =hasRole('admin')/>
< security:intercept-url method =POSTpattern =/ rest / news / **access =hasRole('admin')/>
< security:intercept-url method =DELETEpattern =/ rest / news / **access =hasRole('admin')/>
< / security:http>
< bean class =com.unsubcentral.security.TokenAuthenticationProcessingFilter
id =tokenAuthenticationProcessingFilter>
< constructor-arg value =/ rest / user / authenticate/>
< property name =authenticationManagerref =authenticationManager/>
< property name =authenticationSuccessHandlerref =authenticationSuccessHandler/>
< property name =authenticationFailureHandlerref =authenticationFailureHandler/>
< / bean>
< / beans>
这是Java Config我正在尝试
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
private AuthenticationEntryPoint authenticationEntryPoint;
@Autowired
private AccessDeniedHandler accessDeniedHandler;
@Override
protected void configure(AuthenticationManagerBuilder auth)抛出异常{
auth
.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
}
@Override
protected void configure(HttpSecurity http)抛出异常{
http
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy) .STATELESS)
。和()
.exceptionHandling()
.authenticationEntryPoint(authenticationEntryPoint)
.accessDeniedHandler(accessDeniedHandler)
.and();
// TODO:自定义过滤器
}
}
这是Custom Filter类。给我带来麻烦的一行是AuthenticationManager的setter
@Component
公共类TokenAuthenticationProcessingFilter扩展AbstractAuthenticationProcessingFilter {
@Autowired
public TokenAuthenticationProcessingFilter(@Value(/ rest / useAuthenticationManagerr / authenticate)String defaultFilterProcessesUrl){
super(defaultFilterProcessesUrl);
}
@Override
public身份验证attemptAuthentication(HttpServletRequest请求,HttpServletResponse响应)抛出AuthenticationException,IOException,ServletException {
...
}
private String obtainPassword(HttpServletRequest request){
return request.getParameter(password);
}
private String obtainUsername(HttpServletRequest request){
return request.getParameter(username);
}
@Autowired
@Override
public void setAuthenticationManager(AuthenticationManager authenticationManager){
super.setAuthenticationManager(authenticationManager);
}
@Autowired
@Override
public void setAuthenticationSuccessHandler(AuthenticationSuccessHandler successHandler){
super.setAuthenticationSuccessHandler(successHandler);
}
@Autowired
@Override
public void setAuthenticationFailureHandler(AuthenticationFailureHandler failureHandler){
super.setAuthenticationFailureHandler(failureHandler);
}
}
覆盖方法 authenticationManagerBean
在 WebSecurityConfigurerAdapter
中公开使用 configure(AuthenticationManagerBuilder)构建的AuthenticationManager
作为一个Spring bean:
例如:
@Bean(name = BeanIds.AUTHENTICATION_MANAGER)
@Override
public AuthenticationManager authenticationManagerBean()throws Exception {
return super.authenticationManagerBean();
}
I'm using Spring Security 3.2 and Spring 4.0.1
I'm working on converting an xml config into a Java config. When I annotate AuthenticationManager
with @Autowired
in my Filter, I'm getting an exception
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.security.authentication.AuthenticationManager] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
I've tried injecting AuthenticationManagerFactoryBean
but that also fails with a similar exception.
Here is the XML configuration I'm working from
<?xml version="1.0" encoding="UTF-8"?> <beans ...>
<security:authentication-manager id="authenticationManager">
<security:authentication-provider user-service-ref="userDao">
<security:password-encoder ref="passwordEncoder"/>
</security:authentication-provider>
</security:authentication-manager>
<security:http
realm="Protected API"
use-expressions="true"
auto-config="false"
create-session="stateless"
entry-point-ref="unauthorizedEntryPoint"
authentication-manager-ref="authenticationManager">
<security:access-denied-handler ref="accessDeniedHandler"/>
<security:custom-filter ref="tokenAuthenticationProcessingFilter" position="FORM_LOGIN_FILTER"/>
<security:custom-filter ref="tokenFilter" position="REMEMBER_ME_FILTER"/>
<security:intercept-url method="GET" pattern="/rest/news/**" access="hasRole('user')"/>
<security:intercept-url method="PUT" pattern="/rest/news/**" access="hasRole('admin')"/>
<security:intercept-url method="POST" pattern="/rest/news/**" access="hasRole('admin')"/>
<security:intercept-url method="DELETE" pattern="/rest/news/**" access="hasRole('admin')"/>
</security:http>
<bean class="com.unsubcentral.security.TokenAuthenticationProcessingFilter"
id="tokenAuthenticationProcessingFilter">
<constructor-arg value="/rest/user/authenticate"/>
<property name="authenticationManager" ref="authenticationManager"/>
<property name="authenticationSuccessHandler" ref="authenticationSuccessHandler"/>
<property name="authenticationFailureHandler" ref="authenticationFailureHandler"/>
</bean>
</beans>
Here is the Java Config I'm attempting
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
private AuthenticationEntryPoint authenticationEntryPoint;
@Autowired
private AccessDeniedHandler accessDeniedHandler;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.exceptionHandling()
.authenticationEntryPoint(authenticationEntryPoint)
.accessDeniedHandler(accessDeniedHandler)
.and();
//TODO: Custom Filters
}
}
And this is the Custom Filter class. The line giving me trouble is the setter for AuthenticationManager
@Component
public class TokenAuthenticationProcessingFilter extends AbstractAuthenticationProcessingFilter {
@Autowired
public TokenAuthenticationProcessingFilter(@Value("/rest/useAuthenticationManagerr/authenticate") String defaultFilterProcessesUrl) {
super(defaultFilterProcessesUrl);
}
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
...
}
private String obtainPassword(HttpServletRequest request) {
return request.getParameter("password");
}
private String obtainUsername(HttpServletRequest request) {
return request.getParameter("username");
}
@Autowired
@Override
public void setAuthenticationManager(AuthenticationManager authenticationManager) {
super.setAuthenticationManager(authenticationManager);
}
@Autowired
@Override
public void setAuthenticationSuccessHandler(AuthenticationSuccessHandler successHandler) {
super.setAuthenticationSuccessHandler(successHandler);
}
@Autowired
@Override
public void setAuthenticationFailureHandler(AuthenticationFailureHandler failureHandler) {
super.setAuthenticationFailureHandler(failureHandler);
}
}
Override method authenticationManagerBean
in WebSecurityConfigurerAdapter
to expose the AuthenticationManager built using configure(AuthenticationManagerBuilder)
as a Spring bean:
For example:
@Bean(name = BeanIds.AUTHENTICATION_MANAGER)
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
这篇关于如何在自定义筛选器中使用Java配置注入AuthenticationManager的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!