[英]How to use Spring Boot/Spring Security to wrap a call to an OAuth2 bearer token request?
我遇到了以下问题:为了访问在线API,我需要进行身份验证。 现在,我用自己的代码执行所有操作:
这是代码:
@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的调用。 这就是我想要的工作方式:
我可以在代码中做到这一点,但是我已经在使用Spring Boot。 我想知道如何实现这一目标。 有没有现有的过滤器,拦截器?
感谢您的见解。
尝试从Spring Security使用OAuth2RestTemplate 。 它应该注意获取令牌并在可能的情况下对其进行缓存。 应该在配置文件中对其进行配置,并在您调用该API的任何位置注入它。
有jny提到,要使用的类是OAuth2RestTemplate 。 但是,其构造函数需要实现OAuth2ProtectedResourceDetails 。
有几种实现方式,使用client_credential
是ClientCredentialsResourceDetails
。 我希望仅将@EnableOAuth2Client
添加到我的配置类中,并在application.yml
配置所需的信息就足够了:
security:
oauth2:
client:
grant-type: client_credentials
client-id: my id
client-secret: my secret
access-token-uri: https://bearer.token/get
不幸的是,它不起作用。 原因可以在类OAuth2RestOperationsConfiguration
找到:
@Configuration
@ConditionalOnClass(EnableOAuth2Client.class)
@Conditional(OAuth2ClientIdCondition.class)
public class OAuth2RestOperationsConfiguration {
@Configuration
@ConditionalOnNotWebApplication
protected static class SingletonScopedConfiguration {
@Bean
@ConfigurationProperties("security.oauth2.client")
@Primary
public ClientCredentialsResourceDetails oauth2RemoteResource() {
ClientCredentialsResourceDetails details = new ClientCredentialsResourceDetails();
return details;
}
...
}
...
}
似乎Spring框架假设-错误地,只有非Web应用程序可以使用客户端凭据身份验证。 而就我而言,这是提供者提供的唯一方法。
可以通过复制粘贴相关片段:-)
我的最终代码如下:
@SpringBootApplication
public class RandomApplication {
public static void main(String[] args) {
SpringApplication.run(RandomApplication.class, args);
}
@Bean
@ConfigurationProperties("security.oauth2.client")
ClientCredentialsResourceDetails clientCredentialsResourceDetails() {
return new ClientCredentialsResourceDetails();
}
@Bean
OAuth2RestTemplate oAuth2RestTemplate() {
return new OAuth2RestTemplate(clientCredentialsResourceDetails());
}
@Bean
Random random() {
return new SecureRandom();
}
}
@RestController
public class RandomController {
private final OAuth2RestTemplate oAuth2RestTemplate;
private final Random random;
public RandomController(OAuth2RestTemplate oAuth2RestTemplate, Random random) {
this.oAuth2RestTemplate = oAuth2RestTemplate;
this.random = random;
}
@RequestMapping(value = "/get", method = GET)
public int random() {
int[] bounds = getBounds();
return computeRandom(bounds[0], bounds[1]);
}
private int[] getBounds() {
ResponseEntity<String> res = oAuth2RestTemplate.getForEntity(
"https://configurations.com/bounds", 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;
}
}
注意,控制器的样板要少得多,因为我用RestTemplate
替换了OAuth2RestTemplate
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.