一、SpringSecurity介绍
- Spring Security是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架。它提供了一组可以在Spring应用上下文中配置的Bean,充分利用了Spring IoC,DI(控制反转Inversion of Control ,DI:Dependency Injection 依赖注入)和AOP(面向切面编程)功能,为应用系统提供声明式的安全访问控制功能,减少了为企业系统安全控制编写大量重复代码的工作
二、Basic认证模式
Basic认证是一种较为简单的HTTP认证方式,客户端通过明文(Base64编码格式)传输用户名和密码到服务端进行认证,通常需要配合HTTPS来保证信息传输的安全(登录是保存在session中)
- 1.新建项目spring-security
- 2.maven依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.1.RELEASE</version>
</parent>
<dependencies>
<!-- springboot 整合web组件-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--spring-boot-starter-security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
</dependencies>
- 3.application.yml
server:
port: 8080
spring:
freemarker:
settings:
classic_compatible: true #处理空值
datetime_format: yyy-MM-dd HH:mm
number_format: 0.##
suffix: .ftl
template-loader-path:
- classpath:/templates
- 4.login.ftl
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>sjyl--权限控制登陆系统</h1>
<form action="/login" method="post">
<span>用户名称</span><input type="text" name="username"/> <br>
<span>用户密码</span><input type="password" name="password"/> <br>
<input type="submit" value="登陆">
</form>
<#if RequestParameters['error']??>
用户名称或者密码错误
</#if>
</body>
</html>
- 5.MemberService
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MemberService {
@RequestMapping("/addMember")
public String addMember() {
return "addMember";
}
@RequestMapping("/delMember")
public String delMember() {
return "delMember";
}
@RequestMapping("/updateMember")
public String updateMember() {
return "updateMember";
}
@RequestMapping("/showMember")
public String showMember() {
return "showMember";
}
}
- 7.SecurityConfig
import org.springframework.context.annotation.Bean;
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.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.stereotype.Component;
@Component
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
/*
* 账户规则
* 新增授权的账户
* */
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("sjyl").password("123").authorities("/");
}
/*
* 拦截规则
* 配置认证方式Token、传统表单
* */
@Override
protected void configure(HttpSecurity http) throws Exception {
//拦截所有请求:配置认证方式 token form表单 设置为httpBasic模式
http.authorizeRequests().antMatchers("/**").fullyAuthenticated().and().httpBasic();
}
/**
* There is no PasswordEncoder mapped for the id "null"
* 原因:升级为Security5.0以上密码支持多中加密方式,恢复以前模式
*/
@Bean
public static NoOpPasswordEncoder passwordEncoder() {
return (NoOpPasswordEncoder) NoOpPasswordEncoder.getInstance();
}
}
- 8.测试
- 地址:http://127.0.0.1:8080/showMember
- 输入config配置的用户名密码后就可以正常访问
三、form表单形式
From 表单模式 适合于传统模式项目 前端和后端都是我们java开发人员自己实现
而目前最新的我们基本是使用Vue+SpringBoot,前后端分离的方式实现的
- 1.config修改
- 只需要修改拦截规则,其他不需要修改
/*
* 拦截规则
* 配置认证方式Token、传统表单
* */
@Override
protected void configure(HttpSecurity http) throws Exception {
//拦截 http 安全认证模式 设置为formLogin模式
http.authorizeRequests().antMatchers("/**").fullyAuthenticated().and().formLogin();
}
- 2.测试
- 访问地址:http://127.0.0.1:8080/login
四、配置权限策略
- 在企业管理系统平台中,会拆分成n多个不同的账号,每个账号对应不同的接口访问权限,比如:
- 账号sjyl_admin 所有接口都可以访问;
- 账号sjyl_add账户 只能访问/addMember接口;
- 账号sjyl_show账户 只能访问/showMember接口;
- 账号sjyl_del账户 只能访问/delMember接口;
- 两步配置权限策略
- a)configure(HttpSecurity http):配置接口对应需要的权限名
- b)configure(AuthenticationManagerBuilder auth) :配置用户名所拥有的权限名
import org.springframework.context.annotation.Bean;
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.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.stereotype.Component;
@Component
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
/*
* 账户规则
* 新增授权的账户
* */
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("sjyl_admin").password("sjyl_admin").authorities("addMember", "delMember", "updateMember", "showMember");
/*
* 当前 账户授权 可以访问哪些接口
*/
auth.inMemoryAuthentication().withUser("sjyl_add").password("sjyl_add").authorities("addMember");
auth.inMemoryAuthentication().withUser("sjyl_update").password("sjyl_update").authorities("updateMember");
auth.inMemoryAuthentication().withUser("sjyl_del").password("sjyl_del").authorities("delMember");
auth.inMemoryAuthentication().withUser("sjyl_show").password("sjyl_show").authorities("showMember");
}
/*
* 拦截规则
* 配置认证方式Token、传统表单
* */
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/addMember").hasAnyAuthority("addMember")
.antMatchers("/delMember").hasAnyAuthority("delMember")
.antMatchers("/updateMember").hasAnyAuthority("updateMember")
.antMatchers("/showMember").hasAnyAuthority("showMember")
.antMatchers("/**").fullyAuthenticated().and().formLogin();
}
/**
* There is no PasswordEncoder mapped for the id "null"
* 原因:升级为Security5.0以上密码支持多中加密方式,恢复以前模式
*/
@Bean
public static NoOpPasswordEncoder passwordEncoder() {
return (NoOpPasswordEncoder) NoOpPasswordEncoder.getInstance();
}
}
五、修改403权限不足的页面
- 1.新增WebServerAutoConfiguration
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
/**
* 自定义SpringBoot 错误异常
*/
@Configuration
public class WebServerAutoConfiguration {
@Bean
public ConfigurableServletWebServerFactory webServerFactory() {
TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();
ErrorPage errorPage400 = new ErrorPage(HttpStatus.BAD_REQUEST, "/error/400");
ErrorPage errorPage401 = new ErrorPage(HttpStatus.UNAUTHORIZED, "/error/401");
ErrorPage errorPage403 = new ErrorPage(HttpStatus.FORBIDDEN, "/error/403");
ErrorPage errorPage404 = new ErrorPage(HttpStatus.NOT_FOUND, "/error/404");
ErrorPage errorPage415 = new ErrorPage(HttpStatus.UNSUPPORTED_MEDIA_TYPE, "/error/415");
ErrorPage errorPage500 = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/error/500");
factory.addErrorPages(errorPage400, errorPage401, errorPage403, errorPage404, errorPage415, errorPage500);
return factory;
}
}
- 2.新增ErrorController
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* 统一返回错误异常类
*/
@RestController
public class ErrorController {
@RequestMapping("/error/403")
public String error() {
return "您当前访问的接口权限不足!";
}
}
- 3.测试
六、自定义登录页面
注意:name="username"和name="password"这两个是不可以改变的
- 1.自定义LoginController
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* 自定义 LoginController
*/
@Controller
public class LoginController {
@RequestMapping("/login")
public String login() {
return "login";
}
}
- 2.修改SecurityConfig
- 仅修改
configure(HttpSecurity http)
方法即可
- 仅修改
/*
* 拦截规则
* 配置认证方式Token、传统表单
* */
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/addMember").hasAnyAuthority("addMember")
.antMatchers("/delMember").hasAnyAuthority("delMember")
.antMatchers("/updateMember").hasAnyAuthority("updateMember")
.antMatchers("/showMember").hasAnyAuthority("showMember")
.antMatchers("/login").permitAll()//可以允许login不被拦截
.antMatchers("/**").fullyAuthenticated().and().formLogin()
.loginPage("/login").and().csrf().disable();//设置自定义登录界面
}
- 3.测试