Используя Spring Boot, я настроил бон OAuth2resttemplate в классе конфигурации и соответствующие свойства в файле свойств. Я использовал Swagger Codegen для создания клиентской заглушки. Когда я пытаюсь позвонить в API Restful, Spring не удается получить токен доступа с основной причиной «неподдерживаемый тип носителя». Ниже приведена Stacktrace, моя конфигурация клиента Spring Security и мои попытки исправить. Любая помощь будет очень признателен! scope = [read], client_id = [val from props], client_secret = [val from props]}
error = "access_denied", error_description = "access token.
at at org.springframework.security.oauth2.client.token.oauth2accesstokensupport.retrieveTetoken (oauth2accesstokensupport.java:142)
at org.springframework.security.oauth2.client.token.grant.client.clientcredentialSaccessTokenProvider.obtainaccesstoken (clientCredentialSaccessTokenProvider.java:44)
at org.springframework.security.oauth2.client.token.accesstokenproviderchain.obtaintewaccesstokeninternal (accesstokenproviderchain.java:148)
at org.springframework.security.oauth2.client.token.accesstokenproviderchain.obtainaccesstoken (accesstokenproviderchain.java:121)
at org.springframework.security.oauth2.client.oauth2resttemplate.acquireaccesstoken (oauth2resttemplate.java:221)
at org.springframework.security.oauth2.client.oauth2resttemplate.getaccesstoken (oauth2resttemplate.java:173)
at org.springframework.security.oauth2.client.oauth2resttemplate.createravest (oautheprestteptateptatept at org.springframework.web.client.resttemplate.doexecute (resttemplate.java:735)
at org.springframework.security.oauth2 org.springframework.web.client.resttemplate.exchange (resttemplate.java:651)
at com.my.co.service.holidays.client.invoker.apiclient.invokeapi (apiclient.java:518)
at at at. com.my.co.service.holidays.client.api.holidaysapi.getholidays (kholidaysapi.java:183)
at com.my.co.service.holiday.holidaysapitest.getholidaystest (Holidaysapitest.java:66) att sun.reflect.nativemethodaccsessorimpl.invoke0 (нативный метод)
at sun.reflect.nativemethodacccessorimpl.invoke (nativemethodaccessorimpl.java:62)
sun.reflect.delegatingmethodaccsorsiMpl.invoke (делегирование methodaccessoriMpl.java:43)
at java.lang.reflect.method.invoke (метод.java:498)
at org.junit.platform.commons.util.reflectionutils.invokemethod (Reflectionutils.java:686)
at org.junit.jupiter.engine.excution.methodinvocation.procece (methodinvocation.java:60)
at at at at at at at at at at at at at org.junit.jupiter.engine.execution.invocationInterceptorChain $ velivationInvocation.procecent (vocationInterceptorChain.java:131)
at org.junit.jupiter.engine.extension.timeoutextension.intercept (timeoutextension.java:149)
org.junit.jupiter.engine.extension.timeoutextension.interptteStableMethod (timeoutextension.java:140)
at org.junit.jupiter.engine.extension.timeoutextension.InterceptTestMethod (timeoutextension.java:84)
att org.junit.jupiter.engine.execution.executableInvoker $ ReflectiveInterceptorCall.lambda $ ofvoidmethod $ 0 (executibleInvoker.java:115)
at org.junit.jupiter.engine.execution.executableInvoker.lambda $ villable $ 0 ($ 0 ($ 0 ($ 0. /> at org.junit.jupiter.engine.execution.invocationInterceptorChain $ reterceptedInvocation.proceed (upocationInterceptorChain.java:106)
at org.junit.jupiter.engine.execution.invocationInterceptorChain.procece (vocationInterceptorCeptorChain. org.junit.jupiter.engine.execution.invocationInterceptorChain.chainandInvoke (vocationInterceptorChain.java:45)
at org.junit.jupiter.engine.execution.invocationInterceptorChain.invoke (envocation interceptorchain. org.junit.jupiter.engine.execution.executableInvoker.invoke (executibleInvoker.java:104)
at org.junit.jupiter.engine.execution.executableInvoker.invoke (ExecumbleInvoker.java:98)
at at at at at at at at at at at at atervoker.invoke. org.junit.jupiter.engine.descriptor.testmethodtestdescriptor.lambda $ invoketestmethod $ 6 (testmethodtestdescriptor.java:212)
at org.junit.platform.engine.support.hierarchical.trowablecollector.execute (throwableCollector.java:73)
at org.junit.jupiter.engine.descriptor.testmethodtestdescriptor.invoketesteSteDmethod (testmethodTescripryptor.jethodtestdescriptor.invoketesteSteDmethod. at org.junit.jupiter.engine.descriptor.testmethodtestdescriptor.execute (testmethodtestdescriptor.java:137)
org.junit.jupiter.engine.descriptor.testmethodtestdescriptor.execute (testmethodtestdescriptor.java:71)
at org.junit.platform.engine.support.hierarchical.nodetestsk.lambda $ executorecurbirly $ 5 (nodetesttask.java:135)
at org.junit.platform.engine.support.hierarchical.trowablecollector.execute (hookablecollector.jepport.hierarchical.trowablecollector.execute (kpoblecollector. org.junit.platform.engine.support.hierarchical.nodetesttask.lambda $ executorecurbirly $ 7 (nodetesttask.java:125)
at org.junit.platform.engine.support.hierarchical.node.around (node.java org.junit.platform.engine.support.hierarchical.nodetestsk.lambda $ executorecurbirly $ 8 (nodetesttask.java:123)
at org.junit.platform.engine.support.hierarchical.trowablecollector.execute (throwablecollector.japort.7 org.junit.platform.engine.support.hierarchical.nodetestsk.executerecursive (nodetesttask.java:122)
at org.junit.platform.engine.support.hierarchical.nodetesttask.execut java.util.arraylist.foreach (arraylist.java:1257)
at org.junit.platform.engine.support.hierarchical.samethreadhierarchiteSteStexeCutorService.invokeall (samethreadHicalTeSexeCuterService.Java:38)
org.junit.platform.engine.support.hierarchical.nodetesttask.lambda $ executorecurbirly $ 5 (nodetesttask.java:139)
at org.junit.platform.engine.support.hierarchical.trowablecollector.execute (throwablecollectrector.jepport.hierarchical.trowablecollector.execute (kpoblecollector. org.junit.platform.engine.support.hierarchical.nodetesttask.lambda $ executorecurbirly $ 7 (nodetesttask.java:125)
at org.junit.platform.engine.support.hierarchical.node.around (node.java org.junit.platform.engine.support.hierarchical.nodetestsk.lambda $ executorecurbirly $ 8 (nodetesttask.java:123)
at org.junit.platform.engine.support.hierarchical.trowablecollector.execute (throwablecollector.japort.7 org.junit.platform.engine.support.hierarchical.nodetestsk.executerecursive (nodetesttask.java:122)
at org.junit.platform.engine.support.hierarchical.nodetesttask.execut java.util.arraylist.foreach (arraylist.java:1257)
at org.junit.platform.engine.support.hierarchical.samethreadhierarchiteSteStexeCutorService.invokeall (samethreadHicalTeSexeCuterService.Java:38)
org.junit.platform.engine.support.hierarchical.nodetesttask.lambda $ executorecurbirly $ 5 (nodetesttask.java:139)
at org.junit.platform.engine.support.hierarchical.trowablecollector.execute (throwablecollectrector.jepport.hierarchical.trowablecollector.execute (kpoblecollector. org.junit.platform.engine.support.hierarchical.nodetesttask.lambda $ executorecurbirly $ 7 (nodetesttask.java:125)
at org.junit.platform.engine.support.hierarchical.node.around (node.java org.junit.platform.engine.support.hierarchical.nodetestsk.lambda $ executorecurbirly $ 8 (nodetesttask.java:123)
at org.junit.platform.engine.support.hierarchical.trowablecollector.execute (throwablecollector.japort.7 org.junit.platform.engine.support.hierarchical.nodetestsk.executerecursive (nodetesttask.java:122)
at org.junit.platform.engine.support.hierarchical.nodetesttask.execut org.junit.platform.engine.support.hierarchical.samethreadhierarchicalteSexeCutorService.submit (samethreadHierarchTeSteSeCutorService.java:32)
at org.junit.platform.engine.support.hierarchical.hierarchicalteStexeCutor.execute (hierarchicalteSexeCutor.java:57)
at org.junit.platform.engine.support.hierarchical.hierarchicaltestengine.execute.gine.support.hierarchical.hierarchtes /> at org.junit.platform.launcher.core.defaultlauncher.execute (defaultlauncher.java:248)
at org.junit.platform.launcher.core.defaultlauncher.lambda $ execute $ 5 (Defaultlauncher.java: 21111111111111111. org.junit.platform.launcher.core.defaultlauncher.withinterceptendeams (defaultlauncher.java:226)
at org.junit.platform.launcher.core.defaultlauncher.execute (defaultlauncher.java:199)
org.junit.platform.launcher.core.defaultlauncher.execute (defaultlauncher.java:132)
at com.intellij.junit5.junit5ideatestrunner.startrunnerwithargs (junit5idestrunner. com.intellij.rt.junit.ideatestrunner $ repeater.startrunnerwithargs (ideatestrunner.java:33)
at com.intellij.rt.junit.junitstarter.preparestreamsandstart (junitstarter.java:230)
att com.intellij.rt.junit.junitstarter.main (junitstarter.java:58)
** вызван: error = "Invalid_Request", error_description = "{code = 415, сообщение = не поддерживается медиа org.springframework.security.oauth2.common.exceptions.oauth2exceptionjackson2deserializer.deserialize (oauth2exceptionjackson2deserializer.java:119)
at org.springframework.security.oauth2.common.exceptions.oauth2exceptionjackson2deserializer.deserialize (oauth2exceptionjackson2deserializer.java:33)
at com.fasterxml.jackson.databind.objectmapper._readmap.javemapper.jjackson.databind.objectmapper._readmappere.jjackson.jachson.bind.objectmapper._adermapper. /> at com.fasterxml.jackson.databind.objectmapper.readvalue (objectmapper.java:3519)
at org.springframework.http.converter.json.abstractjackson2httpmessageconverter.readjavatype (Abstractjackson2httpmessageConverter.java:269)
at org.springframework.http.converter.json.abstractjackson2httpmessageconverter.readinternal (Abstractjackson2httpmessageConverter.java:249)
at org.springframework.http.converter.abstracttpmessageconverter.read (artabracttpmessageconverter.java:199)
at org.springframework.security.oauth2.client.token.oauth2accesstokensupport $ accesstokenerrorhandler.handleerror (oauth2accesstokensupport.java:237)
at org.springframework.web.client.ResponseErrorHandler.handleerror (responseErrorHandler.java:63)
at org.springframework.web.client.resttemplate.handleresponse (resttemplate.java:782)
at at. org.springframework.web.client.resttemplate.doexecute (resttemplate.java:740)
at org.springframework.web.client.resttemplate.execute (resttemplate.java:695)
at. org.springframework.security.oauth2.client.token.oauth2accesstokensupport.retrieveTetoken (oauth2accesstokensupport.java:137)
... 75 More
< /pre>
ниже моя конфигурация для клиента Oauth2 < /p> p> p> p> p> p> p> p> p> p> p> p> p> p> p> p> p> p> p> p> < /p> p> p> < /p> p> p> p> p> p> p> p> p> p> < /pre>
ниже.application.properties:
spring.security.oauth2.holiday.client.clientId=valid_key_is_here
spring.security.oauth2.holiday.client.clientSecret=valid_secret_is_here
spring.security.oauth2.holiday.client.accessTokenUri=https://dev-api.some-domain.com/auth/oauth2/v1/token
spring.security.oauth2.holiday.client.clientAuthenticationScheme=form
spring.security.oauth2.holiday.client.grantType=client_credentials
spring.security.oauth2.holiday.client.scope=read
< /code>
@Configuration
@EnableOAuth2Client
public class SpringOauthRestClientConfig {
@Bean
@ConfigurationProperties("spring.security.oauth2.holiday.client")
public OAuth2ProtectedResourceDetails oAuthDetails() {
return new ClientCredentialsResourceDetails();
}
@Bean
public RestTemplate restTemplate() {
OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(oAuthDetails());
for (HttpMessageConverter converter : restTemplate.getMessageConverters()) {
if (converter instanceof AbstractJackson2HttpMessageConverter) {
ObjectMapper mapper = ((AbstractJackson2HttpMessageConverter) converter).getObjectMapper();
mapper.registerModule(new JavaTimeModule());
}
}
// This allows us to read the response more than once - Necessary for debugging.
restTemplate.setRequestFactory(new BufferingClientHttpRequestFactory(restTemplate.getRequestFactory()));
return restTemplate;
}
}
< /code>
I have tried extending the Spring class ClientCredentialsAccessTokenProvider, чтобы предоставить мою собственную реализацию метода eaveAccessToken () , чтобы я мог установить тип контента в заголовке. Затем я ввожу свой пользовательский класс в Resttemplate. Все еще получите ту же ошибку, когда Spring пытается получить токен доступа. < /P>
public class ClientCredentialsCustomAccessTokenProvider extends ClientCredentialsAccessTokenProvider {
@Override
public OAuth2AccessToken obtainAccessToken(OAuth2ProtectedResourceDetails details, AccessTokenRequest request) throws UserRedirectRequiredException, AccessDeniedException, OAuth2AccessDeniedException {
ClientCredentialsResourceDetails resource = (ClientCredentialsResourceDetails)details;
HttpHeaders headers1 = new HttpHeaders();
headers1.add("Content-Type", "application/x-www-form-urlencoded");
return retrieveToken(request, resource, this.getParametersForTokenRequest(resource), headers1);
}
< /code>
If I use Postman to hit the authorization server, I successfully get back a token
{
"tokenType": "BearerToken",
"expiresIn": "899",
"accessToken": "dv6fnhBALtNzlhjMyCRfa9JDYodd"
}
< /code>
using these settings in Postman
POST request,
Authorization - Basic with my client_id/secret as username/password,
Headers - Content-Type = application/x-www-form-urlencoded,
Body - grant_type = client_credentials
< /code>
In JUnit test, I can set the token value (and bypass the Spring injection of RestTemplate) Использование ответа от почтана и позвоните в службу без проблем.
HolidaysApi api = new HolidaysApi();
OAuth oAuth2 = (OAuth) api.getApiClient().getAuthentication("OAuth2");
oAuth2.setAccessToken("dv6fnhBALtNzlhjMyCRfa9JDYodd");
Подробнее здесь: https://stackoverflow.com/questions/638 ... est-code-4
Spring Security Oauth2 Client Get Tocken Token снят с неверным кодом запроса = 415, сообщение = неподдерживаемый тип нос ⇐ JAVA
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение