上篇文章我们搭建了授权服务器:SprgingSecurity Oauth2实战 - 01 搭建授权服务器(密码模式),这里搭建资源服务器来访问受限资源
这个存储配置类在搭建授权服务器的时候就讲到过,资源服务器和授权服务器需要使用同一个token存储方式
@Configuration
public class TokenStoreAutoConfiguration {
@Autowired
private RedisConnectionFactory connectionFactory;
@Bean
public TokenStore tokenStore() {
RedisTokenStore redisTokenStore = new CustomRedisTokenStore(connectionFactory);
redisTokenStore.setAuthenticationKeyGenerator(new CustomAuthenticationKeyGenerator());
return redisTokenStore;
}
}
/**
* 自定义的RedisTokenStore处理
*/
public class CustomRedisTokenStore extends RedisTokenStore {
public CustomRedisTokenStore(RedisConnectionFactory connectionFactory) {
super(connectionFactory);
}
@Override
public OAuth2AccessToken readAccessToken(String tokenValue) {
return super.readAccessToken(tokenValue);
}
@Override
public void removeAccessToken(OAuth2AccessToken accessToken) {
super.removeAccessToken(accessToken);
}
@Override
public void removeAccessTokenUsingRefreshToken(OAuth2RefreshToken refreshToken) {
super.removeAccessTokenUsingRefreshToken(refreshToken);
}
}
public class CustomAuthenticationKeyGenerator extends DefaultAuthenticationKeyGenerator {
private static final String RAND = "keyGeneratorRand";
@Override
protected String generateKey(Map<String, String> values) {
// 加入一个随机的要素,保证每次调用时生成的们的hash都不一样
values.put(RAND, UUID.randomUUID().toString());
return super.generateKey(values);
}
}
@Slf4j
@Configuration
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class ResourceServerAutoConfiguration extends ResourceServerConfigurerAdapter {
@Autowired
private TokenStore tokenStore;
@Value("${spring.application.name}")
private String appName;
@Override
public void configure(ResourceServerSecurityConfigurer resources) {
resources.resourceId(appName);
resources.tokenStore(tokenStore);
}
}
server:
port: 8082
spring:
application:
name: knowledge
# 数据库
datasource:
driver-class-name: com.mysql.jdbc.Driver
username: root
password: root
url: jdbc:mysql://localhost:3306/authority?characterEncoding=utf-8&useSSL=false&serverTimezone=Hongkong
@RestController
@RequestMapping("/api/v1")
public class HelloController {
@GetMapping("/hello")
public String hello(){
return "hello spring security";
}
}
① 到授权服务器获取 token:
② 根据 access_token 访问受限资源:
③ 如果不携带access_token,则会报错: