Spring Security 基于 Spring 框架,提供了一套 Web 应用安全性的完整解决方案
关于安全方面的两个主要区域是“认证”和“授权”(或者访问控制),一般来说,Web 应用的安全性包括用户认证**(Authentication)和用户授权(Authorization)两个部分**,这两点也是 Spring Security 重要核心功能。
**用户认证:**验证某个用户是否为系统中的合法主体,也就是说用户能否访问该系统。用户认证一般要求用户提供用户名和密码。系统通过校验用户名和密码来完成认证过程。通俗点说就是系统认为用户是否能登录。
**用户授权:**验证某个用户是否有权限执行某个操作。在一个系统中,不同用户所具有的权限是不同的。比如对一个文件来说,有的用户只能进行读取,而有的用户可以进行修改。一般来说,系统会为不同的用户分配不同的角色,而每个角色则对应一系列的权限。通俗点讲就是系统判断用户是否有权限去做某些事情。
和 Spring 无缝整合
重量级、全面的权限控制
专门为 Web 开发而设计
旧版本不能脱离 Web 环境使用。
新版本对整个框架进行了分层抽取,分成了核心模块和 Web 模块。单独引入核心模块就可以脱离 Web 环境。
特点:
轻量级。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
以上只是一个推荐的组合而已,如果单纯从技术上来说,无论怎么组合,都是可以运行的。
<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>
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";
}
}
Using generated security password: 22f1f943-b70b-43e9-bf56-adf37851a9e7
刚刚我们的密码是在控制台,Spring Security 内置实现的密码登录,那实际工作中我们怎么自己指定用户名密码呢?
常见的方式有三种:
在 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");
}
}
自定义实现类配置:
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();
}
}
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);
}
}
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;
<?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
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;
}
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> {
}
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);
}
}
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);
}
}
通过重写 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防护
}
如果当前的主体具有指定的权限,则返回 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);
}
如果当前的主体有任何提供的角色(给定的作为一个逗号分隔的字符串列表)的话,返回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 取出角色相关信息 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);
}
用法和配置和 hasRole 一致,只不过在配置类中配置多个角色方可访问资源路径,同时给用户角色信息时,给一个或多个即可
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>自定义403页面</title>
</head>
<body>
自定义403页面!
</body>
</html>
http.exceptionHandling().accessDeniedPage("/unauth");
@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);
}
}
@GetMapping("testSecured")
@Secured({"ROLE_sale","ROLE_admin"})
public String testSecured(){
return "hello Secured";
}
List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("manager,ROLE_sale");
@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);
}
}
@RequestMapping("/preAuthorize")
@PreAuthorize("hasAuthority('menu:system')")
public String preAuthorize(){
return "Hello preAuthorize";
}
List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("manager,menu:system,menu:create");
用法和 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;
}
留下传入参数 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;
}
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
//注入数据源
@Autowired
private DataSource dataSource;
//注入数据源 配置操作数据库对象
@Bean
public PersistentTokenRepository persistentTokenRepository(){
JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
jdbcTokenRepository.setDataSource(dataSource);
//jdbcTokenRepository.setCreateTableOnStartup(true); //配置此配置则会自动帮我们建表
return jdbcTokenRepository;
}
//开启记住我功能
http.rememberMe().tokenRepository(persistentTokenRepository())
.tokenValiditySeconds(60*15) //有效时长 15分钟
.userDetailsService(userDetailsService);
<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();
}
}
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://www.cnblogs.com/doondo/p/14890245.html
内容来源于网络,如有侵权,请联系作者删除!