Skip to content

Commit

Permalink
refactor: extract basic auth parsing to its own class (#399)
Browse files Browse the repository at this point in the history
  • Loading branch information
sdelamo committed Sep 25, 2020
1 parent e2038f5 commit 5bf1762
Show file tree
Hide file tree
Showing 3 changed files with 99 additions and 32 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
import io.micronaut.context.annotation.Requires;
import io.micronaut.core.async.publisher.Publishers;
import io.micronaut.core.util.StringUtils;
import io.micronaut.http.HttpHeaderValues;
import io.micronaut.http.HttpRequest;
import io.micronaut.security.filters.AuthenticationFetcher;
import io.micronaut.security.token.config.TokenConfiguration;
Expand All @@ -29,8 +28,6 @@
import org.slf4j.LoggerFactory;

import javax.inject.Singleton;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Optional;

/**
Expand All @@ -43,7 +40,6 @@
public class BasicAuthAuthenticationFetcher implements AuthenticationFetcher {

private static final Logger LOG = LoggerFactory.getLogger(BasicAuthAuthenticationFetcher.class);
private static final String PREFIX = HttpHeaderValues.AUTHORIZATION_PREFIX_BASIC + " ";
private final Authenticator authenticator;
private final TokenConfiguration configuration;

Expand Down Expand Up @@ -86,35 +82,9 @@ public Publisher<Authentication> fetchAuthentication(HttpRequest<?> request) {
* @param authorization Authorization HTTP Header value
* @return Extracted Credentials as a {@link UsernamePasswordCredentials} or an empty optional if not possible.
*/
@Deprecated
@NonNull
public Optional<UsernamePasswordCredentials> parseCredentials(@NonNull String authorization) {
return Optional.of(authorization)
.filter(s -> s.startsWith(PREFIX))
.map(s -> s.substring(PREFIX.length()))
.flatMap(this::decode);
}

private Optional<UsernamePasswordCredentials> decode(String credentials) {
byte[] decoded;
try {
decoded = Base64.getDecoder().decode(credentials);
} catch (IllegalArgumentException e) {
if (LOG.isDebugEnabled()) {
LOG.debug("Error while trying to Base 64 decode: {}", credentials);
}
return Optional.empty();
}

String token = new String(decoded, StandardCharsets.UTF_8);

String[] parts = token.split(":");
if (parts.length < 2) {
if (LOG.isDebugEnabled()) {
LOG.debug("Bad format of the basic auth header - Delimiter : not found");
}
return Optional.empty();
}

return Optional.of(new UsernamePasswordCredentials(parts[0], parts[1]));
return BasicAuthUtils.parseCredentials(authorization);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
/*
* Copyright 2017-2020 original 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 io.micronaut.security.authentication;

import edu.umd.cs.findbugs.annotations.NonNull;
import io.micronaut.http.HttpHeaderValues;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Optional;

public class BasicAuthUtils {
private static final Logger LOG = LoggerFactory.getLogger(BasicAuthUtils.class);
private static final String PREFIX = HttpHeaderValues.AUTHORIZATION_PREFIX_BASIC + " ";

/**
*
* @param authorization Authorization HTTP Header value
* @return Extracted Credentials as a {@link UsernamePasswordCredentials} or an empty optional if not possible.
*/
@NonNull
public static Optional<UsernamePasswordCredentials> parseCredentials(@NonNull String authorization) {
return Optional.of(authorization)
.filter(s -> s.startsWith(PREFIX))
.map(s -> s.substring(PREFIX.length()))
.flatMap(BasicAuthUtils::decode);
}

private static Optional<UsernamePasswordCredentials> decode(String credentials) {
byte[] decoded;
try {
decoded = Base64.getDecoder().decode(credentials);
} catch (IllegalArgumentException e) {
if (LOG.isDebugEnabled()) {
LOG.debug("Error while trying to Base 64 decode: {}", credentials);
}
return Optional.empty();
}

String token = new String(decoded, StandardCharsets.UTF_8);

String[] parts = token.split(":");
if (parts.length < 2) {
if (LOG.isDebugEnabled()) {
LOG.debug("Bad format of the basic auth header - Delimiter : not found");
}
return Optional.empty();
}

return Optional.of(new UsernamePasswordCredentials(parts[0], parts[1]));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package io.micronaut.security.authentication

import spock.lang.Specification
import spock.lang.Unroll

class BasicAuthUtilsSpec extends Specification {

void "BasicAuthAuthenticationFetcher::parseCredentials parse creds from Basic Auth Http header value"() {
when:
Optional<UsernamePasswordCredentials> creds = BasicAuthUtils.parseCredentials('Basic dXNlcjpwYXNzd29yZA==')

then:
creds.isPresent()
creds.get().identity == 'user'
creds.get().secret == 'password'
}

@Unroll("BasicAuthUtils::parseCredentials returns an empty optional if HTTP Authorization header value ( #value ) does not start with `Basic `")
void "For HTTP Header Authroziation value which do not start with Basic BasicAuthAuthenticationFetcher::parseCredentials returns an empty optional"(String value) {
when:
Optional<UsernamePasswordCredentials> creds = BasicAuthUtils.parseCredentials(value)

then:
noExceptionThrown()
!creds.isPresent()

where:
value << ['', '123', 'Basic', 'Basic ', 'Foooo dXNlcjpwYXNzd29yZA==']
}
}

0 comments on commit 5bf1762

Please sign in to comment.