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

一.使用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);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值