[英]Implement Feign Client with Okta as Authorization Server
我終於能夠保護 rest api 與 Okta 作為 OAuth2.0 安全提供者(基本與默認)。 還可以使用 curl 獲取不記名令牌,通過 postman 調用 rest api 並取回結果。
curl --location --request POST 'https://dev-XXXXXX.okta.com/oauth2/default/v1/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'client_id=XXXXXXXXXXXXX' \
--data-urlencode 'client_secret=XXXXXXXXXXXXXXXXXXXXXXXXXXX' \
--data-urlencode 'grant_type=client_credentials
現在我正在嘗試在 Spring Boot 2.X 應用程序中實施 FeignClient(Rest 客戶端)以調用受保護的 api,但在尋找正確的文檔/示例作為指南時遇到困難。 感謝任何指示/建議?
要使用 Feign 收集令牌,您需要以下內容:
import java.util.Map;
import feign.codec.Encoder;
import feign.form.spring.SpringFormEncoder;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.cloud.netflix.feign.support.SpringEncoder;
import org.springframework.context.annotation.Bean;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import static org.springframework.http.MediaType.APPLICATION_FORM_URLENCODED_VALUE;
@FeignClient(name = "oauth2", url = "https://dev-XXXXXX.okta.com/oauth2/default/v1")
public interface TokenFetcher {
@PostMapping(value = "/token", consumes = APPLICATION_FORM_URLENCODED_VALUE)
String token(@RequestBody Map<String, ?> form);
class Configuration {
@Bean
Encoder feignFormEncoder(ObjectFactory<HttpMessageConverters> converters) {
return new SpringFormEncoder(new SpringEncoder(converters));
}
}
}
像這樣使用客戶端:
@Autowired
TokenFetcher tokenFetcher;
public void test() {
Map<String, Object> form = new HashMap<>();
form.put("client_id", "xxxxxx");
form.put("client_secret", "xxxxxx");
form.put("grant_type", "client_credentials");
String jwt = tokenFetcher.token(form);
}
依賴項是:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
<version>1.4.7.RELEASE</version>
</dependency>
<dependency>
<groupId>io.github.openfeign.form</groupId>
<artifactId>feign-form-spring</artifactId>
<version>3.8.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</dependency>
為了使用令牌,您必須在每次調用時將其添加為“授權”header,前綴為“Bearer”(注意空格)。 最簡單的方法是將 RequestInterceptor 添加到您的 FeignClient 中,如下所示:
public class FeignConfiguration {
@Bean
public RequestInterceptor requestInterceptor() {
@Override
public void apply(RequestTemplate requestTemplate) {
requestTemplate.header("Authorization", "Bearer " + jwtTokenStoredSomewhere);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.