Spring boot 安全配置 - 必须指定 authenticationManager [英] Spring boot Security Config - authenticationManager must be specified

查看:27
本文介绍了Spring boot 安全配置 - 必须指定 authenticationManager的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的主要应用程序配置

Here's my main Application config

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        new SpringApplicationBuilder(Application.class)
                .banner((environment, aClass,  printStream) ->
                        System.out.println(stringBanner()))
                .run();
    }
}

这是我的 spring 安全应用程序配置.

And here's my spring security application config.

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableWebMvcSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private WebServiceAuthenticationEntryPoint unauthorizedHandler;

    @Autowired
    private TokenProcessingFilter authTokenProcessingFilter;

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

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf()
                .disable()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS) // Restful hence stateless
                .and()
                .exceptionHandling()
                .authenticationEntryPoint(unauthorizedHandler) // Notice the entry point
                .and()
                .addFilter(authTokenProcessingFilter) // Notice the filter
                .authorizeRequests()
                .antMatchers("/resources/**", "/api/auth")
                .permitAll()
                .antMatchers("/greeting")
                .hasRole("USER");
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .inMemoryAuthentication()
                .withUser("user")
                .password("password")
                .roles("USER");
    }
}

这是我的 TokenProcessingFilter,它为我的自定义身份验证过滤器扩展了 UsernamePasswordAuthenticationFilter

Here's my TokenProcessingFilter that extends UsernamePasswordAuthenticationFilter for my custom authentication filter

@Component
public class TokenProcessingFilter extends UsernamePasswordAuthenticationFilter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = this.getAsHttpRequest(request);
        String authToken = this.extractAuthTokenFromRequest(httpRequest);
        String userName = TokenUtils.getUserNameFromToken(authToken);
        if (userName != null) {/*
            UserDetails userDetails = userDetailsService.loadUserByUsername(userName);*/
            UserDetails userDetails = fakeUserDetails();
            if (TokenUtils.validateToken(authToken, userDetails)) {
                UsernamePasswordAuthenticationToken authentication =
                        new UsernamePasswordAuthenticationToken(userDetails.getUsername(), userDetails.getPassword(), userDetails.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpRequest));
                SecurityContextHolder.getContext().setAuthentication(authentication);
                Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            }
        }
        chain.doFilter(request, response);
    }

    private HttpServletRequest getAsHttpRequest(ServletRequest request){
        if (!(request instanceof HttpServletRequest)) {
            throw new RuntimeException("Expecting an HTTP request");
        }
        return (HttpServletRequest) request;
    }


    private String extractAuthTokenFromRequest(HttpServletRequest httpRequest) {
        /* Get token from header */
        String authToken = httpRequest.getHeader("x-auth-token");
        /* If token not found get it from request parameter */
        if (authToken == null) {
            authToken = httpRequest.getParameter("token");
        }
        return authToken;
    }

    private UserDetails fakeUserDetails(){
        UsernamePasswordAuthenticationToken authenticationToken = new
                UsernamePasswordAuthenticationToken("user","password");

        List<SimpleGrantedAuthority> auth= new ArrayList<>();
        auth.add(new SimpleGrantedAuthority("USER"));
        return  new User("user","password",auth);
    }
}

但是在运行应用程序时,我遇到了此异常消息.我错过了什么?

however when running the application, I encounter this exception message. What am I missing?

运行时发生异常.空:调用目标异常:无法启动嵌入式容器;嵌套异常是org.springframework.boot.context.embedded.EmbeddedServletContainerException:无法启动嵌入式 Tomcat:使用名称创建 bean 时出错文件中定义的tokenProcessingFilter"[C:\Users\kyel\projects\app\target\classes\org\app\testapp\security\TokenProcessingFilter.class]:init 方法调用失败;嵌套异常是java.lang.IllegalArgumentException: authenticationManager 必须是指定

An exception occured while running. null: InvocationTargetException: Unable to start embedded container; nested exception is org.springframework.boot.context.embedded.EmbeddedServletContainerException: Unable to start embedded Tomcat: Error creating bean with name 'tokenProcessingFilter' defined in file [C:\Users\kyel\projects\app\target\classes\org\app\testapp\security\TokenProcessingFilter.class]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: authenticationManager must be specified

推荐答案

您需要在 TokenProcessingFilter 上设置 AuthenticationManager.不要在 TokenProcessingFilter 上使用 @Component,只需在 SecurityConfig 中创建它.

You need to set the AuthenticationManager on TokenProcessingFilter. Instead of using @Component on TokenProcessingFilter, just create it in the SecurityConfig.

@Bean
TokenProcessingFilter tokenProcessingFilter() {
  TokenProcessingFilter tokenProcessingFilter = new TokenProcessingFilter();
  tokenProcessingFilter.setAuthenticationManager(authenticationManager());
  return tokenProcessingFilter;
}

protected void configure(HttpSecurity http) throws Exception {
  ...
  .addFilter(tokenProcessingFilter())

这篇关于Spring boot 安全配置 - 必须指定 authenticationManager的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆