java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Spring Security持久化用户和授权

Spring Security的持久化用户和授权实现方式

作者:Exill

文章介绍了如何使用JdbcUserDetailsManager实现数据库读取用户,并展示了如何配置SpringSecurity进行授权管理,通过创建数据库表、配置数据库连接和修改SecurityConfig,实现了用户权限的控制

使用JdbcUserDetailsManager(UserDetailsService另一种实现)实现数据库读取用户

1.引入jdbc和相关数据库驱动

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <scope>runtime</scope>
</dependency>

2.创建数据库表

--用户表
CREATE TABLE users( 
    username VARCHAR(50)  NOT NULL PRIMARY KEY --用户名, 
    password VARCHAR(500) NOT NULL             --密码, 
    enabled  BOOLEAN      NOT NULL             --有效性
);
--权限表
CREATE TABLE authorities( 
    username  VARCHAR(50) NOT NULL  --用户名, 
    authority VARCHAR(50) NOT NULL  --权限, 
    constraint fk FOREIGN KEY(username) REFERENCES users(username)
);
CREATE unique index ix_auth_username ON authorities (username, authority);

3.配置数据库连接(application.yml)

spring:
    datasource:
        driver-class-name: org.postgresql.Driver
        url: jdbc:postgresql://localhost:5432/security
        username:postgres
        password: postgres

4.修改SecurityConfig配置

@Configuration
public class SecurityConfig {
    //配置Security过滤链
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        //配置哪些接口需要认证(.anyRequest().authenticated()代表任何请求都需认证)
        http.authorizeHttpRequests(authorize -> {
            authorize.anyRequest().authenticated();
        });
        //配置post表单请求/login接口
        http.formLogin(Customizer.withDefaults());
        //csrf攻击:开发环境可不配方便调试,上线环境需配置,否则会遭csrf攻击
        http.csrf(AbstractHttpConfigurer::disable);
        //返回Security过滤链对象
        return http.build();
    }

    @Bean //配置JdbcUserDetailsManager实现数据库存储用户
    public UserDetailsService userDetailsService(DataSource dataSource) {
        return new JdbcUserDetailsManager(dataSource);
    }
}

实现Spring Security授权功能

1.创建接口

@RestController
public class HelloController{

    @RequestMapping("/hello")
    public String hello() { 
        return "Hello Security"; 
    }

    @RequestMapping("/hello1")
    public String hello1() { 
        return "Hello Security1"; 
    }

}

2.配置数据库账号和权限(DbUser用户拥有hello和hello1权限、DbUser1只拥有hello1权限)

3.修改SecurityConfig配置

@Configuration
public class SecurityConfig {
    //配置Security过滤链
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        //配置哪些接口需要认证(.anyRequest().authenticated()代表任何请求都需认证)
        http.authorizeHttpRequests(authorize -> {
            authorize.requestMatchers("/hello").hasAuthority("hello");
            authorize.requestMatchers("/hello1").hasAuthority("hello1");
            authorize.anyRequest().authenticated();
        });
        //配置post表单请求/login接口
        http.formLogin(Customizer.withDefaults());
        //csrf攻击:开发环境可不配方便调试,上线环境需配置,否则会遭csrf攻击
        http.csrf(AbstractHttpConfigurer::disable);
        //返回Security过滤链对象
        return http.build();
    }

    @Bean //配置JdbcUserDetailsManager实现数据库存储用户
    public UserDetailsService userDetailsService(DataSource dataSource) {
        return new JdbcUserDetailsManager(dataSource);
    }
}

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文