1
+ package de .ioexception .www .server .impl ;
2
+
3
+ import java .net .Socket ;
4
+ import java .util .HashMap ;
5
+ import java .util .Map ;
6
+
7
+ import util .Base64 ;
8
+ import de .ioexception .www .http .HttpRequest ;
9
+ import de .ioexception .www .http .HttpResponse ;
10
+ import de .ioexception .www .http .HttpStatusCode ;
11
+ import de .ioexception .www .http .HttpVersion ;
12
+ import de .ioexception .www .http .impl .BasicHttpResponse ;
13
+
14
+ /**
15
+ * @author Benjamin Erb
16
+ *
17
+ */
18
+ public class BasicAuthHttpWorker extends BasicHttpWorker
19
+ {
20
+ private static final Map <String , String > authentications ;
21
+ private static final String realm = "Protected Area" ;
22
+
23
+ static
24
+ {
25
+ authentications = new HashMap <String , String >();
26
+ authentications .put ("test" , "secret" );
27
+ authentications .put ("user" , "1234" );
28
+ };
29
+
30
+ public BasicAuthHttpWorker (Socket socket , BasicHttpServer server )
31
+ {
32
+ super (socket , server );
33
+ }
34
+
35
+ @ Override
36
+ protected HttpResponse handleRequest (HttpRequest request )
37
+ {
38
+ if (request .getHeaders ().containsKey ("Authorization" ))
39
+ {
40
+ String authValue = request .getHeaders ().get ("Authorization" );
41
+ String [] authValues = authValue .split (" " , 2 );
42
+ String type = authValues [0 ];
43
+ String values = authValues [1 ];
44
+ if (type .equalsIgnoreCase ("Basic" ))
45
+ {
46
+ String auth = new String (Base64 .decode (values ));
47
+ String [] authentication = auth .split (":" , 2 );
48
+ if (authentications .containsKey (authentication [0 ]) && authentications .get (authentication [0 ]).equals (authentication [1 ]))
49
+ {
50
+ return super .handleRequest (request );
51
+ }
52
+ }
53
+ }
54
+ BasicHttpResponse response = new BasicHttpResponse ();
55
+ response .setStatusCode (HttpStatusCode .UNAUTHORIZED );
56
+ Map <String , String > headers = new HashMap <String , String >();
57
+ headers .put ("WWW-Authenticate" , "Basic realm=\" " + realm + "\" " );
58
+ headers .put ("Content-Length" , "0" );
59
+ response .setVersion (HttpVersion .VERSION_1_1 );
60
+ response .setHeaders (headers );
61
+ response .setEntity (null );
62
+ return response ;
63
+ }
64
+ }
0 commit comments