springboot2+sercuity+jwt整合2

这里主要讲前一篇文章的安全验证测试

  1. 接口测试

访问spring.io找到其中测试包

 

 

几种注解模式

  1. @PreAuthorize: 在方法调用前,基于表达式计算结果来限制方法访问
  2. @PostAuthorize: 允许方法调用,但是如果表达式结果为fasle则抛出异常
  3. @PostFilter :允许方法调用,但必须按表达式过滤方法结果
  4. @PreFilter:允许方法调用,但必须在进入方法前过滤输入值

引入其中的一种

 

测试用的几种注解

@WithMockUser 指定模拟用户

@WithAnonymousUser 匿名用户

@WithUserDetails  详细的用户

@WithSecurityContext  配置

下面直接访问有权限的save接口:

 

 

加入测试虚拟权限用户测试

新增一条数据了

再换种方法测试

 

也是成功的

 

4.扩展问题

目前Spring-security这个项目开源,git地址为https://github.com/spring-projects/spring-security.git

 

Spring security最新的2个版本:5.0.5 和4.26最新的2个

   5为最新版本改动:

1、应用服务基路径问题

这个问题应该是Spring Boot 2.0升级带来的,既然遇到了,就在这里写一写。笔者在授权服务器想设置一个统一基路径,按照Spring Boot 1.0,是这样的:

server.context-path=/xxx

  • 1

但是升级之后并不好使,最后看官方文档发现改掉了,现在是这样的:

server.servlet.context-path=/xxx

  • 1

2AuthenticationManager无法注入

在覆写AuthorizationServerConfigurerAdapter类的public void configure(AuthorizationServerEndpointsConfigurer endpoints) 方法时,往往需要显式注入AuthenticationManager ,但是在5.x版本中,启动会报如下错误:

***************************
APPLICATION FAILED
TO START
***************************

Description:

Field authenticationManager in cn.springcloud.book.OAuthConfiguration required a bean of type 'org.springframework.security.authentication.AuthenticationManager' that could not be found.

Action:

Consider defining a bean of type 'org.springframework.security.authentication.AuthenticationManager' in your configuration.

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

解决方案: 

在启动主类继承WebSecurityConfigurerAdapter 类同时,手动注入:

    @Bean(name = BeanIds.AUTHENTICATION_MANAGER)
   
@Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
       
return super.authenticationManagerBean();
    }

  • 1
  • 2
  • 3
  • 4
  • 5

3、登陆报错:There is no PasswordEncoder mapped for the id “null”

在使用Spring Security 5.x登陆页面进行登陆时,后端会报错:There is no PasswordEncoder mapped for the id “null”,因为5.x版本新增了多种密码加密方式,必须指定一种,比如这样解决:

    @Bean
    public static NoOpPasswordEncoder passwordEncoder() {
     
return (NoOpPasswordEncoder) NoOpPasswordEncoder.getInstance();
    }

  • 1
  • 2
  • 3
  • 4

下列加密方式供参考,选取一种即可:

bcrypt - BCryptPasswordEncoder (Also used for encoding)
ldap - LdapShaPasswordEncoder
MD4 - Md4PasswordEncoder
MD5 -
new MessageDigestPasswordEncoder("MD5")
noop - NoOpPasswordEncoder
pbkdf2 - Pbkdf2PasswordEncoder
scrypt - SCryptPasswordEncoder
SHA-
1 - new MessageDigestPasswordEncoder("SHA-1")
SHA-
256 - new MessageDigestPasswordEncoder("SHA-256")
sha256 - StandardPasswordEncoder

 

4.Spring MVC测试集成

MockMvc 对象 ,用于发送模拟http请求。

 

 

这些参数可以参考官方文档

猜你喜欢

转载自blog.csdn.net/qq_40650378/article/details/82803384