Basic Authentication Example in Servlets

In Basic authentication, if you try to send a request, a popup window appears and you enter a particular username/password, which gets sent to Tomcat. Tomcat checks to see that the sent username and password match a user entry in tomcat-users.xml, and it makes sure that the user's tomcat-users.xml role (or roles) match the role (or roles) that have access to your web application resource, which is specified in your web.xml file.

step 1:
Inside tomcat-users.xml add the below code



step 2:
create dynamic web project and in web.xml add the below code:
Inside web.xml


authwebapplication



Controller
Controller
com.vidyayug.Controller


Controller
/Controller



Wildcard means whole app requires authentication
/*
GET
POST


manager-gui


NONE

BASIC


Step 3: Create a Servlet like below:

package com.mypractice;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.tomcat.util.buf.Base64;
public class Controller extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();

Enumeration headerNames = request.getHeaderNames();

while (headerNames.hasMoreElements()) {
String headerName = (String) headerNames.nextElement();
out.print("
Header Name: ---------->" + headerName);
String headerValue = request.getHeader(headerName);
out.print("
, Header Value: " + headerValue);
out.println("
");
}
out.println("
");
String authHeader = request.getHeader("authorization");
String encodedValue = authHeader.split(" ")[1];
out.println("Base64-encoded Authorization Value: " + encodedValue);
String decodedValue = Base64.base64Decode(encodedValue);
out.println("

Base64-decoded Authorization Value: " + decodedValue);
out.println("
");
}
}

Search This Blog

All the rights are reserved to this blog is belongs to me only.. Powered by Blogger.