首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> JSP 程式設計 >> 關於JSP

關於 JSP BASIC 認證的資料與實踐總結

     編輯:關於JSP

BASIC 認證:瀏覽器彈出原生登入對話框(如 Tomcat Manager)。

簡單觸發

<%
  response.addHeader("WWW-Authenticate", "Basic realm=\"Please Login\"");
  response.sendError(401, "Unauthorized");
%>

完整驗證邏輯

String auth = request.getHeader("Authorization");
String authUser = "", authPass = "";
if (auth != null && auth.toUpperCase().startsWith("BASIC")) {
  String encoded = auth.substring(6);
  sun.misc.BASE64Decoder dec = new sun.misc.BASE64Decoder();
  String decoded = new String(dec.decodeBuffer(encoded));
  String[] up = decoded.split(":", 2);
  authUser = up[0]; authPass = up[1];
}
if (!"admin".equals(authUser) || !"password".equals(authPass)) {
  response.setStatus(401);
  response.setHeader("WWW-Authenticate", "Basic realm=\"My Realm\"");
} else {
  // 驗證通過
}

解碼 Base64 後以冒號分割得帳號密碼,再進行比對。注意:sun.misc.BASE64Decoder 為內部 API,生產環境建議用 Apache Commons Codec。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved