Spring Security

简介

spring security 的核心功能主要包括:

认证 (你是谁)
授权 (你能干什么)
攻击防护 (防止伪造身份)

其核心就是一组过滤器链,项目启动后将会自动配置。最核心的就是 Basic Authentication Filter 用来认证用户的身份,一个在spring security中一种过滤器处理一种认证方式。
Spring Security 是针对Spring项目的安全框架,也是Spring Boot底层安全模块默认的技术选型,他可以实现强大的Web安全控制,对于安全控制,我们仅需要引入 spring-boot-starter-security 模块,进行少量的配置,即可实现强大的安全管理!

记住几个类:

  • WebSecurityConfigurerAdapter:自定义Security策略

  • AuthenticationManagerBuilder:自定义认证策略

  • @EnableWebSecurity:开启WebSecurity模式

Spring Security的两个主要目标是 “认证” 和 “授权”(访问控制)。

“认证”(Authentication)

身份验证是关于验证您的凭据,如用户名/用户ID和密码,以验证您的身份。

身份验证通常通过用户名和密码完成,有时与身份验证因素结合使用。

“授权” (Authorization)

授权发生在系统成功验证您的身份后,最终会授予您访问资源(如信息,文件,数据库,资金,位置,几乎任何内容)的完全权限。

这个概念是通用的,而不是只在Spring Security 中存在。

认证和授权

protected void configure(HttpSecurity http ) throws Exception {
             http
                  .authorizeRequests()            1                                                   
                        .antMatchers( "/resources/**", "/signup" , "/about").permitAll()  2
                        .antMatchers( "/admin/**").hasRole("ADMIN" )                    3    
                        .antMatchers( "/db/**").access("hasRole('ADMIN') and hasRole('DBA')")  4
                        .anyRequest().authenticated()        5
                                         
                        .and()
                   // ...
                  .formLogin();
      }

1、http.authorizeRequests()方法有很多子方法,每个子匹配器将会按照声明的顺序起作用。

2、指定用户可以访问的多个url模式。特别的,任何用户可以访问以"/resources"开头的url资源,或者等于"/signup"或about

3、任何以"/admin"开头的请求限制用户具有 "ROLE_ADMIN"角色。你可能已经注意的,尽管我们调用的hasRole方法,但是不用传入"ROLE_"前缀

4、任何以"/db"开头的请求同时要求用户具有"ROLE_ADMIN"和"ROLE_DBA"角色。

5、任何没有匹配上的其他的url请求,只需要用户被验证。
定制请求的授权规则

@Override
protected void configure(HttpSecurity http) throws Exception {
    // 定制请求的授权规则
    // 首页所有人可以访问
    http.authorizeRequests().antMatchers("/").permitAll()
    .antMatchers("/level1/**").hasRole("vip1")
    .antMatchers("/level2/**").hasRole("vip2")
    .antMatchers("/level3/**").hasRole("vip3");
}

测试一下:发现除了首页都进不去了!因为我们目前没有登录的角色,因为请求需要登录的角色拥有对应的权限才可以!

在configure()方法中加入以下配置,开启自动配置的登录功能!

// 开启自动配置的登录功能
// /login 请求来到登录页
// /login?error 重定向到这里表示登录失败
http.formLogin();

查看刚才登录页的注释信息;

我们可以定义认证规则,重写configure(AuthenticationManagerBuilder auth)方法

认证,spring boot2.1.x可以直接使用,
密码编码:passwordEncoder
在Spring Security 5.0+ 新增了很多的加密方法

//定义认证规则
@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {       
 **在内存中定义,也可以在jdbc中去拿....   **
 auth.inMemoryAuthentication()         
  .withUser("kuangshen").password("123456").roles("vip2","vip3")           
 .and()            
.withUser("root").password("123456").roles("vip1","vip2","vip3")            
.and()           
 .withUser("guest").password("123456").roles("vip1","vip2");}

9、测试,我们可以使用这些账号登录进行测试!发现会报错!

There is no PasswordEncoder mapped for the id “null”

image.png

10、原因,我们要将前端传过来的密码进行某种方式加密,否则就无法登录,修改代码

//定义认证规则@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {    //在内存中定义,也可以在jdbc中去拿....   
 //Spring security 5.0中新增了多种加密方式,也改变了密码的格式。    
//要想我们的项目还能够正常登陆,需要修改一下configure中的代码。我们要将前端传过来的密码进行某种方式加密    
//spring security 官方推荐的是使用bcrypt加密方式。    
    auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())          
  .withUser("kuangshen").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2","vip3")         
   .and()            
.withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")            
.and()          
  .withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2");}

11、测试,发现,登录成功,并且每个角色只能访问自己认证下的规则!搞定


90282DE5DC87B6ABF7A8297632BEF018.png
10E97CD99FE72C96E05E7B27EDA2B253.png
D52A5BFB1D1F668B87C1B26001B59C2A.png
30B2C898752728CF3E8D3CBF4196EC9F.png
83D0AB2B0BDCE2FFDB344217D7CF59E5.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容