Merge pull request #1822 from x-x-z

* pr/1822:
  Polish "Add Basic Authorization for UrlResource"
  Add Basic Authorization for UrlResource

Closes gh-1822
This commit is contained in:
Stephane Nicoll
2023-08-22 16:43:37 +02:00
2 changed files with 27 additions and 0 deletions

View File

@@ -28,6 +28,7 @@ import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
@@ -46,6 +47,8 @@ import org.springframework.util.StringUtils;
*/
public class UrlResource extends AbstractFileResolvingResource {
private static final String AUTHORIZATION = "Authorization";
/**
* Original URI, if available; used for URI and File access.
*/
@@ -237,6 +240,16 @@ public class UrlResource extends AbstractFileResolvingResource {
}
}
@Override
protected void customizeConnection(URLConnection con) throws IOException {
super.customizeConnection(con);
String userInfo = this.url.getUserInfo();
if (userInfo != null) {
String encodedCredentials = Base64.getUrlEncoder().encodeToString(userInfo.getBytes());
con.setRequestProperty(AUTHORIZATION, "Basic " + encodedCredentials);
}
}
/**
* This implementation returns the underlying URL reference.
*/

View File

@@ -33,6 +33,7 @@ import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.stream.Stream;
import okhttp3.mockwebserver.Dispatcher;
@@ -377,6 +378,19 @@ class ResourceTests {
assertThat(request.getHeader("Framework-Name")).isEqualTo("Spring");
}
@Test
void useUserInfoToSetBasicAuth() throws Exception {
startServer();
UrlResource resource = new UrlResource("http://alice:secret@localhost:"
+ this.server.getPort() + "/resource");
assertThat(resource.getInputStream()).hasContent("Spring");
RecordedRequest request = this.server.takeRequest();
String authorization = request.getHeader("Authorization");
assertThat(authorization).isNotNull().startsWith("Basic ");
assertThat(new String(Base64.getDecoder().decode(
authorization.substring(6)), StandardCharsets.ISO_8859_1)).isEqualTo("alice:secret");
}
@AfterEach
void shutdown() throws Exception {
this.server.shutdown();