I want to authenticate a socket connection in the Web browser by using the WWW-Authenticate: Basic header but no prompt for username and password comes up. How do go about it?
public static void responseView(Socket socket) throws IOException {
responseHeaders(200);
DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
for(String header : headers) {
outputStream.writeBytes(header + "\r\n");
}
outputStream.writeBytes("\r\n");
outputStream.writeBytes("<!DOCTYPE html><html><head><title>Java Web Server</title></head><body></body></html>");
outputStream.writeBytes("\r\n");
outputStream.flush();
}
public static void responseHeaders(int statusCode) {
SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z");
headers.add("HTTP/1.0 " + Integer.toString(statusCode) + " " + Config.STATUS_CODES.get(statusCode));
headers.add("Content-Type: text/html");
headers.add("Date: " + formatter.format(new Date(System.currentTimeMillis())));
headers.add("Server: Simple Java Web Server");
headers.add("WWW-Authenticate: Basic");
}
Basic access authentication does not authenticate a socket connection, but a HTTP request. There can be multiple HTTP requests inside a single underlying socket connection, with different or with no authentication. And requesting authentication and sending the authenticated request can be done in different connections.
The status code when requesting authentication must be 401, not 200
The
WWW-Authenticateheader must contain therealmattribute to show the user what the authentication is for.For a short overview about the topic see Wikipedia: Basic access authentication: Server side. The ultimate reference is the standard though.