springboot2.0.4集成druid和security解决CSRF开启问题

    最近使用springboot、security、druid做个项目的时候,登录druid监控页面时,刚开始集成完成后可以正常登陆,在项目做完后登录的时候发现无法登陆,输入用户名和密码admin,admin,点击sign in,怎么点都没反应,使用浏览器F12查看控制台信息,发现点击sign in时候,打印如下错误 

springboot2.0.4集成druid和security解决CSRF开启问题

解决方法
https://blog.csdn.net/juan0728juan/article/details/79624676


@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/").permitAll()
                .antMatchers("/hello").hasRole("USER").and()
                //.csrf().disable() //关闭CSRF
                .csrf().requireCsrfProtectionMatcher(new RequestMatcher() {
            //放行这几种请求
            private Pattern allowedMethods = Pattern.compile("^(GET|HEAD|TRACE|OPTIONS)$");
            //放行rest请求,当然后面rest与web将会分开,到时这里可以删除
            private RegexRequestMatcher unprotectedMatcher = new RegexRequestMatcher("^/rest/.*", null);

            @Override
            public boolean matches(HttpServletRequest request) {
                if(allowedMethods.matcher(request.getMethod()).matches()){
                    return false;
                }

                String servletPath = request.getServletPath();
                if (servletPath.contains("/druid")) {
                    return false;
                }
                return !unprotectedMatcher.matches(request);
            }
        }).and()
                .formLogin().loginPage("/login").defaultSuccessUrl("/hello").and()
                .logout().logoutUrl("/logout").logoutSuccessUrl("/login");
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .inMemoryAuthentication()
                .withUser("user").password("password").roles("USER");
    }
}

转载于:https://blog.51cto.com/357712148/2349713

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值