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

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

  •  04-06-2022
  •  | 
  •  

문제

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

도움이 되었습니까?

해결책

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(); 

다른 팁

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"));
    }

            }
      }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top