springboot访问上传页面因csrf出现403的问题-古蔺大橙子建站
RELATEED CONSULTING
相关咨询
选择下列产品马上在线沟通
服务时间:8:30-17:00
你可能遇到了下面的问题
关闭右侧工具栏

新闻中心

这里有您想知道的互联网营销解决方案
springboot访问上传页面因csrf出现403的问题


@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

成都创新互联是一家专业提供康平企业网站建设,专注与网站建设、成都网站建设H5网站设计、小程序制作等业务。10年已为康平众多企业、政府机构等服务。创新互联专业网站设计公司优惠进行中。

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    MemDetailsService memDetailsService;


    @Autowired
    SimpleLoginSuccessHandler simpleLoginSuccessHandler;


    @Override
    //WebSecurity:For example, if you wish to ignore certain requests.
    //用于配置类似防火墙,放行某些URL。
    public void configure(WebSecurity web) throws Exception {
        // 设置不拦截规则
        //web.ignoring().antMatchers("/js/**", "/css/**", "/images/**", "/**/favicon.ico", "/swagger*/**", "/image/**", "/webjars/**","/v2/**");
        web.ignoring().antMatchers("/js/**", "/css/**", "/images/**", "/**/favicon.ico", "/image/**");
    }

    @Override
    //HttpSecurity:一般用它来具体控制权限,角色,url等安全的东西。
    protected void configure(HttpSecurity http) throws Exception {
        // 设置CSRF规则
        http.csrf().requireCsrfProtectionMatcher(new SimpleCsrfSecurityRequestMatcher()).and().
                // 设置拦截规则
                        authorizeRequests()
                .antMatchers("/api/**", "/index", "/updateIndex.html", "/browserIndex.html", "/policy-zcff.html", "/policy-hydj.html", "/policy-jf.html", "/policy-card.html", "/faq.html", "/cm/satCm01Init", "/cm/satCm01List", "/faq/satFaq01", "/logout", "/loginSso", "/bulterservice.html", "/verifySso").permitAll()
                .antMatchers("/autoconfig/**", "/beans/**", "/configprops/**", "/dump/**", "/env/**", "/health/**", "/info/**", "/metrics/**", "/mappings/**", "/shutdown/**", "/trace/**").access("hasRole('ADMIN')")
                .anyRequest().authenticated()
                .and().formLogin().loginPage("/login").usernameParameter("saID").passwordParameter("password").permitAll().defaultSuccessUrl("/home", true).failureForwardUrl("/index").successHandler(simpleLoginSuccessHandler)
                .and().logout().logoutUrl("/logout").logoutSuccessUrl("/index")
                .and().exceptionHandling().accessDeniedPage("/logout")
                .and().sessionManagement().maximumSessions(1).expiredUrl("/index");
    }

    @Override
    //用于配置Authentication,比如LDAP, Database连接,以及用户和角色的查询方法。
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
        daoAuthenticationProvider.setHideUserNotFoundExceptions(false);
        daoAuthenticationProvider.setUserDetailsService(memDetailsService);


        auth.authenticationProvider(daoAuthenticationProvider);
        //auth.userDetailsService(memDetailsService);
        //.passwordEncoder(new BCryptPasswordEncoder())
    }
}

要解决403访问权限问题 必须加http.csrf().requireCsrfProtectionMatcher(new SimpleCsrfSecurityRequestMatcher()
要把上传页面URL过滤掉才能解决403
SimpleCsrfSecurityRequestMatcher具体实现

public class SimpleCsrfSecurityRequestMatcher implements RequestMatcher {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private Pattern allowedMethods = Pattern
            .compile("^(GET|HEAD|TRACE|OPTIONS)$");


    @Override
    public boolean matches(HttpServletRequest request) {
        if (execludeUrls.size() > 0) {
            String servletPath = request.getServletPath();
            for (String url : execludeUrls) {
                if (servletPath.contains(url)) {
                    logger.debug("SimpleCsrfSecurityRequestMatcher排除的url:" + servletPath);
                    return false;
                }
            }
        }
        return !allowedMethods.matcher(request.getMethod()).matches();
    }

    /**
     * 需要排除的url列表
     */
    private final List execludeUrls = new ArrayList() {{
        add("/upload");
        add("/upload/uploadActivateAttachment");
        add("/buy02");
        add("/buy02/uploadActivationSel");

    }};
}


新闻名称:springboot访问上传页面因csrf出现403的问题
本文路径:http://scgulin.cn/article/jsgsgj.html