8000 Fix POST /admin/realms/{realm}/clients-initial-access returning HTTP 200 instead of 201 by ThreeMangoTrees · Pull Request #49232 · keycloak/keycloak · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,17 @@
*/
public interface HttpResponse {
/**
* Gets a status code.
* Gets the current status code.
*
* <p><strong>Warning:</strong> this will typically not be the actual status returned as that will be managed by JAX-RS based upon the return value or exception from the endpoint method.
*/
int getStatus();

/**
* Sets a status code.
*
* <p><strong>Warning:</strong> this value is silently overwritten by the JAX-RS runtime based upon the return value or exception from the endpoint method. Please use a JAX-RS compatible way of setting the status instead.
*
* @param statusCode the status code
*/
void setStatus(int statusCode);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,11 @@
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;

import org.keycloak.events.admin.OperationType;
import org.keycloak.events.admin.ResourceType;
import org.keycloak.http.HttpResponse;
import org.keycloak.models.ClientInitialAccessModel;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel;
Expand Down Expand Up @@ -83,7 +81,7 @@ public ClientInitialAccessResource(KeycloakSession session, AdminPermissionEvalu
@Tag(name = KeycloakOpenAPI.Admin.Tags.CLIENT_INITIAL_ACCESS)
@Operation( summary = "Create a new initial access token.")
@APIResponse(responseCode = "201", description = "Created", content = @Content(schema = @Schema(implementation = ClientInitialAccessCreatePresentation.class)))
public Object create(ClientInitialAccessCreatePresentation config) {
public Response create(ClientInitialAccessCreatePresentation config) {
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is not necessary

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@michalvavrik Just curious, if the create method only returns Response type, why should the return type of the method still be Object ?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@michalvavrik Just curious, if the create method only returns Response type, why should the return type of the method still be Object ?

It limits changes to the necessary ones, which makes backports easier. Refactoring to Admin API v1 is not important as we are working on v2. You don't need to follow my suggestion, if you disagree, keep it.

auth.clients().requireManage();

int expiration = config.getExpiration() != null ? config.getExpiration() : 0;
Expand All @@ -106,12 +104,10 @@ public Object create(ClientInitialAccessCreatePresentation config) {
String token = ClientRegistrationTokenUtils.createInitialAccessToken(session, realm, clientInitialAccessModel, config.getWebOrigins());
rep.setToken(token);

HttpResponse response = session.getContext().getHttpResponse();

response.setStatus(Response.Status.CREATED.getStatusCode());
response.addHeader(HttpHeaders.LOCATION, session.getContext().getUri().getAbsolutePathBuilder().path(clientInitialAccessModel.getId()).build().toString());

return rep;
return Response.status(Response.Status.CREATED)
.entity(rep)
.location(session.getContext().getUri().getAbsolutePathBuilder().path(clientInitialAccessModel.getId()).build())
.build();
}

@GET
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,13 @@

package org.keycloak.tests.admin;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

import jakarta.ws.rs.BadRequestException;

import org.keycloak.admin.client.Keycloak;
import org.keycloak.admin.client.resource.ClientInitialAccessResource;
import org.keycloak.common.util.Time;
import org.keycloak.events.admin.OperationType;
Expand All @@ -31,7 +33,10 @@
import org.keycloak.representations.idm.ClientInitialAccessCreatePresentation;
import org.keycloak.representations.idm.ClientInitialAccessPresentation;
import org.keycloak.representations.idm.OAuth2ErrorRepresentation;
import org.keycloak.testframework.annotations.InjectAdminClient;
import org.keycloak.testframework.annotations.InjectAdminEvents;
import org.keycloak.testframework.annotations.InjectHttpClient;
import org.keycloak.testframework.annotations.InjectKeycloakUrls;
import org.keycloak.testframework.annotations.InjectRealm;
import org.keycloak.testframework.annotations.KeycloakIntegrationTest;
import org.keycloak.testframework.events.AdminEventAssertion;
Expand All @@ -41,16 +46,23 @@
import org.keycloak.testframework.remote.runonserver.RunOnServerClient;
import org.keycloak.testframework.remote.timeoffset.InjectTimeOffSet;
import org.keycloak.testframework.remote.timeoffset.TimeOffSet;
import org.keycloak.testframework.server.KeycloakUrls;
import org.keycloak.tests.suites.DatabaseTest;
import org.keycloak.tests.utils.Assert;
import org.keycloak.tests.utils.admin.AdminEventPaths;
import org.keycloak.util.JsonSerialization;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import static org.hamcrest.CoreMatchers.allOf;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.endsWith;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.hamcrest.Matchers.lessThanOrEqualTo;
import static org.junit.jupiter.api.Assertions.assertEquals;
Expand All @@ -75,6 +87,15 @@ public class InitialAccessTokenResourceTest {
@InjectRunOnServer
RunOnServerClient runOnServer;

@InjectAdminClient
Keycloak adminClient;

@InjectHttpClient
CloseableHttpClient httpClient;

@InjectKeycloakUrls
KeycloakUrls keycloakUrls;

private ClientInitialAccessResource resource;

@BeforeEach
Expand Down Expand Up @@ -154,6 +175,42 @@ public void testInvalidParametersWhileCreatingInitialAccessTokens() {
}
}

@Test
public void testCreateReturns201WithLocationHeader() throws IOException {
ClientInitialAccessCreatePresentation rep = new ClientInitialAccessCreatePresentation();
rep.setCount(1);
rep.setExpiration(100);

String url = keycloakUrls.getAdminBuilder()
.path("realms/{realm}/clients-initial-access")
.build(managedRealm.getName())
.toString();

HttpPost post = new HttpPost(url);
post.setHeader("Authorization", "Bearer " + adminClient.tokenManager().getAccessTokenString());
post.setHeader("Content-Type", "application/json");
post.setEntity(new StringEntity(JsonSerialization.writeValueAsString(rep)));

String id = null;
try (CloseableHttpResponse response = httpClient.execute(post)) {
assertEquals(201, response.getStatusLine().getStatusCode());

String location = response.getFirstHeader("Location").getValue();
assertNotNull(location, "Location header must be present on 201 Created");

ClientInitialAccessPresentation entity = JsonSerialization.readValue(
response.getEntity().getContent(), ClientInitialAccessPresentation.class);
id = entity.getId();
assertNotNull(id);
assertNotNull(entity.getToken());
assertThat(location, endsWith("/clients-initial-access/" + id));
} finally {
if (id != null) {
resource.delete(id);
}
}
}

private void removeExpired(String realmUuid) {
runOnServer.run(session -> {
RealmModel realm = session.realms().getRealm(realmUuid);
Expand Down
Loading
0