springboot 访问上传页面因csrf出现403的问题

简介: @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) public class WebSecurityConfig extends We...


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

    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");

    }};
}

目录
相关文章
|
1月前
|
JavaScript 前端开发 Java
springboot从控制器请求至页面时js失效的解决方法
springboot从控制器请求至页面时js失效的解决方法
15 0
springboot从控制器请求至页面时js失效的解决方法
|
1月前
|
Java 数据库连接 mybatis
springboot访问jsp页面变成直接下载?
springboot访问jsp页面变成直接下载?
31 0
|
1月前
|
JavaScript 前端开发
springboot+layui从控制器请求至页面时js失效的解决方法
springboot+layui从控制器请求至页面时js失效的解决方法
15 0
|
4月前
|
Java 应用服务中间件 API
SpringBoot项目 Tomcat部署war程序时启动成功但是访问404异常处理
SpringBoot项目 Tomcat部署war程序时启动成功但是访问404异常处理
81 0
|
4月前
|
XML Java 数据库连接
Spring Boot的数据访问之Spring Data JPA以及Hibernate的实战(超详细 附源码)
Spring Boot的数据访问之Spring Data JPA以及Hibernate的实战(超详细 附源码)
47 0
|
22天前
|
Java
SpringBoot配置图片访问404SpringBoot配置图片访问路径springboot如何访问图片
SpringBoot配置图片访问404SpringBoot配置图片访问路径springboot如何访问图片
6 0
|
1月前
|
XML Java 数据格式
springboot 微服务项目如何集成 html 页面
springboot 微服务项目如何集成 html 页面
29 0
|
1月前
|
安全 Java 数据安全/隐私保护
SpringBoot启动后出现Please sign in页面
项目启动后,出现莫名其妙的Please sign in页面
38 0
|
3月前
|
前端开发 JavaScript Java
springboot 出现 Cannot resolve MVC View ‘index‘ 问题解决办法,前后端不分离项目前端文件存放位置,已经如何访问
springboot 出现 Cannot resolve MVC View ‘index‘ 问题解决办法,前后端不分离项目前端文件存放位置,已经如何访问
104 0
|
3月前
|
Java
SpringBoot thymeleaf自定义错误页面
SpringBoot thymeleaf自定义错误页面
22 0

热门文章

最新文章