1. 程式人生 > >自動登入中的Base64簡單加密和解密

自動登入中的Base64簡單加密和解密

自動登入的四個檔案如下:

簡單的自動登入,自動登入的有效時間時間可以通過LoginServlet檔案中的cookie.setMaxAge(60);進行設定,時間單位為秒。
登入的過濾器,LoginFilter.java:
其中包含對使用者資訊的Base64解密

package com.java12.cookie.app;

import java.io.IOException;
import java.util.Base64;
import java.util.Base64.Decoder;

import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import
javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.WebFilter; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import
javax.servlet.http.HttpServletResponse; @WebFilter(urlPatterns={"/index.jsp"}) public class LoginFilter implements Filter { public LoginFilter() { } public void destroy() { } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { System.out.println(1254
); HttpServletRequest httpServletRequest = (HttpServletRequest)request; HttpServletResponse httpServletResponse = (HttpServletResponse)response; Cookie[] cookies = httpServletRequest.getCookies(); boolean flag = false; //檢視瀏覽器中是否有cookie if(cookies != null && cookies.length > 0){ //瀏覽器中有cookie 進行迴圈遍歷 查詢一週內登陸的cookie for(Cookie cookie : cookies){ if("loginInfo".equals(cookie.getName())){ //對cookie進行base64解碼 校驗cookie防止被串改 Decoder decoder = Base64.getDecoder(); byte[] decode = decoder.decode(cookie.getValue()); String string = new String(decode); if(string.equals("tom&123456")){ //找到並設定標誌位 flag = true; } } } //根據標誌位進行顧慮請求 特別理解標誌位的使用 if(flag){ chain.doFilter(request, response); }else{ httpServletResponse.sendRedirect(httpServletRequest.getContextPath()+"/login.jsp"); } } //瀏覽器中沒有一個cookie else{ httpServletResponse.sendRedirect(httpServletRequest.getContextPath()+"/login.jsp"); } } public void init(FilterConfig fConfig) throws ServletException { } }

登入校驗處理頁面LoginServlet.java
其中包含對使用者資訊的Base64簡單加密

package com.java12.cookie.app;
import java.io.IOException;
import java.util.Base64;
import java.util.Base64.Encoder;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;    
    public LoginServlet() {
        super();
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String userName = request.getParameter("userName");
        String password = request.getParameter("password");
        String auto = request.getParameter("auto");
        //校驗成功 跳轉到網站首頁
        if("tom".equals(userName)&&"123456".equals(password)){
            if("auto".equals(auto)){
                //經過base64 轉碼處理
                String str = userName+"&"+password;
                Encoder encoder = Base64.getEncoder();
                String encodeToString = encoder.encodeToString(str.getBytes());
                Cookie cookie = new Cookie("loginInfo",encodeToString);
                cookie.setMaxAge(60);
                response.addCookie(cookie);
            }
            request.getRequestDispatcher("/index.jsp").forward(request, response);
        }else{
            request.setAttribute("msg", "使用者名稱或密碼錯誤,請重新登陸");
            request.getRequestDispatcher("/login.jsp").forward(request, response);
        }
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}

成功登入頁面index.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
${info}
    welcome to home page
</body>
</html>

登入頁面login.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    ${msg}
    <form action="login" method="post">
         使用者名稱:<input type="text" name="userName"><br>
         密碼:<input type="password" name="password"><br>
         一週內登陸:<input type="checkbox" name="auto" value="auto">
         <input type="submit" value="登陸 ">
    </form>
</body>
</html>

自動登入的流程圖:

這裡寫圖片描述

此次自動登入的程式碼主要是為了使用cookie實現自動登入,可根據個人需要新增session進行修改。

注意:

登入成功之後,本檔案採用的是request.getRequestDispatcher(“/index.jsp”).forward(request, response);利用轉發的方式,沒有再次進入LoginFilter頁面。而使用response.sendRedirect(“/index.jsp”);重定向時,會進入LoginFilter頁面,由於程式碼的編寫原因,會報錯。
如果想讓轉發的也進入LoginFilter頁面,需要在LoginFilter頁面的@WebFilter(urlPatterns={“/index.jsp”})中加入dispatcherTypes={DispatcherType.FORWARD},對轉發進行授權。當沒有寫的時候預設為dispatcherTypes={DispatcherType.REQUEST}只要請求都攔截。