springboot整合spring security

springboot 要想使用spring security的模块需要导入相应的依赖

在pom文件中添加一下代码

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

然后编写一个简单的配置类 SecurityConfiger 这个配置类需要继承  WebSecurityConfigurerAdapter 这个抽象类

/*安全配置类*/
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)// 启用方法安全设置
public class SecurityConfig extends WebSecurityConfigurerAdapter {
}

并标上@EnableWebSecurity注解,打开这个注解

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Documented
@Import({WebSecurityConfiguration.class, SpringWebMvcImportSelector.class})
@EnableGlobalAuthentication
@Configuration
public @interface EnableWebSecurity {
    boolean debug() default false;
}

可以看到其中是包含了@Configuration注解的,表示这是一个配置类

然后我们需要重载configure方法以达到我们想要的结果

方法 描述
configure(WebSecurity webSecurity) 通过重载,配置SpringSecurity的Filter链
configure(HttpSecurity http) 通过重载,配置如何通过拦截器保护请求
configure(AuthenticationManagerBuilder auth) 通过重载,配置userdetail服务

以上方法不用全部重载,只需要根据具体需求进行重载,下面给出重载例子:


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/css/**","/fonts/**","/js/**","/index").permitAll()//对静态文件允许访问
                .antMatchers("/admins/**").hasRole("ADMIN")//有相应角色才能访问
                .and()
                .formLogin()//基于form表单登录验证 前往/login页面
                .loginPage("/login").failureUrl("/login-error")//自定义登录界面和失败界面
    }


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()//认证信息存储于内存中
            .withUser("root").password("123456").roles("ADMIN");
    }

以上就是springboot整合spring security的一个简单配置类,其中配置了对静态文件的访问权限,对一些特定页面的权限设置,以及对登录验证,登录页面,登录失败的配置;以及适用于生产环境的配置,将User信息保存于内存中

猜你喜欢

转载自blog.csdn.net/qq_40995335/article/details/81145876