使用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: postgres4.修改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);
}
}总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论