HTTP基本认证(Basic Authentication)

时间:2021-08-27 16:22:52

在浏览网页时候,浏览器会弹出一个登录验证的对话框,如下图,这就是使用HTTP基本认证。
HTTP基本认证(Basic Authentication)

1、 客户端发送http request 给服务器,服务器验证该用户是否已经登录验证过了,如果没有的话,
服务器会返回一个401 Unauthozied给客户端,并且在Response 的 header “WWW-Authenticate” 中添加信息。
如下图。HTTP基本认证(Basic Authentication)

HTTP基本认证(Basic Authentication)

2、:浏览器在接受到401 Unauthozied后,会弹出登录验证的对话框。用户输入用户名和密码后,
浏览器用BASE64编码后,放在Authorization header中发送给服务器。如下图:HTTP基本认证(Basic Authentication)

3、 服务器将Authorization header中的用户名密码取出,进行验证, 如果验证通过,将根据请求,发送资源给客户端。

示例代码:

public class SecurityInterceptor implements HandlerInterceptor {

  private static final String SESSION_KEY = "SESSION_KEY";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        HttpSession session = request.getSession();

        Object SESSION_OBJECT = session.getAttribute(SESSION_KEY);

        if(SESSION_OBJECT != null) { return true; }

        String authorization = request.getHeader("authorization");
        if(StringUtils.isNotEmpty(authorization)) {

            String authorizationString[] = authorization.split(" ");

            if(authorizationString.length == 2) {

                String base64String = authorizationString[1];
                String accountString = new String(Base64.decodeBase64(base64String), Charset.forName("UTF-8"));
                String account[] = accountString.split(":");

                if(account.length == 2) {

                    String password = "test";

                    AccountService accountService = (AccountService) SpringApplicationContext.getBean("AccountService");

                   Account account = accountService.getAccount();



                    if(StringUtils.equals("test", account[0]) && StringUtils.equals(password, account[1])) {

                        session.setAttribute(SESSION_KEY, true);

                        return true;
                    }
                }
            }
        }

        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);//401
        response.setCharacterEncoding("UTF-8");
        response.setHeader("WWW-Authenticate", "Basic realm=\"STOP!\"");
        response.setHeader("Content-Type", "text/html");

        response.getWriter().print("<!DOCTYPE HTML><html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /></head><body align=\"center\"><h3>没有权限,慎入!!!</h3></body></html>");

        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        //DO NOTHING!!!
    }
}

当request第一次到达服务器时,服务器没有认证的信息,服务器会返回一个401 Unauthozied给客户端。
认证之后将认证信息放在session,以后在session有效期内就不用再认证了。