Skip to content

BasicAuthenticationInterceptor should cache the encoded credentials #23204

@membersound

Description

@membersound

As BasicAuthenticationInterceptor is just an Interceptor that recreates the encoded Basic Authentication header for each request, I think the encoded credentials should be cached and reused.

Maybe org.springframework.http.HttpHeaders could offer a static encodeBasicAuth(String username, String password, @Nullable Charset charset) that does the same as setBasicAuth(), but instead of setting the header directly, it just returns the Basic <encoded username:password> string.

Suggested class therefore would change to:

public class BasicAuthenticationInterceptor implements ClientHttpRequestInterceptor {
        private final String basicAuth;

	public BasicAuthenticationInterceptor(String username, String password) {
		this(username, password, null);
	}

	public BasicAuthenticationInterceptor(String username, String password, @Nullable Charset charset) {
		Assert.doesNotContain(username, ":", "Username must not contain a colon");
		this.basicAuth = HttpHeaders.encodeBasicAuth(username, password, charset);
	}


	@Override
	public ClientHttpResponse intercept(
			HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {

		HttpHeaders headers = request.getHeaders();
		if (!headers.containsKey(HttpHeaders.AUTHORIZATION)) {
			headers.set(HttpHeaders.AUTHORIZATION, basicAuth);
		}
		return execution.execute(request, body);
	}

}

Pro: neither username nor pass has to be kept as cleartext.

Metadata

Metadata

Assignees

Labels

in: webIssues in web modules (web, webmvc, webflux, websocket)type: enhancementA general enhancement

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions