关闭

自定义单点登录(2)

标签: java单点登录自定义单点登录cookiesession
427人阅读 评论(0) 收藏 举报
分类:

惯例:

我是温浩然:

单点登录,分为客户端和服务器端,客户端,主要与用户的浏览器进行交互,操作浏览器,比如,cookie,session等。

服务器端,主要是储存用户的信息,和后台数据库进行交互,获取当前登录的用户信息,对用户的登录进行验证。

关于单点登录,我感觉,验证方式有很多种,

我这里,是对cookie进行操作,当用户登录成功后,会在浏览器新建cookie,储存一定信息,当用户访问受保护的请求时,获取cookie并进行验证,如果验证通过,则该用户已经登录,可以访问受保护的信息。

下面贴在Filter中,进行验证的代码。

1、服务器中,对用户进行验证的代码。

package com.tujia.core.security;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.util.WebUtils;

import com.tujia.common.exception.UnAuthedException;
import com.tujia.tuuser.dao.UserDao;
import com.tujia.tuuser.entity.User;
import com.tujia.tuuser.service.UserService;

@Component
public class SecurityUtil {

	@Resource
    private UserDao userDao;
	
	private String TOURL = "TOURL";

	private static ThreadLocal<User> threadTuser = new ThreadLocal<User>();

	private Map<String,AuthTuUser> map = new HashMap<String,AuthTuUser>();
	
	private Map<String,User> mapUser = new HashMap<String,User>();
	
        //下面这个是对数据进行操作,与数据库进行交互的Java类
	@Autowired
	private UserService userService;

        /*@Autowired
	TokenAuthentication tokenAuthentication;*/
	//tujia.requrl  下面这些都是配置文件
	@Value("${tujia.requrl}")
	private String requrl;
	@Value("${tujia.token}")
	private String tokenKey;
	@Value("${loginURL:\"\"}")
	private String loginURL;

	private int MS_IN_A_DAY = 24 * 3600 * 1000;
	private int SECS_IN_A_MONTH = 24 * 3600 * 30;

	/**
	 * 得到当前登录的用户,用户再业务逻辑的地方
	 * 
	 * @return
	 */
	public static User getCurrentTuser() {
		return threadTuser.get();
	}

	/**
	 * 用在filter的地方,
	 * 
	 * @param request
	 * @throws UnAuthedException 
	 * @return:true:已经登录了。false:没有登录
	 */
	public boolean authenticate(HttpServletRequest request,
			HttpServletResponse response) throws UnAuthedException {
		boolean result;
		// 处理cookie情况
		Cookie cookie = WebUtils.getCookie(request, tokenKey);
		String url = request.getRequestURI();
		
		//if登录cookie is null ,则添加cookie url.
		if (cookie == null){
			//这是被拦截后添加的cookie
			Cookie cookieurl = new Cookie(requrl, url);
			cookieurl.setPath("/");
			cookieurl.setMaxAge(-1);
			response.addCookie(cookieurl);
			return false;
			}
		
		String value = cookie.getValue();
		AuthTuUser au = (AuthTuUser) map.get(value);
		if (au == null ){
			Cookie cookieurl = new Cookie(requrl, url);
			cookieurl.setPath("/");
			cookieurl.setMaxAge(-1);
			response.addCookie(cookieurl);
			return false;
			}
		request.getSession().setAttribute("userLogin", mapUser.get(value));
		result = verifyTuserId(au.getId()); 
		if (!result) {
			logout(request, response);
		}
		
		return result;
	}


	public User getLoinTuser(HttpServletRequest request) throws UnAuthedException {
		// 处理cookie情况
		Cookie cookie = WebUtils.getCookie(request, tokenKey);
		if (cookie == null)
			return null;
		String value = cookie.getValue();
		AuthTuUser au = (AuthTuUser) map.get(value);
		if (au == null)// || au.isExpire()
			return null;

		 User user = userService.get(au.getId());
		return user;
	}

	private String generateValue() {
		return UUID.randomUUID().toString();
	}

	public void inputSuccess(HttpServletRequest request,HttpServletResponse response, long userId,
			boolean saved) throws UnAuthedException {
		if (verifyTuserId(userId)) {
			addCookieAndCache(request,response, userId, saved);
		}else{
			throw new UnAuthedException("该用户不存在,请重新输入!");
		}
	}

	private void addCookieAndCache(HttpServletRequest request,HttpServletResponse response, long userId,
			boolean saved) {
		
		AuthTuUser au = new AuthTuUser(userId);
		
		User user = userDao.get(userId);
		
		String tokenValue = generateValue();
		Cookie cookie = new Cookie(tokenKey, tokenValue);
		cookie.setPath("/");
		if (saved) {
			cookie.setMaxAge(SECS_IN_A_MONTH);
			au.setSaved(true);
		} else {
			cookie.setMaxAge(-1);
			au.setExpireDate(new Date(System.currentTimeMillis() + MS_IN_A_DAY));
		}
		request.setAttribute("token", tokenValue);
		response.addCookie(cookie);
		
		map.put(tokenValue, au);
		mapUser.put(tokenValue, user);
		request.getSession().setAttribute("userLogin", user);
	}

	public boolean verifyTuserId(long userId) throws UnAuthedException {
		boolean result;
		 User user = userService.get(userId);
		if (user.isDeleted()) {// 员工被停用了
			result = false;
		} else {
			threadTuser.set(user);
			result = true;
		}
		return result;
	}

	/**
	 * 
	 * @param req
	 * @return
	 */
	public void logout(HttpServletRequest request, HttpServletResponse response) {

		Cookie cookie = WebUtils.getCookie(request, tokenKey);
		if (cookie == null)
			return;

		String value = cookie.getValue();
		AuthTuUser au = (AuthTuUser) map.get(value);
		if (au == null) {
			delteCookie(response, tokenKey);
			delteCookie(response, requrl);
			return;
		}

		delteCookie(response, tokenKey);
		map.remove(value);
		return;

	}

	private void delteCookie(HttpServletResponse response, String cookieName) {
		Cookie cookie = new Cookie(cookieName, "");
		cookie.setPath("/");
		cookie.setMaxAge(0);
		response.addCookie(cookie);
	}

	// 线程结束的时候调用。
	public static void clearOnThreadOver() {
		threadTuser.remove();
	}

	public void setTOURL(HttpServletResponse response,
			HttpServletRequest request) {
		StringBuffer u = request.getRequestURL();
		if (request.getQueryString() != null) {
			u.append('?');
			u.append(request.getQueryString());
		}
		Cookie cookie = new Cookie(TOURL, u.toString());
		cookie.setPath("/");
		cookie.setMaxAge(-1);
		response.addCookie(cookie);
	}

	public String getTOURL(HttpServletRequest request,
			HttpServletResponse response) {
		Cookie cookie = WebUtils.getCookie(request, TOURL);
		if (cookie == null)
			return "";
		delteCookie(response, TOURL);
		return cookie.getValue();
	}

	public String getLoginURL() {
		return loginURL;
	}

	public String getReqURL(HttpServletRequest request,HttpServletResponse response){
		
		Cookie cookie = WebUtils.getCookie(request, requrl);
		
		String value = cookie.getValue();	
		return value;
	}

	public void setLoginURL(String loginURL) {
		this.loginURL = loginURL;
	}
	
	public void requrl(HttpServletRequest request,HttpServletResponse response) {
		Cookie cookie = WebUtils.getCookie(request, requrl);
		if(cookie == null){
			Cookie cookieurl = new Cookie(requrl, "/tu-login/user/index");
			cookieurl.setPath("/");
			cookieurl.setMaxAge(-1);
			response.addCookie(cookieurl);
		}
	}
	
	public boolean getAuthTuUser(String token){
		
		AuthTuUser au = (AuthTuUser) map.get(token);
		
		if (au == null ){
			return false;
		}else{
			User user = mapUser.get(token);
			
			return true;
		}
		
	}
}


贴的很多,但是如果看得仔细,会发现其中我增加了两个cookie,一个是token,就是保存在浏览器中的登录信息。

另一个cookie是requrl,这个是,当用户访问受保护的请求,然后登录后,能自动调整显示的页面。

AuthTuUser这个是储存用户登录信息的javaBean,当用户判断是否登录时,就用map来判断。

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:364997次
    • 积分:5059
    • 等级:
    • 排名:第6292名
    • 原创:158篇
    • 转载:104篇
    • 译文:1篇
    • 评论:38条
    最新评论