HTTP基本認證(Basic Authentication)的JAVA樣本__java

來源:互聯網
上載者:User
大家在登入網站的時候,大部分時候是通過一個表單提交登入資訊。
但是有時候瀏覽器會彈出一個登入驗證的對話方塊,如下圖,這就是使用HTTP基本認證。

下面來看看一看這個認證的工作過程:
第一步:  用戶端發送http request 給伺服器,伺服器驗證該使用者是否已經登入驗證過了,如果沒有的話,
伺服器會返回一個401 Unauthozied給用戶端,並且在Response 的 header "WWW-Authenticate" 中添加資訊。
如下圖。

第二步:瀏覽器在接受到401 Unauthozied後,會彈出登入驗證的對話方塊。使用者輸入使用者名稱和密碼後,
瀏覽器用BASE64編碼後,放在Authorization header中發送給伺服器。如下圖:

第三步: 伺服器將Authorization header中的使用者名稱密碼取出,進行驗證, 如果驗證通過,將根據請求,發送資源給用戶端。

下面來看一個JAVA的範例程式碼:

import java.io.IOException;  import java.io.PrintWriter;  import javax.servlet.http.HttpServlet;  import javax.servlet.http.HttpServletRequest;  import javax.servlet.http.HttpServletResponse;  import sun.misc.BASE64Decoder;    public class HTTPAuthServlet extends HttpServlet {            public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {          String sessionAuth = (String) request.getSession().getAttribute("auth");            if (sessionAuth != null) {              System.out.println("this is next step");              nextStep(request, response);            } else {                if(!checkHeaderAuth(request, response)){                  response.setStatus(401);                  response.setHeader("Cache-Control", "no-store");                  response.setDateHeader("Expires", 0);                  response.setHeader("WWW-authenticate", "Basic Realm=\"test\"");              }                       }        }        private boolean checkHeaderAuth(HttpServletRequest request, HttpServletResponse response) throws IOException {            String auth = request.getHeader("Authorization");          System.out.println("auth encoded in base64 is " + getFromBASE64(auth));                    if ((auth != null) && (auth.length() > 6)) {              auth = auth.substring(6, auth.length());                String decodedAuth = getFromBASE64(auth);              System.out.println("auth decoded from base64 is " + decodedAuth);            String user="";                 String password="";                 if(decodedAuth!=null){                     user=decodedAuth.substring(0,decodedAuth.indexOf(":"));                password=decodedAuth.substring(decodedAuth.indexOf(":")+1);                 }                 if(user.equals("unixboy")&&password.equals("123456")){                 //認證成功            request.getSession().setAttribute("auth", decodedAuth);              return true;                   }else{                 //認證失敗             return false;                }               }else{              return false;          }        }        private String getFromBASE64(String s) {          if (s == null)              return null;          BASE64Decoder decoder = new BASE64Decoder();          try {              byte[] b = decoder.decodeBuffer(s);              return new String(b);          } catch (Exception e) {              return null;          }      }        public void nextStep(HttpServletRequest request, HttpServletResponse response) throws IOException {          PrintWriter pw = response.getWriter();          pw.println("<html> next step, authentication is : " + request.getSession().getAttribute("auth") + "<br>");          pw.println("<br></html>");      }        public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {          doGet(request, response);      }    }  
當request第一次到達伺服器時,伺服器沒有認證的資訊,伺服器會返回一個401 Unauthozied給用戶端。

認證之後將認證資訊放在session,以後在session有效期間內就不用再認證了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.