【发布时间】:2016-10-05 09:38:09
【问题描述】:
我遇到了以下问题:为了访问在线 API,我需要通过身份验证。现在,我用自己的代码做所有事情:
- 调用不记名令牌的令牌 URL
- 获取不记名令牌
- 使用不记名令牌调用真实服务
- 得到结果
代码如下:
@RestController
public class RandomController {
private final Random random;
public RandomController(Random random) {
this.random = random;
}
@RequestMapping(value = "/get", method = GET)
public int random(@RequestParam(value = "limit", defaultValue = "100") int limit) {
String bearerToken = getBearerToken();
int[] bounds = getBounds(bearerToken);
return computeRandom(bounds[0], bounds[1]);
}
private String getBearerToken() {
RestTemplate tokenTemplate = new RestTemplate();
MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
body.add("client_id", "my id");
body.add("client_secret", "my secret");
body.add("grant_type", "client_credentials");
HttpHeaders headers = new HttpHeaders();
headers.add("Accept", "application/json");
HttpEntity<?> entity = new HttpEntity<>(body, headers);
ResponseEntity<String> res = tokenTemplate.exchange(
"https://bearer.token/get", POST, entity, String.class);
Map<String, Object> map = new BasicJsonParser().parseMap(res.getBody());
return (String) map.get("access_token");
}
private int[] getBounds(String bearerToken) {
RestTemplate configurationTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Bearer " + bearerToken);
HttpEntity<?> entity = new HttpEntity<>(headers);
ResponseEntity<String> res = configurationTemplate.exchange(
"https://configurations.com/bounds", HttpMethod.GET, entity, String.class);
Map<String, Object> map = new BasicJsonParser().parseMap(res.getBody());
Map<String, Long> value = (Map<String, Long>) map.get("value");
int lowerBound = value.get("lower").intValue();
int upperBound = value.get("upper").intValue();
return new int[]{lowerBound, upperBound};
}
private int computeRandom(int lowerBound, int upperBound) {
int difference = upperBound - lowerBound;
int raw = random.nextInt(difference);
return raw + lowerBound;
}
}
它有效,但我在每次调用时都在浪费对令牌 URL 的调用。这就是我希望它的工作方式:
- 调用真正的服务
- 如果收到 401
- 调用不记名令牌的令牌 URL
- 获取不记名令牌
- 使用不记名令牌调用服务
- 得到结果
我可以在我的代码中做到这一点,但我已经在使用 Spring Boot。我想知道如何实现这一目标。是否有现成的过滤器、拦截器之类的?
感谢您的见解。
【问题讨论】:
标签: java spring spring-security spring-boot oauth-2.0