spring-security的简单配置

1.先导入依赖

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

2.进行配置

@EnableWebSecurity
public class SecurityConfig  extends WebSecurityConfigurerAdapter {

    // 授权
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        // 首页所有人都可以访问,功能页只有对应权限的人才能访问
        // 请求授权的规则
        http.authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/level1").hasRole("vip1")
                .antMatchers("/level2").hasRole("vip2")
                .antMatchers("level3").hasRole("vip3");

        // 没有权限的人会回到登录界面
        http.formLogin();

        // http注销功能
        http.logout().logoutSuccessUrl("/");

        // 记住我  接收前端参数
        http.rememberMe().rememberMeParameter("rememeber");
    }


    // 认证  密码要进行加密才能使用
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 这些数据正常应从数据库中读入
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1")
                .and()
                .withUser("user").password(new BCryptPasswordEncoder().encode("123")).roles("vip2", "vip3");
    }
}

版权声明:本文为qq_43352316原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。