程序问答   发布时间:2022-06-02  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了Spring Boot Security Config-必须指定authenticationManager大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决Spring Boot Security Config-必须指定authenticationManager?

开发过程中遇到Spring Boot Security Config-必须指定authenticationManager的问题如何解决?下面主要结合日常开发的经验,给出你关于Spring Boot Security Config-必须指定authenticationManager的解决方法建议,希望对你解决Spring Boot Security Config-必须指定authenticationManager有所启发或帮助;

您需要设置AuthenticationManageronTokenProcessingFilter。与其在TokenProcessingFilter上使用@Component,不如在SecurityConfig中创建它。

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

protected voID configure(httpSecurity http) throws Exception {
  ...
  .addFilter(tokenProcessingFilter())

解决方法

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

@SpringBootApplication
public class Application {

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

这是我的Spring安全应用程序配置。

@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

@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);
    }
}

但是,在运行应用程序时,我会遇到此异常消息。我想念什么?

大佬总结

以上是大佬教程为你收集整理的Spring Boot Security Config-必须指定authenticationManager全部内容,希望文章能够帮你解决Spring Boot Security Config-必须指定authenticationManager所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。