Security
RBAC模型: Role-Based Access Control 基于角色的权限控制访问控制,角色关联权限,角色又关联用户的授权方式
一个用户可以有多个角色,每一个角色又可以分配多个权限
AuthenticationProvider是AuthenticationManager的一个组成部分,它负责处理特定类型的Authentication对象。AuthenticationManager可能会有多个AuthenticationProvider,每个AuthenticationProvider都会尝试验证传入的Authentication对象。
使用流程:
- controller
- 配置拦截器/Filter,继承OncePerRequestFilter,验证token
- 配置security,在这里可以指定自定义的provider
@Configuration @EnableWebSecurity public class WebSecurityConfig { @Bean public AuthenticationManager authenticationManager(AuthenticationConfiguration authConfig) throws Exception { return authConfig.getAuthenticationManager(); } //我们自定义的拦截器 @Bean public JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter() { return new JwtAuthenticationTokenFilter(); } @Bean public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception { //基于token,所以不需要csrf防护 httpSecurity.csrf().disable() //基于token,所以不需要session .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .authorizeRequests() //登录注册不需要认证 .antMatchers("/user/login", "/user/register").permitAll() //除上面的所有请求全部需要鉴权认证 .anyRequest() .authenticated(); //禁用缓存 httpSecurity.headers().cacheControl(); //将我们的JWT filter添加到UsernamePasswordAuthenticationFilter前面,因为这个Filter是authentication开始的filter,我们要早于它 httpSecurity.addFilterBefore(jwtAuthenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class); return httpSecurity.build(); } }
认证相关的概念和原理
Cookie被禁用了Session还能使用吗
可以使用,可以把SessionID放在请求路径中,同时可以对SessionID进行加密
为什么Cookie无法防止CSRF攻击,而Token可以
CSRF(Cross Site Request Forgery) 跨站请求伪造,Token存在localStorage浏览器本地缓存,然后每次发送请求携带这个即可。而Cookie是可以被别的获取的
XSS 跨站脚本攻击(Cross Site Scripting)
JWT
格式
xxxxx.yyyyy.zzzz
HEADER
描述JWT的元数据,定义了生成签名的算法以及Token的类型
- typ(Type) :令牌类型,也就是JWT
- alg(Algorithm) :签名算法
PAYLOAD
存放实际要传输的数据,包含Claims(声明,包含JWT的相关信息)
- 注册声明:预定义的一些声明
- 公有声明:JWT签发方可以自定义的声明
- 私有声明:签发方因为项目中需要而自定义的声明
SIGNATURE (签名)
通过Payload和Header和Secret是哟个Header中指定的签名算法
用于防止JWT被篡改
这个签名的生成需要用到:
- Header + Payload。
- 存放在服务端的密钥(一定不要泄露出去)。
- 签名算法。
基本概念
SSO 单点登录
OAuth 2.0
权限设计
RBAC
基于角色的权限控制
ABAC
基于属性的控制访问