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:
@@ -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.
|
||||
*/
|
||||
|
||||
@@ -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();
|
||||
|
||||
Reference in New Issue
Block a user