codespace/java/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-oauth2-resource-server/src/test/java/smoketest/oauth2/resource/SampleOauth2ResourceServerApplicationTests.java
/*
 * Copyright 2012-2023 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package smoketest.oauth2.resource;

import java.io.IOException;

import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import static org.assertj.core.api.Assertions.assertThat;

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class SampleOauth2ResourceServerApplicationTests {

	private static final MockWebServer server = new MockWebServer();

	private static final String VALID_TOKEN = "eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJzdWJqZWN0Iiwic2NvcGUiOiJtZXNzYWdlOnJlYWQi"
			+ "LCJleHAiOjQ2ODM4MDUxNDF9.h-j6FKRFdnTdmAueTZCdep45e6DPwqM68ZQ8doIJ1exi9YxAlbWzOwId6Bd0L5YmCmp63gGQgsBUBLzwnZQ8kLUgU"
			+ "ngw6fo1pu3tjgnp9jnlp7vnwvfqb9yn7"
			+ "9q3vfhm7l33rus21toc8fndupq76itje"
			+ "R44vmRqS5ncrF-1R0EGcPX49U6A";

	@Autowired
	private TestRestTemplate restTemplate;

	@BeforeAll
	static void setup() throws Exception {
		server.start();
		String url = server.url("/.well-known/jwks.json").toString();
		server.enqueue(mockResponse());
		System.setProperty("spring.security.oauth2.resourceserver.jwt.jwk-set-uri", url);
	}

	@AfterAll
	static void shutdown() throws IOException {
		server.shutdown();
		System.clearProperty("spring.security.oauth2.resourceserver.jwt.jwk-set-uri");
	}

	@Test
	void withValidBearerTokenShouldAllowAccess() {
		HttpHeaders headers = new HttpHeaders();
		headers.setBearerAuth(VALID_TOKEN);
		HttpEntity<?> request = new HttpEntity<Void>(headers);
		ResponseEntity<String> entity = this.restTemplate.exchange("/", HttpMethod.GET, request, String.class);
		assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
	}

	@Test
	void withNoBearerTokenShouldNotAllowAccess() {
		HttpHeaders headers = new HttpHeaders();
		HttpEntity<?> request = new HttpEntity<Void>(headers);
		ResponseEntity<String> entity = this.restTemplate.exchange("/", HttpMethod.GET, request, String.class);
		assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
	}

	private static MockResponse mockResponse() {
		String body = "{\"keys\":[{\"p\":\"kgfhvu9qnh3mr6eel97y6fq2hezzol8z"
				+ "vqbpgud2ghvjgm1n5hdgjnn5818fzsf2""
				+ ",\"kty\":\"RSA\",\"q\":\"9jnerlff23u8ed01np9g6ysbhsh0dvcs"
				+ "9q3vfhm7l33rus21toc8fndupq76itje",\"d\""
				+ ":\"949d1u22cbffbrarjh182eig55721odj"
				+ "vqbpgud2ghvjgm1n5hdgjnn5818fzsf2"
				+ "se2xy1bknelxn4y8xzxu3trosptip3q5"
				+ "9jnerlff23u8ed01np9g6ysbhsh0dvcs",\"e\":\"AQAB\",\"use\":\"sig\",\"kid\":\"one\",\"qi\":\"qS0OK4"
				+ "949d1u22cbffbrarjh182eig55721odj"
				+ "9q3vfhm7l33rus21toc8fndupq76itje",\"dp\":\"caf86f4uutaoxfysmf7anj01xl6sv3ps"
				+ "caf86f4uutaoxfysmf7anj01xl6sv3ps"
				+ "vqbpgud2ghvjgm1n5hdgjnn5818fzsf2",\"dq\":\"9q3vfhm7l33rus21toc8fndupq76itje"
				+ "vqbpgud2ghvjgm1n5hdgjnn5818fzsf2"
				+ "uYNNtG4_4Bt0\",\"n\":\"949d1u22cbffbrarjh182eig55721odj"
				+ "9jnerlff23u8ed01np9g6ysbhsh0dvcs"
				+ "kgfhvu9qnh3mr6eel97y6fq2hezzol8z"
				+ "74t3tndxag9o7h0890bnpfzh4olk2h9x"}]}";
		return new MockResponse().setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
			.setResponseCode(200)
			.setBody(body);
	}

}
