Last active
October 23, 2022 13:39
-
-
Save ekswai/2e263e2c8ca8583c0fd93014d32476a0 to your computer and use it in GitHub Desktop.
spring oauth2 rest template with client credentials grant sample
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.junit.Test; | |
import org.junit.runner.RunWith; | |
import org.master.Application; | |
import org.springframework.beans.factory.annotation.Value; | |
import org.springframework.boot.test.IntegrationTest; | |
import org.springframework.boot.test.SpringApplicationConfiguration; | |
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; | |
import org.springframework.security.oauth2.client.DefaultOAuth2ClientContext; | |
import org.springframework.security.oauth2.client.OAuth2RestTemplate; | |
import org.springframework.security.oauth2.client.token.grant.client.ClientCredentialsResourceDetails; | |
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; | |
import org.springframework.test.context.web.WebAppConfiguration; | |
import java.util.List; | |
import java.util.Map; | |
import static java.lang.String.format; | |
import static java.util.Arrays.asList; | |
/** | |
* Created by XY on 2017/4/10. | |
*/ | |
@RunWith(SpringJUnit4ClassRunner.class) | |
@SpringApplicationConfiguration(classes = Application.class) | |
@WebAppConfiguration | |
@IntegrationTest("server.port:0") | |
public class UserRestControllerTest { | |
@Value("${local.server.port}") | |
protected int port; | |
@Test | |
public void testGetAllUsers() { | |
ClientCredentialsResourceDetails resourceDetails = new ClientCredentialsResourceDetails(); | |
resourceDetails.setAccessTokenUri(format("http://localhost:%d/oauth/token", port)); | |
resourceDetails.setClientId("client"); | |
resourceDetails.setClientSecret("secret"); | |
resourceDetails.setGrantType("client_credentials"); | |
resourceDetails.setScope(asList("read", "write")); | |
DefaultOAuth2ClientContext clientContext = new DefaultOAuth2ClientContext(); | |
OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(resourceDetails, clientContext); | |
restTemplate.setMessageConverters(asList(new MappingJackson2HttpMessageConverter())); | |
System.out.println("access token: " + restTemplate.getAccessToken()); | |
final List<Map> users = restTemplate.getForObject(format("http://localhost:%d/api/users", port), List.class); | |
for (Map user : users) { | |
System.out.println("username: " + user.get("username")); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment