Spring Boot、Spring Security登录认证及权限问题


目录

一、登录验证

1.自定义密码账号

Ⅰ.引入依赖

Ⅱ. XxxApplication启动类

Ⅲ. 在application.yml文件中自定义

Ⅳ.启动项目

2.从数据库中查找账号和密码 

Ⅰ.引入依赖

Ⅱ. application.yml文件

Ⅲ. bean包的操作

Ⅳ. service层

Ⅴ.config配置类 

Ⅵ.启动项目

二、权限问题

1.config类

2.bean包

3.service层

4.启动项目


一、登录验证

1.自定义密码账号

Ⅰ.引入依赖

先搭建好一个SpringBoot框架,在基础上引入依赖

<!--web-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <version>2.7.1</version>
</dependency>
<!--小辣椒-->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.24</version>
</dependency>
<!--spring security-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

Ⅱ. XxxApplication启动类

@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class,args);
    }
}

Ⅲ. 在application.yml文件中自定义

spring:
  security:
    user:
      name: porsche
      password: 911

Ⅳ.启动项目

运行项目,在网页中输入账号密码。

2.从数据库中查找账号和密码 

Ⅰ.引入依赖

<!--mysql连接-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>
<!--mybatis plus-->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.5.1</version>
</dependency>
<!--druid-->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.2.9</version>
</dependency>

Ⅱ. application.yml文件

server:
  port: 8080
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: bjwl
    password: bjwl
    url: jdbc:mysql://192.168.1.118:3306/book_store?serverTimezone=Asia/Shanghai&useSSL=false&allowPublicKeyRetrieval=true
    type: com.alibaba.druid.pool.DruidDataSource
mybatis-plus:
  configuration:
    map-underscore-to-camel-case: false 
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

Ⅲ. bean包的操作

实体类:

@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName("user")
public class Users implements Serializable {

    private Integer id;
    private String userName;
    private String passWord;
    private String nickName;
    private Integer state;
}

LoginUsers类:

@AllArgsConstructor
@NoArgsConstructor
public class LoginUsers implements UserDetails {
    private Users users;

    //返回当前用户的所有权限
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return users.getList();
    }

    //返回密码
    public String getPassword() {
        return users.getPassWord();
    }

    //返回用户名
    public String getUsername() {
        return users.getUserName();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}

Ⅳ. service层

// 是SpringSecurity的业务类,负责实现认证和授权
@Service
public class UsersService implements UserDetailsService {
    @Resource
    private UsersMapper mapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<Users> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        Users users = mapper.selectOne(wrapper);//查询一条记录
        if (Objects.isNull(users)) {
            throw new RuntimeException("用户名没有找到");
        }
        return new LoginUsers(users);
    }
}

Ⅴ.config配置类 

/*
它是SpringSecurity的配置类
 */
@Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
    @Resource
    private UsersService usersService;

    @Bean
    public PasswordEncoder getPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    //数据库的认证
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(usersService).passwordEncoder(getPasswordEncoder());
    }
}

Ⅵ.启动项目

 此时后台也会显示出,在数据库中查询了一次

二、权限问题

1.config类

在类中设置权限,和设置权限名,给1.html只开启了abc01的权限,给2.html开启了abc01和abc02的权限。

也就是说abc01可以访问1.html和2.html,abc02只可以访问2.html

protected void configure(HttpSecurity http) throws Exception {
    http.formLogin()
            .loginPage("/login.html")   //登录页面设置
            .loginProcessingUrl("/a/lo")    //登录访问路径  这里同 login.html中的action
            .permitAll()
            .and().exceptionHandling().accessDeniedPage("/403.html")
            .and().authorizeRequests()
            .antMatchers("/login.html", "/a/lo").permitAll()    //设置哪些路径可以直接访问,不需要认证
            .antMatchers("/1.html").hasAuthority("adc01")   //设置当前网页访问权限
            .antMatchers("/2.html").hasAnyAuthority("abc01","abc02")
            .anyRequest().authenticated()   //所有请求都可以访问
            .and().csrf().disable();    //关闭csrf,csrf:跨站请求伪造
}

2.bean包

在实体类中加入

@TableField(exist = false)
private List<GrantedAuthority> list;

3.service层

为用户设置权限名

List<GrantedAuthority> list = new ArrayList<>();
list.add(new SimpleGrantedAuthority("abc02"));
users.setList(list);

4.启动项目

登录

访问1.html

访问2.html

 


猜你喜欢

转载自blog.csdn.net/weixin_55166132/article/details/125509739