Spring Security 快速上手
Spring Security 框架简介
Spring Security 说明
- Spring Security 基于 Spring 框架,提供了一套 Web 应用安全性的完整解决方案
- 关于安全方面的两个主要区域是“认证”和“授权”(或者访问控制),一般来说,Web 应用的安全性包括用户认证(Authentication)和用户授权(Authorization)两个部分,这两点也是 Spring Security 重要核心功能。
- 用户认证:验证某个用户是否为系统中的合法主体,也就是说用户能否访问该系统。用户认证一般要求用户提供用户名和密码。系统通过校验用户名和密码来完成认证过程。通俗点说就是系统认为用户是否能登录。
- 用户授权:验证某个用户是否有权限执行某个操作。在一个系统中,不同用户所具有的权限是不同的。比如对一个文件来说,有的用户只能进行读取,而有的用户可以进行修改。一般来说,系统会为不同的用户分配不同的角色,而每个角色则对应一系列的权限。通俗点讲就是系统判断用户是否有权限去做某些事情。
- 关于安全方面的两个主要区域是“认证”和“授权”(或者访问控制),一般来说,Web 应用的安全性包括用户认证(Authentication)和用户授权(Authorization)两个部分,这两点也是 Spring Security 重要核心功能。
Spring Security 官网
Spring Security 特点
- 和 Spring 无缝整合
- 重量级、全面的权限控制
- 专门为 Web 开发而设计
- 旧版本不能脱离 Web 环境使用。
- 新版本对整个框架进行了分层抽取,分成了核心模块和 Web 模块。单独引入核心模块就可以脱离 Web 环境。
Spring Security 对比 Shiro
Shiro 简介
Shrio 是Apache 旗下的轻量级权限控制框架
特点:
- 轻量级。Shiro 主张的理念是把复杂的事情变简单。针对对性能有更高要求的互联网应用有更好表现。
- 通用性:
- 好处:不局限于 Web 环境,可以脱离 Web 环境使用。
- 缺陷:在 Web 环境下一些特定的需求需要手动编写代码定制。
总结
Spring Security 是 Spring 家族中的一个安全管理框架,实际上,在 Spring Boot 出现之前,Spring Security 就已经发展了多年了,但是使用的并不多,安全管理这个领域,一直是 Shiro 的天下。
相对于 Shiro,在 SSM 中整合 Spring Security 都是比较麻烦的操作,所以,SpringSecurity 虽然功能比 Shiro 强大,但是使用反而没有 Shiro 多(Shiro 虽然功能没有Spring Security 多,但是对于大部分项目而言,Shiro 也够用了)。
自从有了 Spring Boot 之后,Spring Boot 对于 Spring Security 提供了自动化配置方案,可以使用更少的配置来使用 Spring Security。
因此,一般来说,常见的安全管理技术栈的组合是这样的:
• SSM + Shiro
• Spring Boot/Spring Cloud + Spring Security
以上只是一个推荐的组合而已,如果单纯从技术上来说,无论怎么组合,都是可以运行的。
Spring Security 框架快速入门
搭建spring boot 项目,并引入项目依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
新建Controller,并配置访问方法
package org.taoguoguo.controller; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; /**
* @author taoGuoGuo
* @description HelloController
* @website https://www.cnblogs.com/doondo
* @create 2021-06-11 14:16
*/
@RestController
@RequestMapping("/test")
public class HelloController { @GetMapping("hello")
public String hello(){
return "hello security";
}
}
访问对应的方法,我们发现跳转至了默认的Spring Security 登录页面,用户名默认为 user , 密码为 控制台打印 password
Using generated security password: 22f1f943-b70b-43e9-bf56-adf37851a9e7
Spring Security 用户名密码配置
刚刚我们的密码是在控制台,Spring Security 内置实现的密码登录,那实际工作中我们怎么自己指定用户名密码呢?
常见的方式有三种:
- 通过配置文件指定
- 通过配置类指定
- 通过实现 UserDetailService 接口实现 数据库查询
通过配置文件指定
在 application.properties 中 进行配置
#第一种方式:通过配置文件配置Spring Security用户名密码
spring.security.user.name=taoguoguo
spring.security.user.password=taoguoguo
通过配置类实现 配置用户名密码
新建 SecurityConfig 并 实现 WebSecurityConfigurerAdapter 适配器实现配置重写
package org.taoguoguo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
/**
* @author taoGuoGuo
* @description SecurityConfig
* @website https://www.cnblogs.com/doondo
* @create 2021-06-11 14:55
*/
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
//如果缺少密码解析 登陆后会返回当前登陆页面 并报 id 为 null 的错误
@Bean
PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
//方式二:通过配置类设置登录用户名和密码,通过auth设置用户名密码
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
String password = passwordEncoder.encode("taoguoguo");
auth.inMemoryAuthentication().withUser("taoguoguo").password(password).roles("admin");
}
}
通过实现 UserDetailService 自定义实现
自定义实现类配置:
创建配置类,设置使用哪个userDetailService 实现类
package org.taoguoguo.config; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder; /**
* @author taoGuoGuo
* @description SecurityConfig
* @website https://www.cnblogs.com/doondo
* @create 2021-06-11 15:14
* SpringSecurity 自定义配置
*/
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired
private UserDetailsService userDetailsService; @Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//设置自定义的数据库实现及密码解析器
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
} @Bean
PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
}编写实现类,返回User对象,User对象有用户名密码和操作权限
package org.taoguoguo.service; import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service; import java.util.List; /**
* @author taoGuoGuo
* @description MyUserDetailService
* @website https://www.cnblogs.com/doondo
* @create 2021-06-11 15:18
*/
@Service("userDetailsService")
public class MyUserDetailService implements UserDetailsService { /**
* 自定义实现类方式查询用户名密码
* @param s
* @return
* @throws UsernameNotFoundException
*/
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
//密码
String password = passwordEncoder.encode("taoguoguo");
//权限
List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("role");
return new User("taoguoguo", password, auths);
}
}
数据库查询认证
数据库建立 users表
CREATE TABLE `users` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`username` varchar(20) COLLATE utf8mb4_general_ci NOT NULL,
`password` varchar(100) COLLATE utf8mb4_general_ci DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `username` (`username`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
项目添加依赖 采用 mybatis-plus
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>org.taoguoguo</groupId>
<artifactId>spring-security</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-security</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency> <dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.3</version>
</dependency> <dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency> <dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency> </dependencies> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build> </project>增加数据库参数配置
server.port=8111 #数据库配置
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/security_db?serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=root
创建Users实体
package org.taoguoguo.entity; import lombok.Data; /**
* @author taoGuoGuo
* @description Users
* @website https://www.cnblogs.com/doondo
* @create 2021-06-11 15:51
*/
@Data
public class Users {
private Integer id;
private String username;
private String password;
}创建UsersMapper
package org.taoguoguo.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.springframework.stereotype.Repository;
import org.taoguoguo.entity.Users; /**
* @author taoGuoGuo
* @description UsersMapper
* @website https://www.cnblogs.com/doondo
* @create 2021-06-11 15:53
*/
@Repository
public interface UsersMapper extends BaseMapper<Users> {
}修改自定义配置实现类 MyUserDetailService 进行数据库查询
package org.taoguoguo.service; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.taoguoguo.entity.Users;
import org.taoguoguo.mapper.UsersMapper;
import java.util.List; /**
* @author taoGuoGuo
* @description MyUserDetailService
* @website https://www.cnblogs.com/doondo
* @create 2021-06-11 15:18
*/
@Service("userDetailsService")
public class MyUserDetailService implements UserDetailsService { @Autowired
private UsersMapper usersMapper;
/**
* 自定义实现类方式查询用户名密码
* @param username
* @return
* @throws UsernameNotFoundException
*/
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//调用usersMapper方法,根据用户名查询数据库
QueryWrapper<Users> wrapper = new QueryWrapper<>();
wrapper.eq("username", username);
Users users = usersMapper.selectOne(wrapper);
if(users == null){ //数据库没有该用户名 认证失败
throw new UsernameNotFoundException("用户名或密码不存在!");
}
//权限
List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("role");
return new User(users.getUsername(), users.getPassword(), auths);
}
}在Spring Boot 配置启动类中进行Mapper注解扫描配置 注入Mapper Bean
package org.taoguoguo; import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication
@MapperScan("org.taoguoguo.mapper")
public class SpringSecurityApplication {
public static void main(String[] args) {
SpringApplication.run(SpringSecurityApplication.class, args);
} }
Spring Security自定义登录页面 及 认证放行
通过重写 webSecurityConfigureAdapter 的 configure(HttpSecurity http) 方法进行配置
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin() //自定义自己编写登录页面
.loginPage("/login.html") //登录页面设置
.loginProcessingUrl("/user/login") //登录访问路径
.defaultSuccessUrl("/test/index") //登录成功后,跳转路径
.permitAll()
.and().authorizeRequests() //定义请求路径访问规则
.antMatchers("/","/test/hello","/user/login").permitAll() //设置不需要认证可以直接访问的路径
.anyRequest().authenticated() //除此之外任何请求都需要认证
.and().csrf().disable(); //关闭csrf防护
}
基于角色或权限的进行访问控制
hasAuthority 方法,主要针对某一个权限进行控制访问
如果当前的主体具有指定的权限,则返回 true,否则返回 false
修改配置类,增加
.antMatchers("/test/index").hasAuthority("admin")具备admin权限 才能访问/test/index路径@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin() //自定义自己编写登录页面
.loginPage("/login.html") //登录页面设置
.loginProcessingUrl("/user/login") //登录访问路径
.defaultSuccessUrl("/test/index") //登录成功后,跳转路径
.permitAll()
.and().authorizeRequests() //定义请求路径访问规则
.antMatchers("/","/test/hello","/user/login").permitAll() //设置不需要认证可以直接访问的路径
.antMatchers("/test/index").hasAuthority("admin") //具备admin权限才能访问 /test/index资源
.anyRequest().authenticated() //除此之外任何请求都需要认证
.and().csrf().disable(); //关闭csrf防护
}
那这个admin的权限是在哪里指定的呢?其实在之前我们已经提到过,在自定义的登录逻辑中,我们会放置用户所具备的权限信息
List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("admin");@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//调用usersMapper方法,根据用户名查询数据库
QueryWrapper<Users> wrapper = new QueryWrapper<>();
wrapper.eq("username", username);
Users users = usersMapper.selectOne(wrapper);
if(users == null){ //数据库没有该用户名 认证失败
throw new UsernameNotFoundException("用户名或密码不存在!");
}
//权限
List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("admin");
return new User(users.getUsername(), users.getPassword(), auths);
}
hasAnyAuthority 方法
如果当前的主体有任何提供的角色(给定的作为一个逗号分隔的字符串列表)的话,返回true
修改配置类,增加
.antMatchers("/test/index").hasAnyAuthority("admin,manager")具备admin 或 manager其中任一权限 就能访问/test/index路径@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin() //自定义自己编写登录页面
.loginPage("/login.html") //登录页面设置
.loginProcessingUrl("/user/login") //登录访问路径
.defaultSuccessUrl("/test/index") //登录成功后,跳转路径
.permitAll()
.and().authorizeRequests() //定义请求路径访问规则
.antMatchers("/","/test/hello","/user/login").permitAll() //设置不需要认证可以直接访问的路径
.antMatchers("/test/index").hasAnyAuthority("admin,manager")
.anyRequest().authenticated() //除此之外任何请求都需要认证
.and().csrf().disable(); //关闭csrf防护
}
hasRole 如果用户具备给定角色就允许访问,否则出现 403 如果当前主体具有指定的角色,则返回 true。
查看源码用法
// hasRole 取出角色相关信息 access 判断是否能够访问
public ExpressionInterceptUrlRegistry hasRole(String role) {
return access(ExpressionUrlAuthorizationConfigurer.hasRole(role));
} // 为role 底层拼接 ROLE_ 所以 我们在自定义登录逻辑 赋予权限时 要拼接 ROLE_
private static String hasRole(String role) {
Assert.notNull(role, "role cannot be null");
Assert.isTrue(!role.startsWith("ROLE_"),
() -> "role should not start with 'ROLE_' since it is automatically inserted. Got '" + role + "'");
return "hasRole('ROLE_" + role + "')";
}修改配置类,配置用户具备
deptManager才能访问/test/index资源@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin() //自定义自己编写登录页面
.loginPage("/login.html") //登录页面设置
.loginProcessingUrl("/user/login") //登录访问路径
.defaultSuccessUrl("/test/index") //登录成功后,跳转路径
.permitAll()
.and().authorizeRequests() //定义请求路径访问规则
.antMatchers("/","/test/hello","/user/login").permitAll() //设置不需要认证可以直接访问的路径
.antMatchers("/test/index").hasRole("deptManager")
.anyRequest().authenticated() //除此之外任何请求都需要认证
.and().csrf().disable(); //关闭csrf防护
}
给用户配置
deptManager角色权限@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//调用usersMapper方法,根据用户名查询数据库
QueryWrapper<Users> wrapper = new QueryWrapper<>();
wrapper.eq("username", username);
Users users = usersMapper.selectOne(wrapper);
if(users == null){ //数据库没有该用户名 认证失败
throw new UsernameNotFoundException("用户名或密码不存在!");
}
//权限
List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("manager,ROLE_deptManager");
return new User(users.getUsername(), users.getPassword(), auths);
}
hasAnyRole 表示用户具备任何一个条件都可以访问
用法和配置和 hasRole 一致,只不过在配置类中配置多个角色方可访问资源路径,同时给用户角色信息时,给一个或多个即可
Spring Security 自定义403 无权限访问页面
我们在项目的静态资源文件夹 static 下 新建 unauth.html 自定义的403页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>自定义403页面</title>
</head>
<body>
自定义403页面!
</body>
</html>
修改访问配置类
http.exceptionHandling().accessDeniedPage("/unauth");
Spring Security 注解使用
@Secured 判断是否具有角色
开启Spring Security注解功能
@EnableGlobalMethodSecurity(securedEnabled = true)package org.taoguoguo; import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; @SpringBootApplication
@MapperScan("org.taoguoguo.mapper")
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SpringSecurityApplication {
public static void main(String[] args) {
SpringApplication.run(SpringSecurityApplication.class, args);
} }编写需要 Secured 注解指定角色访问的控制器
@GetMapping("testSecured")
@Secured({"ROLE_sale","ROLE_admin"})
public String testSecured(){
return "hello Secured";
}
在自定义登录逻辑中,为用户分配对应的角色信息
List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("manager,ROLE_sale");
@PreAuthorize 进入方法前的权限验证
开启注解功能
@EnableGlobalMethodSecurity(prePostEnabled = true)package org.taoguoguo; import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; @SpringBootApplication
@MapperScan("org.taoguoguo.mapper")
@EnableGlobalMethodSecurity(securedEnabled = true,prePostEnabled = true)
public class SpringSecurityApplication {
public static void main(String[] args) {
SpringApplication.run(SpringSecurityApplication.class, args);
} }编写需要 preAuthorize 需要权限验证的控制器
@RequestMapping("/preAuthorize")
@PreAuthorize("hasAuthority('menu:system')")
public String preAuthorize(){
return "Hello preAuthorize";
}
在自定义登录逻辑中,为用户分配对应的角色信息
List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("manager,menu:system,menu:create");
@PostAuthorize 在方法执行后再进行权限验证,适合验证带有返回值的权限
用法和 preAuthorize 基本一致,比较简单,这边就不详细说明了。重点明白什么场景下使用即可
@PostFilter 权限验证之后对数据进行过滤
留下用户名是 admin1 的数据 表达式中的 filterObject 引用的是方法返回值 List 中的某一个元素
@RequestMapping("getAll")
@PreAuthorize("hasRole('ROLE_ 管理员')")
@PostFilter("filterObject.username == 'admin1'")
@ResponseBody
public List<UserInfo> getAllUser(){
ArrayList<UserInfo> list = new ArrayList<>();
list.add(new UserInfo(1l,"admin1","6666"));
list.add(new UserInfo(2l,"admin2","888"));
return list;
}
@PreFilter 进入控制器之前对数据进行过滤
留下传入参数 id 能对 2 整除的参数数据
@RequestMapping("getTestPreFilter")
@PreAuthorize("hasRole('ROLE_ 管理员')")
@PreFilter(value = "filterObject.id%2==0")
@ResponseBody
public List<UserInfo> getTestPreFilter(@RequestBody List<UserInfo> list){
list.forEach(t-> {
System.out.println(t.getId()+"\t"+t.getUsername());
});
return list;
}
Spring Security 实现 RememberMe
用户流程及框架实现原理

具体实现方式
创建表,这个表也可以由程序自动创建
CREATE TABLE `persistent_logins` (
`username` varchar(64) NOT NULL,
`series` varchar(64) NOT NULL,
`token` varchar(64) NOT NULL,
`last_used` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`series`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
添加数据库配置文件
#数据库配置
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/security_db?serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=root
修改配置类 SecurityConfig 中 注入数据源及配置数据库操作对象
//注入数据源
@Autowired
private DataSource dataSource; //注入数据源 配置操作数据库对象
@Bean
public PersistentTokenRepository persistentTokenRepository(){
JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
jdbcTokenRepository.setDataSource(dataSource);
//jdbcTokenRepository.setCreateTableOnStartup(true); //配置此配置则会自动帮我们建表
return jdbcTokenRepository;
}
开启 Remeber me 功能
//开启记住我功能
http.rememberMe().tokenRepository(persistentTokenRepository())
.tokenValiditySeconds(60*15) //有效时长 15分钟
.userDetailsService(userDetailsService);
login.html 页面增加记住我 功能标签 【注意:name 属性值必须位 remember-me.不能改为其他值】
<form action="/user/login" method="post">
用户名:<input type="text" name="username"><br/>
密 码:<input type="password" name="password"><br/>
<input type="checkbox" name="remember-me" title="记住密码">自动登录<br/>
<input type="submit" value="login">
</form>
最后附上完整的配置类代码
package org.taoguoguo.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;
import javax.sql.DataSource;
/**
* @author taoGuoGuo
* @description SecurityConfig
* @website https://www.cnblogs.com/doondo
* @create 2021-06-11 15:14
* SpringSecurity 自定义配置
*/
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
//注入数据源
@Autowired
private DataSource dataSource;
//注入数据源 配置操作数据库对象
@Bean
public PersistentTokenRepository persistentTokenRepository(){
JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
jdbcTokenRepository.setDataSource(dataSource);
//jdbcTokenRepository.setCreateTableOnStartup(true); //配置此配置则会自动帮我们建表
return jdbcTokenRepository;
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//设置自定义的数据库实现及密码解析器
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
//表单认证
http.formLogin() //自定义自己编写登录页面
.loginPage("/login.html") //登录页面设置
.loginProcessingUrl("/user/login") //登录访问路径
.defaultSuccessUrl("/sys/loginSuccess") //登录成功后,跳转路径
.permitAll()
.and().authorizeRequests() //定义请求路径访问规则
.antMatchers("/","/test/hello","/user/login").permitAll() //设置不需要认证可以直接访问的路径
//1 hasAuthority方法 具备admin权限才能访问 /test/index资源
// .antMatchers("/test/index").hasAuthority("admin")
//2 hasAnyAuthority方法 具备admin,manager其中任一权限 才能访问/test/index资源
// .antMatchers("/test/index").hasAnyAuthority("admin,manager")
.antMatchers("/test/index").hasRole("manager")
.anyRequest().authenticated(); //除此之外任何请求都需要认证
//开启记住我功能
http.rememberMe().tokenRepository(persistentTokenRepository())
.tokenValiditySeconds(60*15) //有效时长 15分钟
.userDetailsService(userDetailsService);
//关闭csrf防护
http.csrf().disable();
//用户注销配置
http.logout().logoutUrl("/logout").logoutSuccessUrl("/sys/logout").permitAll();
//自定义403页面
http.exceptionHandling().accessDeniedPage("/sys/unauth403");
}
@Bean
PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
}
Spring Security 快速上手的更多相关文章
- Spring Security 快速了解
在Spring Security之前 我曾经使用 Interceptor 实现了一个简单网站Demo的登录拦截和Session处理工作,虽然能够实现相应的功能,但是无疑Spring Security提 ...
- Spring WebFlux快速上手——响应式Spring的道法术器
https://blog.csdn.net/get_set/article/details/79480233
- Spring Security LDAP简介
1.概述 在本快速教程中,我们将学习如何设置Spring Security LDAP. 在我们开始之前,了解一下LDAP是什么? - 它代表轻量级目录访问协议.它是一种开放的,与供应商无关的协议,用于 ...
- SpringBoot安全篇Ⅵ --- 整合Spring Security
知识储备: 关于SpringSecurity的详细学习可以查看SpringSecurity的官方文档. Spring Security概览 应用程序的两个主要区域是"认证"和&qu ...
- springboot集成spring security安全框架入门篇
一. :spring security的简介 Spring Security是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架.它提供了一组可以在Spring应用上下 ...
- 想要快速上手 Spring Boot?看这些教程就足够了!
1.项目名称:分布式敏捷开发系统架构 项目简介:基于 Spring + SpringMVC + Mybatis 分布式敏捷开发系统架构,提供整套公共微服务服务模块:集中权限管理(单点登录).内容管理. ...
- 想要快速上手 Spring Boot?看这些教程就足够了!| 码云周刊第 81 期
原文:https://blog.gitee.com/2018/08/19/weekly-81/ 想要快速上手 Spring Boot?看这些教程就足够了!| 码云周刊第 81 期 码云周刊 | 201 ...
- Spring Boot 揭秘与实战(一) 快速上手
文章目录 1. 简介 1.1. 什么是Spring Boot 1.2. 为什么选择Spring Boot 2. 相关知识 2.1. Spring Boot的spring-boot-starter 2. ...
- Spring Cloud Gateway 服务网关快速上手
Spring Cloud Gateway 服务网关 API 主流网关有NGINX.ZUUL.Spring Cloud Gateway.Linkerd等:Spring Cloud Gateway构建于 ...
随机推荐
- 1.关于逆向工程(RE、RCE)-笔记
名词 逆向工程(Reverse Engineering,简称RE):代码逆向工程(Reverse Code Engineering,简称RCE). 逆向分析方法 静态分析:不执行代码,观察外部特征.获 ...
- android之Tween Animation
android Tween Animation有四种,AlphaAnimation(透明度动画).ScaleAnimation(尺寸伸缩动画).TranslateAnimation(位移动画).Rot ...
- Docker安装教程(超详细)
Docker安装教程(超详细) 欢迎关注博主公众号「Java大师」, 专注于分享Java领域干货文章, 关注回复「资源」, 免费领取全网最热的Java架构师学习PDF, 转载请注明出处 http:// ...
- 还不懂 redis 持久化?看看这个
Redis 是一个内存数据库,为了保证数据不丢失,必须把数据保存到磁盘,这就叫做持久化. Redis 有两种持久化方法: RDB 方式以及 AOF 方式 RDB 持久化 前言 RDB持久化把内存中的数 ...
- JVM虚拟机-垃圾回收机制与垃圾收集器概述
目录 前言 什么是垃圾回收 垃圾回收的区域 垃圾回收机制 流程 怎么判断对象已经死亡 引用计数法 可达性分析算法 不可达的对象并非一定会回收 关于引用 强引用(StrongReference) 软引用 ...
- NABCD-name not found
项目 内容 课程 2020春季计算机学院软件工程(罗杰 任健) 作业要求 团队项目选择 项目名称 FOTT 项目内容 在OCR-Form-Tools开源项目的基础上,扩展功能,支持演示更多的API,例 ...
- 浅谈CRM系统的选型和实施
CRM的本质是最大化利用企业的现有资源来提供客户所需的产品,保证提供给客户最好的服务,帮助销售人员提高客户转化率,储存所有重要的客户信息,帮助企业深入挖掘潜在客户等等. 对于企业来说,即使处于同一行业 ...
- [Java] GUI编程基础 绘图
库 swing awt 过程 创建窗口JFrame JFrame-->MenuBar-->Container 屏幕坐标系:左上角为原点 Graphics2D Main.java 1 imp ...
- SSH连接自动断开的解决方法(deb/rpm)
######### 修改后的: ## # tail -f -n 20 sshd_config#MaxStartups 10:30:60#Banner /etc/issue.net # Allow cl ...
- MegaCli是一款管理维护硬件RAID软件,可以通过它来了解当前raid卡的所有信息,包括 raid卡的型号,raid的阵列类型,raid 上各磁盘状态
MegaCli 监控raid状态 转载weixin_30344131 最后发布于2015-10-16 13:05:00 阅读数 简介 MegaCli是一款管理维护硬件RAID软件,可以通过它来了 ...