SpringBoot+SpringSecurity+Druid解决CSRF开启问题

今天在用springboot2.0集成Druid的时候,访问http://localhost:8010/druid 的时候始终跳到下面这个界面(我设定项目工程启动端口是8010),开始还以为这就是德鲁伊的登录界面,输入账号密码一直登录不上,http://localhost:8010/login

image.png

猜想是不是拦截器拦截了,发现自己在创建项目的时候勾选了SpringSecurity,需要在配置安全访问时过滤路径;需要加上如下代码;

package com.ijustone.service.core.security;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.util.matcher.RequestMatcher;

import javax.servlet.http.HttpServletRequest;

@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() {
            @Override
            public boolean matches(HttpServletRequest httpServletRequest) {
                String servletPath = httpServletRequest.getServletPath();
                if (servletPath.contains("/druid")) {
                    return false;
                }
                return true;
            }
        }).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");
    }
}

再次访问:


image.png

就可以登录了。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容