diff --git a/src/main/java/org/takes/facets/auth/PsBasic.java b/src/main/java/org/takes/facets/auth/PsBasic.java index 138a22019..84128bb46 100644 --- a/src/main/java/org/takes/facets/auth/PsBasic.java +++ b/src/main/java/org/takes/facets/auth/PsBasic.java @@ -30,6 +30,7 @@ import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.HashMap; +import java.util.Iterator; import java.util.Map; import java.util.logging.Level; import java.util.regex.Pattern; @@ -83,13 +84,24 @@ public PsBasic(final String rlm, final PsBasic.Entry basic) { @Override public Opt enter(final Request request) throws IOException { + final Iterator headers = new RqHeaders.Smart( + new RqHeaders.Base(request) + ).header("authorization").iterator(); + if (!headers.hasNext()) { + throw new RsForward( + new RsWithHeader( + String.format( + "WWW-Authenticate: Basic ream=\"%s\" ", + this.realm + ) + ), + HttpURLConnection.HTTP_UNAUTHORIZED, + new RqHref.Base(request).href() + ); + } final String decoded = new String( DatatypeConverter.parseBase64Binary( - PsBasic.AUTH.split( - new RqHeaders.Smart( - new RqHeaders.Base(request) - ).single("authorization") - )[1] + PsBasic.AUTH.split(headers.next())[1] ), StandardCharsets.UTF_8 ).trim(); final String user = decoded.split(":")[0]; diff --git a/src/test/java/org/takes/facets/auth/PsBasicTest.java b/src/test/java/org/takes/facets/auth/PsBasicTest.java index 4e35ac00d..b1ece8498 100644 --- a/src/test/java/org/takes/facets/auth/PsBasicTest.java +++ b/src/test/java/org/takes/facets/auth/PsBasicTest.java @@ -32,6 +32,7 @@ import org.takes.HttpException; import org.takes.Take; import org.takes.facets.forward.RsForward; +import org.takes.facets.forward.TkForward; import org.takes.misc.Opt; import org.takes.rq.RqFake; import org.takes.rq.RqMethod; @@ -222,20 +223,22 @@ public void authenticatesUser() throws Exception { */ @Test public void requestAuthentication() throws Exception { - final Take take = new TkAuth( - new TkSecure( - new TkText("secured area...") - ), - new PsBasic( - "the realm 5", - new PsBasic.Default("bob pwd88 urn:users:bob") + final Take take = new TkForward( + new TkAuth( + new TkSecure( + new TkText("secured area...") + ), + new PsBasic( + "the realm 5", + new PsBasic.Default("bob pwd88 urn:users:bob") + ) ) ); MatcherAssert.assertThat( new RsPrint( take.act(new RqFake()) ).print(), - Matchers.containsString("HTTP/1.1 401 Unauthorized") + Matchers.containsString("HTTP/1.1 401 Unauthorized\r\n") ); }