05 Spring Boot 整合Spring Security

整合Spring Security

整合方法

  1. 创建项目时选择security依赖或在pom中添加security依赖

  2. 建立SpringSecurityConfig类,继承WebSecurityConfigurerAdapter方法

  3. 在刚刚创建的类上添加@EnableWebSecurity注解

  4. 设置授权规则

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/").permitAll()					//所有人均可访问
                .antMatchers("/level1/**").hasRole("vip1")		//vip1可访问
                .antMatchers("/level2/**").hasRole("vip2")		//vip3可访问
                .antMatchers("/level3/**").hasRole("vip3");		//vip3可访问
        
        http.formLogin()						//启动security自带login页面
            .loginPage("/toLogin")				//设置自定义login页面
            .loginProcessingUrl("/login")		//设置自定义login认证页面
            .usernameParameter("user")			//设置login页面中的账户参数名
            .passwordParameter("pwd");			//设置login页面中的密码参数名
        http.logout()							//logout:添加登出页面
            .logoutSuccessUrl("/");				//logoutSuccessUrl:添加登出后跳转页面
        http.rememberMe()						//开启记住我功能
            .rememberMeParameter("rem");		//设置记住我参数名
    }
  5. 设置角色

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("shimeath").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2", "vip3")
                .and()
                .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1", "vip2", "vip3")
                .and()
                .withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
    }

Spring security整合thymeleaf

  1. 添加maven依赖

    <dependency>
        <groupId>org.thymeleaf.extras</groupId>
        <artifactId>thymeleaf-extras-springsecurity5</artifactId>
    </dependency>

    2.添加命名空间

    xmlns:sec="http://www.thymeleaf.org/extras/spring-security"
  2. 常用方法

    sec:authorize		<!-- 授权 -->
    sec:authentication  <!-- 认证方式 -->
    <!-- 函数 -->
    isAuthenticated()	<!-- 已登录吗 -->
    hasRole('vip1')		<!-- 判断角色 -->
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值