sso单点登录与Jsonp

单点登录与Jsonp

SSO英文全称Single Sign On,单点登录。SSO是在多个应用系统中,用户只需要登录一次就可以访问所有相互信任的应用系统。它包括可以将这次主要的登录映射到其他应用中用于同一个用户的登录的机制。它是目前比较流行的企业业务整合的解决方案之一。 例如天猫和淘宝 登陆一个网站 另一个网站不需要登陆

单点登录的主要问题在于session共享问题 要对session中进行统一管理 使用tomcat中的session不好管理 因此我们使用redis模拟Session,实现Session的统一管理。

用户注册和传统的一样

用户登录

####用户登录的大体思路:

传入用户名和密码 与数据库中的比对 如果相同 登录成功,生成token(UUID),设置键值 放入redis缓中 并设置过期时间 并把token写入cookie中,其他系统通过取cookie中的token来从redis中得到用户信息,展示用户信息。

####用户登录

ajax调用

doLogin:function() {
				$.post("/user/login", $("#formlogin").serialize(),function(data){
					if (data.status == 200) {
						jAlert('登录成功!',"提示", function(){
							if (redirectUrl == "") {
								location.href = "http://localhost:8082";
							} else {
								location.href = redirectUrl;
							}
						});
						
					} else {
						jAlert("登录失败,原因是:" + data.msg,"失败");
					}
				});
			}

控制层:

package cn.e3mall.sso.controller;

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.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.e3mall.common.util.CookieUtils;
import cn.e3mall.common.util.E3Result;
import cn.e3mall.sso.service.LoginService;

/**
 * 用户登录处理
 * 

Title: LoginController

*

Description:

*

Company: www.itcast.cn

* @version 1.0 */ @Controller public class LoginController { @Autowired private LoginService loginService; @Value("${TOKEN_KEY}") private String TOKEN_KEY; @RequestMapping("/page/login") public String showLogin(){ return "login"; } @RequestMapping("/user/login") @ResponseBody public E3Result login(String username,String password, HttpServletRequest request,HttpServletResponse response){ E3Result e3Result = loginService.userLogin(username, password); //判断是否登录成功 if (e3Result.getStatus()==200) { String token = e3Result.getData().toString(); //如果登录成功 把token写入cookie CookieUtils.setCookie(request, response, TOKEN_KEY, token); } return e3Result; } }

service层:

package cn.e3mall.sso.service.impl;

import java.util.List;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import cn.e3mall.common.jedis.JedisClient;
import cn.e3mall.common.util.E3Result;
import cn.e3mall.common.util.JsonUtils;
import cn.e3mall.mapper.TbUserMapper;
import cn.e3mall.pojo.TbUser;
import cn.e3mall.pojo.TbUserExample;
import cn.e3mall.pojo.TbUserExample.Criteria;
import cn.e3mall.sso.service.LoginService;

/**
 * 用户登录处理
 * 

Title: LoginServiceImpl

*

Description:

*

Company: www.itcast.cn

* @version 1.0 */ @Service public class LoginServiceImpl implements LoginService { @Autowired private TbUserMapper userMapper; @Autowired private JedisClient jedisClient; @Value("${SESSION_EXPIRE}") private Integer SESSION_EXPIRE; @Override public E3Result userLogin(String username, String password) { // 1.判断用户名密码是否正确 //根据用户名查询用户信息 TbUserExample example = new TbUserExample(); Criteria criteria = example.createCriteria(); criteria.andUsernameEqualTo(username); List list = userMapper.selectByExample(example); if (list==null || list.size()==0) { //返回用户登录失败 return E3Result.build(400, "用户名或密码错误"); } //取用户信息 TbUser user = list.get(0); //判断密码是否正确 if (!DigestUtils.md5DigestAsHex(password.getBytes()).equals(user.getPassword())) { //2.如果不正确 返回登录失败 return E3Result.build(400, "用户名或密码错误"); } // 3.正确生成token(SessionId) String token = UUID.randomUUID().toString(); // 4.把用户信息写入Redis key:token value:用户信息 user.setPassword(null); jedisClient.set("SESSION:"+token, JsonUtils.objectToJson(user)); // 5. 设置session过期时间 jedisClient.expire("SESSION:"+token, SESSION_EXPIRE); // 6.把token返回 return E3Result.ok(token); } }

其中代码中用的jedis

https://blog.csdn.net/sdaujsj1/article/details/80210721

CookieUtils工具类:

package cn.e3mall.common.util;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

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


/**
 * 
 * Cookie 工具类
 *
 */
public final class CookieUtils {

    /**
     * 得到Cookie的值, 不编码
     * 
     * @param request
     * @param cookieName
     * @return
     */
    public static String getCookieValue(HttpServletRequest request, String cookieName) {
        return getCookieValue(request, cookieName, false);
    }

    /**
     * 得到Cookie的值,
     * 
     * @param request
     * @param cookieName
     * @return
     */
    public static String getCookieValue(HttpServletRequest request, String cookieName, boolean isDecoder) {
        Cookie[] cookieList = request.getCookies();
        if (cookieList == null || cookieName == null) {
            return null;
        }
        String retValue = null;
        try {
            for (int i = 0; i < cookieList.length; i++) {
                if (cookieList[i].getName().equals(cookieName)) {
                    if (isDecoder) {
                        retValue = URLDecoder.decode(cookieList[i].getValue(), "UTF-8");
                    } else {
                        retValue = cookieList[i].getValue();
                    }
                    break;
                }
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return retValue;
    }

    /**
     * 得到Cookie的值,
     * 
     * @param request
     * @param cookieName
     * @return
     */
    public static String getCookieValue(HttpServletRequest request, String cookieName, String encodeString) {
        Cookie[] cookieList = request.getCookies();
        if (cookieList == null || cookieName == null) {
            return null;
        }
        String retValue = null;
        try {
            for (int i = 0; i < cookieList.length; i++) {
                if (cookieList[i].getName().equals(cookieName)) {
                    retValue = URLDecoder.decode(cookieList[i].getValue(), encodeString);
                    break;
                }
            }
        } catch (UnsupportedEncodingException e) {
        	 e.printStackTrace();
        }
        return retValue;
    }

    /**
     * 设置Cookie的值 不设置生效时间默认浏览器关闭即失效,也不编码
     */
    public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
            String cookieValue) {
        setCookie(request, response, cookieName, cookieValue, -1);
    }

    /**
     * 设置Cookie的值 在指定时间内生效,但不编码
     */
    public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
            String cookieValue, int cookieMaxage) {
        setCookie(request, response, cookieName, cookieValue, cookieMaxage, false);
    }

    /**
     * 设置Cookie的值 不设置生效时间,但编码
     */
    public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
            String cookieValue, boolean isEncode) {
        setCookie(request, response, cookieName, cookieValue, -1, isEncode);
    }

    /**
     * 设置Cookie的值 在指定时间内生效, 编码参数
     */
    public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
            String cookieValue, int cookieMaxage, boolean isEncode) {
        doSetCookie(request, response, cookieName, cookieValue, cookieMaxage, isEncode);
    }

    /**
     * 设置Cookie的值 在指定时间内生效, 编码参数(指定编码)
     */
    public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
            String cookieValue, int cookieMaxage, String encodeString) {
        doSetCookie(request, response, cookieName, cookieValue, cookieMaxage, encodeString);
    }

    /**
     * 删除Cookie带cookie域名
     */
    public static void deleteCookie(HttpServletRequest request, HttpServletResponse response,
            String cookieName) {
        doSetCookie(request, response, cookieName, "", -1, false);
    }

    /**
     * 设置Cookie的值,并使其在指定时间内生效
     * 
     * @param cookieMaxage cookie生效的最大秒数
     */
    private static final void doSetCookie(HttpServletRequest request, HttpServletResponse response,
            String cookieName, String cookieValue, int cookieMaxage, boolean isEncode) {
        try {
            if (cookieValue == null) {
                cookieValue = "";
            } else if (isEncode) {
                cookieValue = URLEncoder.encode(cookieValue, "utf-8");
            }
            Cookie cookie = new Cookie(cookieName, cookieValue);
            if (cookieMaxage > 0)
                cookie.setMaxAge(cookieMaxage);
            if (null != request) {// 设置域名的cookie
            	String domainName = getDomainName(request);
            	System.out.println(domainName);
                if (!"localhost".equals(domainName)) {
                	cookie.setDomain(domainName);
                }
            }
            cookie.setPath("/");
            response.addCookie(cookie);
        } catch (Exception e) {
        	 e.printStackTrace();
        }
    }

    /**
     * 设置Cookie的值,并使其在指定时间内生效
     * 
     * @param cookieMaxage cookie生效的最大秒数
     */
    private static final void doSetCookie(HttpServletRequest request, HttpServletResponse response,
            String cookieName, String cookieValue, int cookieMaxage, String encodeString) {
        try {
            if (cookieValue == null) {
                cookieValue = "";
            } else {
                cookieValue = URLEncoder.encode(cookieValue, encodeString);
            }
            Cookie cookie = new Cookie(cookieName, cookieValue);
            if (cookieMaxage > 0)
                cookie.setMaxAge(cookieMaxage);
            if (null != request) {// 设置域名的cookie
            	String domainName = getDomainName(request);
            	System.out.println(domainName);
                if (!"localhost".equals(domainName)) {
                	cookie.setDomain(domainName);
                }
            }
            cookie.setPath("/");
            response.addCookie(cookie);
        } catch (Exception e) {
        	 e.printStackTrace();
        }
    }

    /**
     * 得到cookie的域名
     */
    private static final String getDomainName(HttpServletRequest request) {
        String domainName = null;

        String serverName = request.getRequestURL().toString();
        if (serverName == null || serverName.equals("")) {
            domainName = "";
        } else {
            serverName = serverName.toLowerCase();
            serverName = serverName.substring(7);
            final int end = serverName.indexOf("/");
            serverName = serverName.substring(0, end);
            final String[] domains = serverName.split("\\.");
            int len = domains.length;
            if (len > 3) {
                // www.xxx.com.cn
                domainName = "." + domains[len - 3] + "." + domains[len - 2] + "." + domains[len - 1];
            } else if (len <= 3 && len > 1) {
                // xxx.com or xxx.cn
                domainName = "." + domains[len - 2] + "." + domains[len - 1];
            } else {
                domainName = serverName;
            }
        }

        if (domainName != null && domainName.indexOf(":") > 0) {
            String[] ary = domainName.split("\\:");
            domainName = ary[0];
        }
        return domainName;
    }

}

service层的resource.properties配置文件:

#session过期时间
SESSION_EXPIRE=1800

controller层的resource.properties配置文件:

#cookie中保存token的key
TOKEN_KEY=token

其他系统显示用户信息

跨域调用单点登录系统的方法进行获取信息 用jsonp实现

Js不可以跨域请求数据。

什么是跨域:

1、域名不同

2、域名相同端口不同。

解决js的跨域问题可以使用jsonp。

Jsonp不是新技术,跨域的解决方案。使用js的特性绕过跨域请求。Js可以跨域加载js文件。

其他系统调用单点登录的js文件:

var E3MALL = {
	checkLogin : function(){
		var _ticket = $.cookie("token");
		if(!_ticket){
			return ;
		}
		$.ajax({
			url : "http://localhost:8088/user/token/" + _ticket,
			dataType : "jsonp",
			type : "GET",
			success : function(data){
				if(data.status == 200){
					var username = data.data.username;
					var html = username + ",欢迎来到宜立方购物网![退出]";
					$("#loginbar").html(html);
				}
			}
		});
	}
}

$(function(){
	// 查看是否已经登录,如果已经登录查询登录信息
	E3MALL.checkLogin();
});

单点登录控制层:

package cn.e3mall.sso.controller;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJacksonValue;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.e3mall.common.util.E3Result;
import cn.e3mall.common.util.JsonUtils;
import cn.e3mall.sso.service.TokenService;

/**
 * 根据token取用户信息Controller
 * 

Title: TokenController

*

Description:

*

Company: www.itcast.cn

* @version 1.0 */ @Controller public class TokenController { @Autowired private TokenService tokenService; //spring4.1用这个版本可以 // @RequestMapping(value="/user/token/{token}",produces=MediaType.APPLICATION_JSON_UTF8_VALUE) // @ResponseBody // public String getUserByToken(@PathVariable String token,String callback){ // E3Result result = tokenService.getUserByToken(token); // //判断是否为jsonp请求 // if (StringUtils.isNotBlank(callback)) { // //把结果封装成js语句响应 // return callback+"("+JsonUtils.objectToJson(result)+");"; // } // return JsonUtils.objectToJson(result); // } //不支持spring4.1之前的版本 @RequestMapping(value="/user/token/{token}") @ResponseBody public Object getUserByToken(@PathVariable String token,String callback){ E3Result result = tokenService.getUserByToken(token); //判断是否为jsonp请求 if (StringUtils.isNotBlank(callback)) { //把结果封装成js语句响应 MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(result); mappingJacksonValue.setJsonpFunction(callback); return mappingJacksonValue; } return result; } }

单点登录Service层

package cn.e3mall.sso.service.impl;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import cn.e3mall.common.jedis.JedisClient;
import cn.e3mall.common.util.E3Result;
import cn.e3mall.common.util.JsonUtils;
import cn.e3mall.pojo.TbUser;
import cn.e3mall.sso.service.TokenService;

/**
 * 根据token取用户信息
 * 

Title: TokenServiceImpl

*

Description:

*

Company: www.itcast.cn

* @version 1.0 */ @Service public class TokenServiceImpl implements TokenService { @Autowired private JedisClient jedisClient; @Value("${SESSION_EXPIRE}") private Integer SESSION_EXPIRE; @Override public E3Result getUserByToken(String token) { //根据token到redis中取用户信息 String json = jedisClient.get("SESSION:"+token); //取不到用户信息 登录已经过期 返回登录过期 if (StringUtils.isBlank(json)) { return E3Result.build(201, "用户登录已经过期"); } //取到用户信息更新token的过期时间 jedisClient.expire("SESSION:"+token, SESSION_EXPIRE); //返回结果,E3Result其中包含TbUser对象 TbUser user = JsonUtils.jsonToPojo(json, TbUser.class); return E3Result.ok(user); } }

登出

需要根据token删除redis中的key。

你可能感兴趣的:(Java)