spring security 3 实现异步登录
1》 实现过滤器
/**
?*
?*/
package ******************;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.context.HttpSessionContextIntegrationFilter;
import org.springframework.web.filter.OncePerRequestFilter;
import flexjson.JSONSerializer;
/**
?* function:
?*
?* @author LJ
?*
?*/
public class LoginAjaxFilter extends OncePerRequestFilter {
??? private static final Logger log = LoggerFactory
??? ??? ??? .getLogger(LoginAjaxFilter.class);
??? @Override
??? protected void doFilterInternal(HttpServletRequest request,
??? ??? ??? HttpServletResponse response, FilterChain filterChain)
??? ??? ??? throws ServletException, IOException {
??? ??? // 检查提交的变量中是否有ajax请求的变量,如果没有,则不是ajax的登录请求,则走默认的请求。
??? ??? if (!isAjaxRequest(request)) {
??? ??? ??? filterChain.doFilter(request, response);
??? ??? ??? return;
??? ??? }
??? ??? log.debug("AjaxSecurityFilter: Processing an AJAX call : "
??? ??? ??? ??? + request.getRequestURL());
??? ??? RedirectResponseWrapper redirectResponseWrapper = new RedirectResponseWrapper(
??? ??? ??? ??? response);
??? ??? filterChain.doFilter(request, redirectResponseWrapper);
??? ??? Map<String, String> map = new HashMap<String, String>();
??? ??? if (redirectResponseWrapper.getRedirect() != null) {
??? ??? ??? String redirectURL = redirectResponseWrapper.getRedirect();
??? ??? ??? HttpSession httpSession = request.getSession();
??? ??? ??? if (redirectURL.indexOf("login") != -1) {
??? ??? ??? ??? // populate your reply in this case the json object
??? ??? ??? ??? // with what ever information needed to pop up your login window
??? ??? ??? ??? if (redirectURL.indexOf("login_error=1") != -1) {
??? ??? ??? ??? ??? // 登录失败
??? ??? ??? ??? ??? map.put("success", "false");
??? ??? ??? ??? }
??? ??? ??? }
??? ??? ??? // / your auth is successful the call is successful
??? ??? ??? else {
??? ??? ??? ??? // you can return the user name and password in the reply so it
??? ??? ??? ??? // can be displayed for example in you app
??? ??? ??? ??? SecurityContext ctx = (SecurityContext) httpSession
??? ??? ??? ??? ??? ??? .getAttribute(HttpSessionContextIntegrationFilter.SPRING_SECURITY_CONTEXT_KEY);
??? ??? ??? ??? if (ctx != null) {
??? ??? ??? ??? ??? Authentication auth = ctx.getAuthentication();
??? ??? ??? ??? ??? UserDetails user = (UserDetails) auth.getPrincipal();
??? ??? ??? ??? ??? if (user != null) {
??? ??? ??? ??? ??? ??? map.put("username", user.getUsername());
??? ??? ??? ??? ??? ??? map.put("success", "true");
??? ??? ??? ??? ??? } else {
??? ??? ??? ??? ??? ??? // 登录失败
??? ??? ??? ??? ??? ??? map.put("success", "false");
??? ??? ??? ??? ??? ??? map.put("errorMsg", "error");
??? ??? ??? ??? ??? }
??? ??? ??? ??? } else {
??? ??? ??? ??? ??? map.put("success", "false");
??? ??? ??? ??? }
??? ??? ??? }
??? ??? ??? try {
??? ??? ??? ??? String outString = new JSONSerializer().serialize(map);
??? ??? ??? ??? log.debug("jsonString : "+outString);
??? ??? ??? ??? response.getWriter().write(outString);
??? ??? ??? } catch (Exception e) {
??? ??? ??? ??? log.error("{}",e.getMessage());
??? ??? ??? }
??? ??? }
??? }
??? /**
??? ?* @param request
??? ?*??????????? the request object
??? ?* @return true if this request is an ajax request. This is determined by a
??? ?*???????? configured name/value pair that is applied to the request header
??? ?*/
??? protected boolean isAjaxRequest(HttpServletRequest request) {
??? ??? // test with our ajax request pairs
??? ??? String ajax = request.getParameter("ajax");
??? ??? if ("".equals(ajax) || ajax == null) {
??? ??? ??? return false;
??? ??? }
??? ??? return true;
??? }
???
??? protected class JsonFlag{
??? ???
??? ??? String success;
??? ??? public String getSuccess() {
??? ??? ??? return success;
??? ??? }
??? ??? public void setSuccess(String success) {
??? ??? ??? this.success = success;
??? ??? }
??? ??? public String getUsername() {
??? ??? ??? return username;
??? ??? }
??? ??? public void setUsername(String username) {
??? ??? ??? this.username = username;
??? ??? }
??? ??? String username;
??? }
}
2》 web.xml
<!-- 异步登录过滤器 filter -->
??? <filter>
??? ??? <filter-name>loginAjaxFilter</filter-name>
??? ??? <filter-class>com.book511.app.web.login.LoginAjaxFilter</filter-class>
??? </filter>
?
<!-- 乱码处理 放置第一位filter-mapping -->
??? <filter-mapping>
??? ??? <filter-name>CharacterEncodingFilter</filter-name>
??? ??? <url-pattern>/*</url-pattern>
??? </filter-mapping>
???
??? <filter-mapping>
??? ??? <filter-name>Spring OpenEntityManagerInViewFilter</filter-name>
??? ??? <url-pattern>/*</url-pattern>
??? </filter-mapping>
???
??? <!-- 异步登录过滤器 map -->
??? <filter-mapping>
??? ??? <filter-name>loginAjaxFilter</filter-name>
??? ??? <url-pattern>/j_spring_security_check</url-pattern>
??? </filter-mapping>
??? <filter-mapping>
??? ??? <filter-name>springSecurityFilterChain</filter-name>
??? ??? <url-pattern>/*</url-pattern>
??? </filter-mapping>
?
3 》 ajaxLogin.js
//弹出窗口
function openLoginDiv(){
??? var htl = "<div id='loginFormDiv'><span class='span_error' id='login_error'></span><a href='javascript:void(0);' onclick='closeDiv();'>关闭窗口</a><form action='##' method='post'><table>"
??? ??? + "<tr><td colspan='2'><span style='color:#FF0000;' id='login_error'></span></td></tr>"
??? ??? + "<tr><td class='td_name'>用户名:</td><td class='td_text'><input type='text' name='j_username' id='j_username' /></td></tr>"
??? ??? + "<tr><td class='td_name'>密码:</td><td class='td_text'><input type='password' name='j_password' id='j_password' /></td></tr>"
??? ??? + "<tr><td colspan='2' class='td_but'><input type='button' id='login_button' onclick='doLogin();' value='登录' /></td></tr>"
??? ??? + "</table></form></div><div id='bg' class='bg' style='display: none;'></div>"+
??? ??? "<iframe id='popIframe' class='popIframe' frameborder='0'></iframe>";
if (!$(".loginDiv").hasClass(
??? ??? "loginDiv")) {
??? //alert(htl);
??? // 动态写一个div弹出层
??? $("<div>", {
??? ??? "class" : "loginDiv",
??? ??? "id":"loginDiv"
??? }).append(htl).appendTo("body");
}
document.getElementById('popIframe').style.display = 'block';
document.getElementById('bg').style.display = 'block';
}
// 关闭窗口
function closeDiv(){
??? $("#loginDiv").remove();
??? document.getElementById('bg').style.display='none';
??? document.getElementById('popIframe').style.display='none';
??? window.location.reload(true);
}
//登录操作
function doLogin(){
??? var j_username = $("#j_username").val();
??? var j_password = $("#j_password").val();
??? var redirectURL = location.href;
??? $.ajax({
??? ??? ??? type : "POST",
??? ??? ??? url : "/app/j_spring_security_check",
??? ??? ??? data : "j_username="
??? ??? ??? ??? ??? + j_username
??? ??? ??? ??? ??? + "&j_password="
??? ??? ??? ??? ??? + j_password
??? ??? ??? ??? ??? + "&ajax=ajax"+ "&redirectURL="+redirectURL,
??? ??? ??? success : function(msg) {
??? ??? ??? ??? eval("var jsonObj="+ msg);
??? ??? ??? ??? if (jsonObj.success == "true") {
??? ??? ??? ??? ??? // 如果登录成功,则跳转到。
??? ??? ??? ??? ??? alert("登录成功");
??? ??? ??? ??? ???
??? ??? ??? ??? ??? window.location.reload(true);
??? ??? ??? ??? ??? //closeDiv();
??? ??? ??? ??? ??? //alert(111);
??? ??? ??? ??? } else if (jsonObj.success = "false") {
??? ??? ??? ??? ??? // 写入登录失败信息
??? ??? ??? ??? ??? var errors = "对不起,用户名或密码不正确!";
??? ??? ??? ??? ??? $("#login_error").html(errors);
??? ??? ??? ??? }
??? ??? ??? }
??? ??? });
}
?
4 》
?