首先,spring security oauth2 这个东西简单来说就是访问接口的时候要在Authorization里带上一个access_token,生产环境下怎么获取这个token的话有四种方法,详情可以看看其他博客。这里就说下使用springboot、junit5的时候怎么用mockMvc来进行接口测试。
在main代码中,需要使用config来开启oauth2的各种组件,例如
如果想在测试中也开启这些组件,则需要在测试启动类上扫描这些组件,(具体是哪些就要问问开发大佬了)例如
然后在初始化mockMvc的时候带上.apply(SecurityMockMvcConfigurers.springSecurity()),
做到这里如无意外就已经开启了oauth的鉴权功能了。这时候再跑一遍已经写好的接口测试代码应该也会报401。
然后解决方法就是需要自己写一个配置AuthorizeConfig和一个组件OAuthHelper。如果不清楚AuthorizeConfig是什么的话建议先去大致了解一下Oauth2的开发教程。这里有个前提,就是接下来用到的resourceId、clientId、userId、scopes等属性都要在数据库中存在
import com.google.common.collect.Sets;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.client.BaseClientDetails;
import org.springframework.security.oauth2.provider.client.InMemoryClientDetailsService;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.stereotype.Compon