How to put browser's native login prompt in JSP and retrieve the username & password

StackOverflow https://stackoverflow.com/questions/17941682

  •  04-06-2022
  •  | 
  •  

Domanda

I want the web browser to ask for username and password using it's default login prompt like this.

Firefox Login Prompt
I read about how to implement it here but it is for ASP. I want it done in JSP or servlet and I also want to know that how will I receive those username and password in my servlet

È stato utile?

Soluzione

You need to use BASIC authentication. You need to use JAAS for the same. This tutorial provides FORM based authentication. but as you want BASIC authentication, you need to

<login-config>
     <auth-method>BASIC</auth-method>
</login-config>

You can retrieve the user principal as follows

request.getUserPrincipal().getName().toString(); 

Altri suggerimenti

You have to use Basic authentication for this you can refer following link, it gives basic authentication using servlet.

<login-config>
        <auth-method>BASIC</auth-method>
</login-config>

It configures basic authentication in web.xml Also, you need to add

<?xml version='1.0' encoding='utf-8'?>
<tomcat-users>
  <role rolename="tomcat"/>
  <user username="tomcat" password="tomcat" roles="tomcat"/>
  <user username="yourname" password="yourpassword" roles="tomcat"/>
  <user username="test" password="test"/>
</tomcat-users>

in tomcat-users.xml

Example link : http://www.avajava.com/tutorials/lessons/how-do-i-use-basic-authentication-with-tomcat.html?page=1

Hope it helpful to you.

public void  doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    request.setCharacterEncoding("windows-31j");
    response.setContentType("text/html; charset=windows-31j");
    String auth = request.getHeader("Authorization");
    if (auth == null)
    {
      response.setStatus(401); 
      response.setHeader("Cache-Control","no-store"); 
      response.setDateHeader("Expires",0); 
      response.setHeader("WWW-authenticate","Basic Realm=\"AuthDemo Server\""); 

    } else {
        response.getWriter().print("Authorization :" + request.getHeader("Authorization"));
    }

            }
      }
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top