springboot-springsecurity:用户认证和授权

承接:springboot-springsecurity:测试环境搭建

1 引入springsecurity依赖

pom.xml

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

2 创建config包,并在该包下编写SecurityConfig.java

src/main/java/com/lv/config/SecurityConfig.java

package com.lv.config;

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.crypto.bcrypt.BCryptPasswordEncoder;

//AOP : 拦截器!
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    //授权
    @Override
    public void configure(HttpSecurity http) throws Exception {
        //首页所有人都可以访问,功能页只有对应的有权限的人才能访问
        //请求授权的规则~(链式编程)
        http.authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("vip1")
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3");

        //没有权限默认会跳转到登录页,需要开启登录页面
        http.formLogin();
    }
    //认证,springboot 2.1.x 可以直接使用
    //密码编码:PasswordEncoder
    //在Spring Security 5.0+ 新增了很多加密方法~
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //这些数据正常应该从数据库中读
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("lv").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");
    }
}

3 启动项目测试

访问主页

在未登录状态下访问任何页面,都会跳到登录页面

登录 lv 账户,该账户可以访问level2和level3,不能访问level1

登录成功后,点击level1里的链接

访问失败,返回主页再点击level2和level3里的链接

level2和level3的页面可以成功访问,由此说明 lv 用户权限设置和用户认证成功,剩下的 root 用户和 guest 用户测试流程与 lv 测试流程相同,这里就不演示了

posted @ 2022-03-08 08:21  从0开始丿  阅读(284)  评论(0编辑  收藏  举报