private static String[] getCredentials(String authorizationHeader) {
String basicAuthEncoded = authorizationHeader.substring(6);
- String basicAuthDecoded = new String(BASE64_DECODER.decode(basicAuthEncoded.getBytes(Charsets.UTF_8)), Charsets.UTF_8);
+ String basicAuthDecoded = getDecodedBasicAuth(basicAuthEncoded);
int semiColonPos = basicAuthDecoded.indexOf(':');
if (semiColonPos <= 0) {
return new String[] {login, password};
}
+ private static String getDecodedBasicAuth(String basicAuthEncoded) {
+ try {
+ return new String(BASE64_DECODER.decode(basicAuthEncoded.getBytes(Charsets.UTF_8)), Charsets.UTF_8);
+ } catch (Exception e) {
+ throw new UnauthorizedException("Invalid basic header");
+ }
+ }
+
private UserDto authenticate(String login, String password, HttpServletRequest request) {
if (isEmpty(password)) {
return authenticateFromUserToken(login);
package org.sonar.server.authentication;
-import static com.google.common.base.Charsets.UTF_8;
-import static org.assertj.core.api.Java6Assertions.assertThat;
-import static org.junit.rules.ExpectedException.none;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.verifyZeroInteractions;
-import static org.mockito.Mockito.when;
-
import java.util.Base64;
import java.util.Optional;
import javax.servlet.http.HttpServletRequest;
import org.sonar.server.exceptions.UnauthorizedException;
import org.sonar.server.usertoken.UserTokenAuthenticator;
+import static com.google.common.base.Charsets.UTF_8;
+import static org.assertj.core.api.Java6Assertions.assertThat;
+import static org.junit.rules.ExpectedException.none;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyZeroInteractions;
+import static org.mockito.Mockito.when;
+
public class BasicAuthenticatorTest {
private static final Base64.Encoder BASE64_ENCODER = Base64.getEncoder();
underTest.authenticate(request);
}
+ @Test
+ public void fail_to_authenticate_when_invalid_header() throws Exception {
+ when(request.getHeader("Authorization")).thenReturn("Basic InvĂ lid");
+
+ expectedException.expect(UnauthorizedException.class);
+ expectedException.expectMessage("Invalid basic header");
+ underTest.authenticate(request);
+ }
+
@Test
public void authenticate_from_user_token() throws Exception {
insertUser(UserTesting.newUserDto().setLogin(LOGIN));