-
-
Notifications
You must be signed in to change notification settings - Fork 1
Client Credentials Grant #6
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
febdf67
`createTokenRequest` returns `HttpRequest.Builder`
overheadhunter 922bad4
adjusted JavaDoc
overheadhunter addb7d8
implemented `clientCredentialsGrant(...)`
overheadhunter 12f4052
adjusted README
overheadhunter dba708a
fix parameter order
overheadhunter 4d16a16
Merge branch 'develop' into feature/client-credential
overheadhunter 308a7f4
reduce visibility
overheadhunter be95b9f
add jetbrains annotations
overheadhunter 7cef133
Merge branch 'develop' into feature/client-credential
overheadhunter 8028a7f
add some OIDC scopes to usage examples
overheadhunter File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
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
106 changes: 106 additions & 0 deletions
106
src/main/java/io/github/coffeelibs/tinyoauth2client/ClientCredentialsGrant.java
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,106 @@ | ||
| package io.github.coffeelibs.tinyoauth2client; | ||
|
|
||
| import org.jetbrains.annotations.ApiStatus; | ||
| import org.jetbrains.annotations.Blocking; | ||
| import org.jetbrains.annotations.NonBlocking; | ||
| import org.jetbrains.annotations.VisibleForTesting; | ||
|
|
||
| import java.io.IOException; | ||
| import java.net.http.HttpClient; | ||
| import java.net.http.HttpRequest; | ||
| import java.net.http.HttpResponse; | ||
| import java.nio.CharBuffer; | ||
| import java.nio.charset.Charset; | ||
| import java.nio.charset.StandardCharsets; | ||
| import java.util.Arrays; | ||
| import java.util.Base64; | ||
| import java.util.Collection; | ||
| import java.util.Map; | ||
| import java.util.Set; | ||
| import java.util.concurrent.CompletableFuture; | ||
|
|
||
| /** | ||
| * Simple OAuth 2.0 Client Credentials Grant | ||
| * | ||
| * @see TinyOAuth2Client#clientCredentialsGrant(Charset, CharSequence) () | ||
| * @see <a href="https://datatracker.ietf.org/doc/html/rfc6749#section-4.4">RFC 6749, Section 4.4</a> | ||
| * @see <a href="https://datatracker.ietf.org/doc/html/rfc6749#section-3.2.1">RFC 6749, Section 3.2.1</a> | ||
| */ | ||
| @ApiStatus.Experimental | ||
| public class ClientCredentialsGrant { | ||
|
|
||
| @VisibleForTesting | ||
| final TinyOAuth2Client client; | ||
|
|
||
| @VisibleForTesting | ||
| final String basicAuthHeader; | ||
|
|
||
| ClientCredentialsGrant(TinyOAuth2Client client, Charset charset, CharSequence clientSecret) { | ||
| this.client = client; | ||
| this.basicAuthHeader = buildBasicAuthHeader(charset, client.clientId, clientSecret); | ||
| } | ||
|
|
||
| /** | ||
| * Requests a new access token, using the pre-shared client credentials to authenticate against the authorization server. | ||
| * | ||
| * @param httpClient The http client used to recieve the authorization code | ||
| * @param scopes The desired <a href="https://datatracker.ietf.org/doc/html/rfc6749#section-3.3">scopes</a> | ||
| * @return The <a href="https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.4">Access Token Response</a> | ||
| * @throws IOException In case of I/O errors when communicating with the token endpoint | ||
| * @throws InterruptedException When this thread is interrupted before a response is received | ||
| * @see #authorizeAsync(HttpClient, String...) | ||
| */ | ||
| @Blocking | ||
| public HttpResponse<String> authorize(HttpClient httpClient, String... scopes) throws IOException, InterruptedException { | ||
| var req = buildTokenRequest(Set.of(scopes)); | ||
| return httpClient.send(req, HttpResponse.BodyHandlers.ofString()); | ||
| } | ||
|
|
||
| /** | ||
| * Requests a new access token, using the pre-shared client credentials to authenticate against the authorization server. | ||
| * | ||
| * @param httpClient The http client used to recieve the authorization code | ||
| * @param scopes The desired <a href="https://datatracker.ietf.org/doc/html/rfc6749#section-3.3">scopes</a> | ||
| * @return The future <a href="https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.4">Access Token Response</a> | ||
| * @see #authorize(HttpClient, String...) | ||
| */ | ||
| @NonBlocking | ||
| public CompletableFuture<HttpResponse<String>> authorizeAsync(HttpClient httpClient, String... scopes) { | ||
| var req = buildTokenRequest(Set.of(scopes)); | ||
| return httpClient.sendAsync(req, HttpResponse.BodyHandlers.ofString()); | ||
| } | ||
|
|
||
| @VisibleForTesting | ||
| static String buildBasicAuthHeader(Charset charset, String clientId, CharSequence clientSecret) { | ||
| // while it is inevitable to have a String copy of the encoded header in memory during the http request, | ||
| // this is an attempt to at least avoid unnecessary copies of the clientSecret: | ||
| var userPassChars = CharBuffer.allocate(clientId.length() + 1 + clientSecret.length()); | ||
| userPassChars.put(clientId).put(':').put(CharBuffer.wrap(clientSecret)).flip(); | ||
| var userPassBytes = charset.encode(userPassChars); | ||
| var base64Bytes = Base64.getEncoder().encode(userPassBytes); | ||
| try { | ||
| return "Basic " + StandardCharsets.US_ASCII.decode(base64Bytes); | ||
| } finally { | ||
| Arrays.fill(userPassChars.array(), ' '); | ||
| Arrays.fill(userPassBytes.array(), (byte) 0x00); | ||
| Arrays.fill(base64Bytes.array(), (byte) 0x00); | ||
| } | ||
| } | ||
|
|
||
| @VisibleForTesting | ||
| HttpRequest buildTokenRequest(Collection<String> scopes) { | ||
| var params = scopes.isEmpty() | ||
| ? Map.of("grant_type", "client_credentials") | ||
| : Map.of("grant_type", "client_credentials", "scope", String.join(" ", scopes)); | ||
| var req = client.createTokenRequest(params); | ||
|
|
||
| // https://datatracker.ietf.org/doc/html/rfc6749#section-2.3.1: | ||
| // The authorization server MUST support the HTTP Basic authentication [...] | ||
| // Alternatively, the authorization server MAY support including the client credentials in the request-body [...] | ||
| // Including the client credentials in the request-body using the two parameters is NOT RECOMMENDED and | ||
| // SHOULD be limited to clients unable to directly utilize the HTTP Basic authentication scheme | ||
| req.setHeader("Authorization", basicAuthHeader); | ||
| return req.build(); | ||
| } | ||
|
|
||
| } |
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
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
90 changes: 90 additions & 0 deletions
90
src/test/java/io/github/coffeelibs/tinyoauth2client/ClientCredentialsGrantTest.java
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,90 @@ | ||
| package io.github.coffeelibs.tinyoauth2client; | ||
|
|
||
| import org.junit.jupiter.api.Assertions; | ||
| import org.junit.jupiter.api.DisplayName; | ||
| import org.junit.jupiter.api.Test; | ||
| import org.junit.jupiter.params.ParameterizedTest; | ||
| import org.junit.jupiter.params.provider.CsvSource; | ||
| import org.mockito.Mockito; | ||
|
|
||
| import java.io.IOException; | ||
| import java.net.URI; | ||
| import java.net.http.HttpClient; | ||
| import java.net.http.HttpRequest; | ||
| import java.net.http.HttpResponse; | ||
| import java.nio.charset.StandardCharsets; | ||
| import java.util.List; | ||
| import java.util.Map; | ||
| import java.util.concurrent.CompletableFuture; | ||
|
|
||
| public class ClientCredentialsGrantTest { | ||
|
|
||
| private final TinyOAuth2Client client = Mockito.spy(new TinyOAuth2Client("Aladdin", URI.create("http://example.com/oauth2/token"))); | ||
|
|
||
| @DisplayName("build basic auth header") | ||
| @ParameterizedTest(name = "{0}:{1} -> {2}") | ||
| @CsvSource({ | ||
| // from https://datatracker.ietf.org/doc/html/rfc7617: | ||
| "Aladdin, open sesame, Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", | ||
| "test, 123£, Basic dGVzdDoxMjPCow==", | ||
| }) | ||
| public void testBuildBasicAuthHeader(String username, String password, String expectedResult) { | ||
| var result = ClientCredentialsGrant.buildBasicAuthHeader(StandardCharsets.UTF_8, username, password); | ||
|
|
||
| Assertions.assertEquals(expectedResult, result); | ||
| } | ||
|
|
||
| @Test | ||
| @DisplayName("buildTokenRequest() builds new http request") | ||
| public void testBuildTokenRequest() { | ||
| var grant = new ClientCredentialsGrant(client, StandardCharsets.UTF_8, "open sesame"); | ||
| var requestBuilder = Mockito.mock(HttpRequest.Builder.class); | ||
| var request = Mockito.mock(HttpRequest.class); | ||
| Mockito.doReturn(requestBuilder).when(client).createTokenRequest(Mockito.any()); | ||
| Mockito.doReturn(request).when(requestBuilder).build(); | ||
|
|
||
| var result = grant.buildTokenRequest(List.of("foo", "bar")); | ||
|
|
||
| Assertions.assertEquals(request, result); | ||
| Mockito.verify(client).createTokenRequest(Map.of(// | ||
| "grant_type", "client_credentials", // | ||
| "scope", "foo bar" | ||
| )); | ||
| Mockito.verify(requestBuilder).setHeader("Authorization", "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=="); | ||
| } | ||
|
|
||
| @Test | ||
| @DisplayName("authorize(...) sends access token request") | ||
| @SuppressWarnings("unchecked") | ||
| public void testAuthorize() throws IOException, InterruptedException { | ||
| var grant = Mockito.spy(new ClientCredentialsGrant(client, StandardCharsets.UTF_8, "open sesame")); | ||
| var httpClient = Mockito.mock(HttpClient.class); | ||
| var httpRequest = Mockito.mock(HttpRequest.class); | ||
| var httpRespone = Mockito.mock(HttpResponse.class); | ||
| Mockito.doReturn(httpRequest).when(grant).buildTokenRequest(Mockito.any()); | ||
| Mockito.doReturn(httpRespone).when(httpClient).send(Mockito.any(), Mockito.any()); | ||
|
|
||
| var result = grant.authorize(httpClient); | ||
|
|
||
| Assertions.assertEquals(httpRespone, result); | ||
| Mockito.verify(httpClient).send(httpRequest, HttpResponse.BodyHandlers.ofString()); | ||
| } | ||
|
|
||
| @Test | ||
| @DisplayName("authorizeAsync(...) sends access token request") | ||
| @SuppressWarnings("unchecked") | ||
| public void testAuthorizeAsync() throws IOException, InterruptedException { | ||
| var grant = Mockito.spy(new ClientCredentialsGrant(client, StandardCharsets.UTF_8, "open sesame")); | ||
| var httpClient = Mockito.mock(HttpClient.class); | ||
| var httpRequest = Mockito.mock(HttpRequest.class); | ||
| var httpRespone = Mockito.mock(HttpResponse.class); | ||
| Mockito.doReturn(httpRequest).when(grant).buildTokenRequest(Mockito.any()); | ||
| Mockito.doReturn(CompletableFuture.completedFuture(httpRespone)).when(httpClient).sendAsync(Mockito.any(), Mockito.any()); | ||
|
|
||
| var result = grant.authorizeAsync(httpClient); | ||
|
|
||
| Assertions.assertEquals(httpRespone, result.join()); | ||
| Mockito.verify(httpClient).sendAsync(httpRequest, HttpResponse.BodyHandlers.ofString()); | ||
| } | ||
|
|
||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.