1.Spring Security的认识
1.Spring Security是什么?
Spring Security是和spring框架结合起来管理项目安全的框架。
处理流程:
2.Spring Security的核心功能
1.Authentication:身份的验证,用户登陆的验证;
2.Authorization:访问授权,授权资源的访问权限;
3.安全防护、防止跨站请求、session攻击;
4.Spring Security对OAuth的支持更友好;
5.Spring Security在网络安全方面下了更多的功夫
3.Spring Security整体的认识
Spring Security框架主要是来执行一系列的Filter来完成各种需求
一共是11个过滤器来完成框架的功能的,过滤器如下
HttpSessionContextIntegrationFilter
功能:
LogoutFilter
功能:退出登录
AuthenticationProcessingFilter
功能
DefaultLoginPageGeneratingFilter
功能
BasicProcessingFilter
功能:
SecurityContextHolderAwareRequestFilter
功能:
RememberMeProcessingFilter
功能:记住我
AnonymousProcessingFilter
功能:
ExceptionTranslationFilter
功能:负责检测抛出的所有Spring Security异常,此类异常主要由AbstractSecurityInterceptor授权服务
的主要提供者抛出异常
SessionFixationProtectionFilter
功能:
FilterSecurityInterceptor
功能:
4.Spring Security添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
5.实现
5.1创建一个HelloController
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello(){
return "hello world";
}
}
5.2启动项目
你会在控制台拿到一个密码
在浏览器输入 http://localhost:8080/hello
同时系统也给我们预置了一个用户,用户名是user,密码显示在启动控制台中。
登录后的页面
5.3自定义前后端分离
注意看这段代码的缩进距离,http是根对象,其下有4个配置项:authorizeRequests、formLogin、logout、csrf,缩进距离是一样的。每个配置项使用and方法分隔连接,and前面是当前配置项的下级参数配置,缩进更多。
创建一个SecurityConfig类继承WebSecurityConfigurerAdapter
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
/**
*
* 这是一个访问配置适配器
*/
@SpringBootConfiguration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()//配置权限
.anyRequest().authenticated()//任意请求需要登录
.and()
.formLogin()//开启formLogin默认配置
.loginPage("/login/auth").permitAll()//请求时未登录跳转接口
.failureUrl("/login/fail")//用户密码错误跳转接口
.defaultSuccessUrl("/login/success", true)//登录成功跳转接口
.loginProcessingUrl("/login")//post登录接口,登录验证由系统实现
.usernameParameter("username") //要认证的用户参数名,默认username
.passwordParameter("password") //要认证的密码参数名,默认password
.and()
.logout()//配置注销
.logoutUrl("/logout")//注销接口
.logoutSuccessUrl("/login/logout").permitAll()//注销成功跳转接口
.deleteCookies("myCookie") //删除自定义的cookie
.and()
.csrf().disable(); //禁用csrf
}
}
自定义接口实现
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class LoginController {
@GetMapping("/login/{status}")
public String login(@PathVariable String status) {
System.out.println(status);
if ("auth".equals(status)) {
return "没有登录";
}
if ("fail".equals(status)) {
return "登录失败";
}
if ("success".equals(status)) {
return "登录成功";
}
if ("logout".equals(status)) {
return "注销成功";
}
return "";
}
}
写一个前端页面
login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登录页</title>
</head>
<body>
<p>
<label>Username</label> <input id="username">
</p>
<p>
<label>Password</label> <input id="password">
</p>
<button onclick="login()">Sign in</button>
<script src="/jquery.min.js"></script>
<script>
function login(){
$.ajax({
url : "/login" ,
type : 'post',
data : {
username: $("#username").val(),
password: $("#password").val(),
},
success : function(data) {
alert(data);
}
});
}
</script>
</body>
</html>
配置角色和权限
http
.authorizeRequests()//配置权限
.antMatchers("/anonymous1").hasAnyRole("ANONYMOUS")//角色ANONYMOUS
.antMatchers("/anonymous2").hasAnyAuthority("ROLE_ANONYMOUS")//权限ROLE_ANONYMOUS
.antMatchers("/anonymous3").anonymous()//匿名用户
.anyRequest().authenticated()//任意请求需要登录
.and()
匿名用户
spring security中有匿名用户的概念,即你没有登录,仍然会给你分配匿名权限:ROLE_ANONYMOUS。而带ROLE_前缀的权限 ROLE_xxx 等同于角色 xxx ,所以上面三个/anonymous的访问权限是一模一样的,不需要登录可匿名访问。相反,登录以后就不再拥有匿名权限,将无法再访问这三个url。但是其他url必须登录以后才能访问。
常用的权限配置方法
- hasAnyRole:用户拥有方法参数中任意一个角色,如上代码中就是。
- hasAnyAuthority:用户拥有方法参数中任意一个权限。
- authenticated:登录用户。
- anonymous:匿名用户。
- permitAll:任何人都能请求。
- denyAll:任何人不能请求。
- rememberMe:使用记住我方式登录的用户可以请求,以后会讲。
- fullyAuthenticated:使用记住我方式登录的用户不可请求。
- hasIpAddress:指定ip地址的用户。
- not:求反,可用于其他方法的前缀。如.not().hasAnyRole(“ANONYMOUS”)指没有ANONYMOUS角色的用户。
- access:使用SpEL表达式,如下
SpEL表达式
以上方法一次只能配置一种,如果一个url要同时匹配多种方法,可使用SpEL表达式,如下,用户同时具备role角色和auth权限。
.antMatchers("/any").access("hasAnyRole('role') and hasAnyAuthority('auth')")
- and和or:逻辑与和逻辑或。
- hasAnyRole(xxx):拥有xxx中的一个角色。
- hasAnyAuthority(xxx):拥有xxx中的一个权限。
- isAuthenticated():登录用户。
- isAnonymous():匿名用户。
- permitAll:任意用户。
- denyAll:拒绝请求。
- isRememberMe():记住我登录。
- isFullyAuthenticated():非记住我登录。
- hasIpAddress(xxx):限制ip。
- !:求反。
含对象的表达示,如下:只有用户名user可以请求。authentication对象是非常重要的核心对象,以后详解
.antMatchers("/any").access("authentication.name=='user'")
静态资源
spring security默认会拦截任何请求,以下方法可以排除静态资源。
public void configure(WebSecurity web)throws Exception {
web.ignoring().antMatchers("/**.html","/**.js");
}
2.OAuth2的认识
2.1OAuth2是什么
OAuth简单说就是一种授权的协议,只要授权方和被授权方遵守这个协议去写代码提供服务,那双方就是实现了OAuth模式。
简单来说就是实现第三方登录
登录流程图
2.2需要添加的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
<version>2.3.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
2.3需要编写的代码
配置security
package cn.com.ly.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.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
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.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
/**
* 配置Security
* web适配器配置
*/
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
super.configure(auth);
// auth.inMemoryAuthentication().withUser("zhangsan").password("$2a$10$qsJ/Oy1RmUxFA.YtDT8RJ.Y2kU3U4z0jvd35YmiMOAPpD.nZUIRMC").roles("USER");
}
@Override
public void configure(WebSecurity web) throws Exception {
super.configure(web);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
}
@Bean
@Override
protected UserDetailsService userDetailsService() {
User.UserBuilder builder = User.builder();
UserDetails user = builder.username("zhangsan").password("$2a$10$GStfEJEyoSHiSxnoP3SbD.R8XRowP1QKOdi.N6/iFEwEJWTQqlSba").roles("USER").build();
UserDetails admin = builder.username("lisi").password("$2a$10$GStfEJEyoSHiSxnoP3SbD.R8XRowP1QKOdi.N6/iFEwEJWTQqlSba").roles("USER", "ADMIN").build();
return new InMemoryUserDetailsManager(user, admin);
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
public static void main(String[] args) {
BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
System.out.println(bCryptPasswordEncoder.encode("123456"));
System.out.println(bCryptPasswordEncoder.encode("12345678"));
}
}
配置授权服务器
package cn.com.ly.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
/**
* 配置授权服务器
*
*/
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
super.configure(security);
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("my-client-1")
.secret("$2a$10$0jyHr4rGRdQw.X9mrLkVROdQI8.qnWJ1Sl8ly.yzK0bp06aaAkL9W")
.authorizedGrantTypes("authorization_code", "refresh_token")
.scopes("all")
.redirectUris("http://www.baidu.com");
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
super.configure(endpoints);
}
public static void main(String[] args) {
System.out.println(new org.apache.tomcat.util.codec.binary.Base64().encodeAsString("my-client-1:12345678".getBytes()));
System.out.println(java.util.Base64.getEncoder().encodeToString("my-client-1:12345678".getBytes()));
}
}
3.JWT
3.1什么是JWT
JWT是为了在网络应用环境间传递声明而执行的一种基于JSON开放标椎((RFC 7519).该token被设计为紧凑且安全的,特别适用于分布式站点的单点登录(SSO)场景。JWT的声明一般被用来在身份提供者和服务提供者间传递被认证的用户身份信息,以便于从资源服务器获取资源,也可以增加一些额外的其他业务逻辑必须的声明信息,该token也可以直接被用于认证,也可以被加密。
3.2 JWT长什么样?
JWT一般是由三段信息构成的,将这三段信息文本用.连接一起就构成了JWT字符串,就像这样:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ
3.3 JWT的构成
第一部分我们称它为头部(header),第二部分我们称其为载荷(payLoad,类似于飞机上承载的货物),第三部分是签证(Signature)
Header
jwt的头部承载两部分信息:
1.声明类型,这里是jwt
2.声明加密的算法,通常直接使用HMAC SHA256
完整的头部就像下面的JSON:
{
'typ': 'JWT',
'alg': 'HS256'
}
然后将头部进行base64加密(该加密是可以对称解密的),构成了第一部分。
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9
payLoad
载荷就是存放有效信息的地方,这个名字像是特指飞机上承载的货物,这些有效信息包含三个部分
1.标椎中注册的声明
2.公共的声明
3.私有的声明
标椎中注册的声明(建议但不强制使用)
1.iss:jwt签发者
2.sub:jwt所有向的用户
3.aud:接收jwt的一方
4.exp:jwt的过期时间,这个过期时间必须要大于签发时间
5.nbf:定义在什么时间之前,改jwt都是不可用的
6.iat:jwt签发时间
7.jti:jwt的唯一身份标识,主要用来作为一次性token,从而回避重放攻击
公共的声明公共的声明可以添加任何的信息,一般添加用户的相关信息或其他业务需求的必要信息,但不建议添加敏感信息,因为改部分在客户端可解密
**私有的声音:**私有的声明是提供者和消费者所共同定义的声明,一般不建议存放敏感信息,因为base64是对称加密的,意味着该部分信息可以归类为明文信息。
定义一个payload:
{
"sub": "1234567890",
"name": "John Doe",
"admin": true
}
然后将其进行base64加密,得到jwt的第二部分
eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9
signature
JWT的第三部分是一个签证信息,这个签证信息由三部分组成
1.header(base64后的)
2.payload(base64后的)
3.secret
这个部分需要base64加密后的header和base64后的payload使用.连接组成字符串,然后通过header中声明的加密方式进行加盐secret组合加密,然后就构成了jwt的第三部分。
// javascript
var encodedString = base64UrlEncode(header) + '.' + base64UrlEncode(payload);
var signature = HMACSHA256(encodedString, 'secret'); // TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ
将这三部分用.连接成一个完整的字符串,构成了最终的jwt:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ
注意:secret是保护在服务端的,jwt的签发生成也是在服务端的,secret就是用来进行jwt的签发和jwt的验证,所以,他就是你服务端私钥,在任何场景都不应该流露出去。一旦客户端得知这个secret,那就意味着客户端可以自我签发jwt了。
3.4 JWT如何应用
一般是在请求头里加入Authorization,并嘉加上Bearer标注:
fetch('api/user/1', {
headers: {
'Authorization': 'Bearer ' + token
}
})
服务端会验证token,如果验证通过就会返回响应的资源,整个流程就是这个样子的:
总结:
优点
1.因为JSON的通用性,所以JWT是可以进行跨语言支持的,JAVA,JavaScript,NodeJS,PHP等很多语言都可以使用
2.因为有了payload部分,所以JWT可以在自身存储一些其他业务逻辑所必要的非敏感信息
3.便于传输,jwt构成非常简单,字节占用很小,所以它是非常便于传输的。
4.它不需要在服务端保存会话信息,所以它易于应用的扩展。
安全相关:
1.不应该在jwt的payload部分存放敏感信息,因为该部分是客户端可解密的部分
2.保护好secret私钥,该私钥非常重要。
3.如果可以,请使用HTTPS协议。
3.4 JWT实现
添加依赖
<!-- JWT依赖 -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.7.0</version>
</dependency>
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.4.0</version>
</dependency>
server:
port: 8080
spring:
application:
name: springboot-jwt
config:
jwt:
# 加密密钥
secret: abcdefg1234567
# token有效时长
expire: 3600
# header 名称
header: token