当前位置: 首页 > 面试题库 >

如何在自定义过滤器中使用Java配置注入AuthenticationManager

张高义
2023-03-14
问题内容

我正在使用Spring Security 3.2和Spring 4.0.1

我正在将xml配置转换为Java配置。当我在“过滤器”中添加注释AuthenticationManager时@Autowired,出现异常

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: {}

我已经尝试了注入,AuthenticationManagerFactoryBean但是由于类似的异常也失败了。

这是我正在使用的XML配置

<?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>

这是我正在尝试的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) 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
    }
}

这是“自定义过滤器”类。给我麻烦的那一行是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

问题答案:

覆盖方法authenticationManagerBeanWebSecurityConfigurerAdapter的内置的AuthenticationManager使用揭露configure(AuthenticationManagerBuilder)作为一个Spring bean:

例如:

   @Bean(name = BeanIds.AUTHENTICATION_MANAGER)
   @Override
   public AuthenticationManager authenticationManagerBean() throws Exception {
       return super.authenticationManagerBean();
   }


 类似资料:
  • 我正在使用Spring Security 3.2和Spring 4.0.1 下面是我正在尝试的Java配置 这是自定义筛选器类。给我带来麻烦的是AuthenticationManager的setter

  • 我正在寻找一种有效地针对JUnit5集成测试的方法。测试使用gradle运行,所有集成测试类都由自定义类级别注释修饰。我可以根据它们的类名模式或通过使用标记对它们进行分类来筛选它们,但是有没有一种方法可以设置一个针对带有注释的测试的测试套件呢?

  • 我的问题是我的SpringConfig类中筛选器的配置。我希望筛选器仅在请求是/authenticate URL时生效,我已将.antmatcher(“/authenticate/**”)添加到筛选器配置中。 当所有其他URL中的该行不再安全时,我可以手动导航到/home,而不进行身份验证,删除该行并对/home进行身份验证。 我应该声明一个只适用于特定URL的筛选器吗? 我如何在维护其他URL的

  • 本文向大家介绍详解AngularJS中$filter过滤器使用(自定义过滤器),包括了详解AngularJS中$filter过滤器使用(自定义过滤器)的使用技巧和注意事项,需要的朋友参考一下 1.内置过滤器 2.自定义过滤器     套用上面的格式定义两个简单的自定义过滤器一个带条件的,一个不带条件的。 (1)【不带条件】,功能:固定转换(有时候项目中会遇到角色代号,门店编码什么的,但是显示的时候

  • 我试图添加一个过滤器,需要参数作为FilterConfig给出。我将它添加到WebApplication ation初始::onStartup(ServletContext容器)方法中,并且配置良好(init方法使用正确的FilterConfig调用)。 关键是我使用的是SpringSecurityWebSecurityConfigureAdapter,我的过滤器从未被调用过(不在过滤器链中)。如