Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot OAuth2RestTemplate Client Credentials in Body

I was trying to configure a Spring Boot OAuth2RestTemplate to issue an access token for an OAuth2 Resource Server. The Resource Server only accepts the credentials in the Request Body.

Something like this:

grant_type: "client_credentials"
scope: ""
client_id: "client"
client_secret: "superdupersecret"

In Postman I can archive this by selecting "Send client credentials in body" in the "Get new access token" dialog.

However, I need to get this token in my Spring Boot application. I debugged the OAuth2RestTemplate (and the classes used by the template) but couldn't find a way to configure it to send the credentials as request body.

Am I completely on the wrong track here or just missing something?

Currently I configure the template like this:

 private fun resourceDetails(): BaseOAuth2ProtectedResourceDetails? {
        val resourceDetails: BaseOAuth2ProtectedResourceDetails = ClientCredentialsResourceDetails()
        resourceDetails.id = clientId
        resourceDetails.clientId = clientId
        resourceDetails.clientSecret = clientSecret
        resourceDetails.accessTokenUri = accessTokenUri
        //resourceDetails.clientAuthenticationScheme = AuthenticationScheme.header
        return resourceDetails
    }

I found the clientAuthenticationScheme parameter but only query, form and header are supported

like image 972
GAlexMES Avatar asked Feb 07 '26 10:02

GAlexMES


2 Answers

You must use AuthenticationScheme.form in clientAuthenticationScheme and authenticationScheme to put the data in the body with content type application/x-www-form-urlencoded. It works for me.

The request will be something like that:

POST /auth/oauth/v2/token HTTP/1.1
Host: localhost:8080
Content-Type: application/x-www-form-urlencoded
Content-Length: 136

client_id=user1&client_secret=pass1&grant_type=client_credentials&scope=admin
like image 66
Roberto García Avatar answered Feb 09 '26 08:02

Roberto García


For future reference, the correct answer is setting the client authentication method to client_secret_post in the client registration configuration. It should be something like this

 private fun resourceDetails(): BaseOAuth2ProtectedResourceDetails? {
    val resourceDetails: BaseOAuth2ProtectedResourceDetails = ClientCredentialsResourceDetails()
    resourceDetails.id = clientId
    resourceDetails.clientId = clientId
    resourceDetails.clientSecret = clientSecret
    resourceDetails.accessTokenUri = accessTokenUri
    resourceDetails.clientAuthenticationMethod = ClientAuthenticationMethod.CLIENT_SECRET_POST
    return resourceDetails
}
like image 37
César Alves Avatar answered Feb 09 '26 09:02

César Alves



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!