Spring Boot教程第37篇:SpringBoot整合SpringSecurity

  1. 准备工作
    创建一个springBoot项目,解压附件java压缩包将对应的文件分别放到

在这里插入图片描述在这里插入图片描述
2. 引入依赖

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

3.创建security配置类

@EnableWebSecurity
public class MySecurityConfig extends WebSecurityConfigurerAdapter {

    //定义授权规则
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //访问/任意角色 访问/level1下的所有角色必须要有权限VIP1
        http.authorizeRequests().antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("VIP1")
                .antMatchers("/level2/**").hasRole("VIP2")
                .antMatchers("/level3/**").hasRole("VIP3");
        //开启自动配置的登录页  user和pwd 为登录页上的用户名和密码的参数名
         http.formLogin().usernameParameter("user").passwordParameter("pwd").loginPage("/userlogin");
//        //1. /login请求来到登录页
//        //2. 重定向/login?error表示登陆失败
//
//        //注销成功后来到/
        http.logout();
        //1. 访问/logout 表示用户会注销,清空sessin
        //2. 注销成功后会返回 /login?logout页面

        //开启记住我功能 remeber为登录页上的记住我参数名
        http.rememberMe().rememberMeParameter("remeber");
    }

    //定义认证规则
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("zhangsan").password(new BCryptPasswordEncoder().encode("123456")).roles("VIP1","VIP2")
                .and()
                .withUser("lisi").password(new BCryptPasswordEncoder().encode("123456")).roles("VIP2","VIP3")
                .and()
                .withUser("wangwu").password(new BCryptPasswordEncoder().encode("123456")).roles("VIP1","VIP3");
}
}

附上源码:在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值