Skip to content

Instantly share code, notes, and snippets.

@lakemove
Last active August 29, 2015 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lakemove/8b900dd3d216b058be5c to your computer and use it in GitHub Desktop.
Save lakemove/8b900dd3d216b058be5c to your computer and use it in GitHub Desktop.
Form based authentication Filter, with in Servlet Container
package com.surdoc.enterprisecloud.web;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
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.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* features :
* <ul>
* <li> redirect to previous page after successfully login
* <li> failed login indication (?fail)
* <li> response 401 for unauthenticated access
* <li> response with html meta to redirect to login page after 401 happens
* </ul>
* @author liulijie
*
*/
public class DeadSimpleAuthFilter implements Filter {
private String loginurl;//POST
private String loginpage;//Form
public void init(FilterConfig filterConfig) throws ServletException {
loginurl = filterConfig.getServletContext().getContextPath() + "/login";
loginpage = filterConfig.getServletContext().getContextPath() + "/login.html";
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
HttpSession session = req.getSession();
//ya! i recognise you , pass !
if (session.getAttribute("user") != null) {
chain.doFilter(request, response);
return;
}
//mm.. not yet a user
String method = req.getMethod(), path = req.getRequestURI();
if(path.endsWith(".html") || path.endsWith(".css") || path.endsWith(".js")) {
chain.doFilter(request, response);
return;
}
if ("POST".equalsIgnoreCase(method) && loginurl.equals(path)) {
//login
String username = req.getParameter("username");
String password = req.getParameter("password");
String next = req.getParameter("next");
if ("admin".equals(username) && "admin".equals(password)) {
session.setAttribute("user", "admin");
resp.sendRedirect(next == null ? "/" : URLDecoder.decode(next, "UTF-8"));
return;
} else {
//sadly, you failed to identify yourself
resp.sendRedirect(loginpage + (next == null ? "?fail" : String.format("?fail&next=%s", next)));
return;
}
}
// dude, you are now allowed here !
resp.setStatus(401);//Unauthorized
// resp.addHeader("WWW-Authenticate", "Basic");//doesn't support form auth
// and it is not possible send both 401 unauthorized and a Location redirect, browser will ignore later one
// see http://stackoverflow.com/questions/8775593/is-it-possible-to-send-a-401-unauthorized-and-redirect-with-a-location
String loc = req.getRequestURL().toString().replace(req.getRequestURI(), "") + loginpage;
if("GET".equalsIgnoreCase(method)) {
loc += "?next=" + URLEncoder.encode(req.getRequestURL().toString(), "UTF-8");
}
resp.getWriter().write(String.format("<html><head><meta http-equiv='refresh' content='0;%s'</head></html>", loc));
}
public void destroy() {
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>云盘后台 登录</title>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="renderer" content="webkit">
<style>
.login-panel{
width: 300px;
margin: 20% auto;
}
.login-panel label {
width: 50px;
display: inline-block;
margin-top: 5px;
}
</style>
</head>
<body>
<div class="login-panel">
<form action="login" method="POST">
<label for="id_username">用户名</label> <input type="text" name="username" id="id_username"/>
<br/>
<label for="id_password">密码</label> <input type="password" name="password" id="id_password"/>
<br/><br/>
<input type="hidden" name="next" id="id_next"/>
<input type="submit" value="登录"/>
</form>
</div>
<script type="text/javascript">
var results = new RegExp('[\\?&]next=([^&#]*)').exec(window.location.href);
if (results && results[1]) {
document.getElementById("id_next").value = results[1];
}
</script>
</body>
</html>
<filter>
<filter-name>authFilter</filter-name>
<filter-class>com.surdoc.enterprisecloud.web.DeadSimpleAuthFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>authFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment