第04项目:淘淘商城(SpringMVC+Spring+Mybatis)【第十天】(单点登陆系统实现)

https://pan.baidu.com/s/1bptYGAb#list/path=%2F&parentPath=%2Fsharelink389619878-229862621083040html

第04项目:淘淘商城(SpringMVC+Spring+Mybatis) 的学习实践总结【第六天】java

第04项目:淘淘商城(SpringMVC+Spring+Mybatis)【第七天】(redis缓存)redis

第04项目:淘淘商城(SpringMVC+Spring+Mybatis)【第八天】(solr服务器搭建、搜索功能实现)spring

第04项目:淘淘商城(SpringMVC+Spring+Mybatis)【第九天】(商品详情页面实现)数据库

第04项目:淘淘商城(SpringMVC+Spring+Mybatis)【第十天】(单点登陆系统实现)json

 

2   课程计划浏览器

一、单点登陆系统SSO缓存

a)       建立单点登陆系统,独立的工程。服务器

b)       发布登陆、注册的接口cookie

c)       单点登陆系统实现登陆、注册功能。


3  什么是单点登陆系统

3.1   什么是SSO

SSO英文全称Single Sign On,单点登陆。SSO是在多个应用系统中,用户只须要登陆一次就能够访问全部相互信任的应用系统。它包括能够将此次主要的登陆映射到其余应用中用于同一个用户的登陆的机制。它是目前比较流行的企业业务整合的解决方案之一。

3.2   传统的登陆流程

 

 

3.2.1   传统流程中的问题:

在集群环境中。须要把同一套代码部署到多台服务器上。每一个工程都有本身独立的session

 

在集群环境中每一个工程都有本身的session,若是把用户信息写入session而不共享的话,会出现用户反复登陆的状况。


第二种方案

实现单点登陆系统,提供服务接口。把session数据存放在redis。

Redis能够设置key的生存时间、访问速度快效率高。

优势:redis存取速度快,不会出现多个节点session复制的问题。效率高。

SSO单点登陆系统通常流程

 

 

 

4   建立单点登陆系统

单点登陆系统是一个独立的工程。须要操做redis、链接数据库。

 

 注册以前的数据校验

Service层

/**
 * 用户管理Service
 * 
 * @author kangy
 *
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private TbUserMapper userMapper;

    @Override
    public TaotaoResult checkData(String content, Integer type) {
        // 建立查询条件
        TbUserExample example = new TbUserExample();
        TbUserExample.Criteria criteria = example.createCriteria();

        // 对数据进行校验:一、二、3分别表明username、phone、email
        if (1 == type) {
            criteria.andUsernameEqualTo(content);

        } else if (2 == type) {
            criteria.andPhoneEqualTo(content);

        } else {
            criteria.andEmailEqualTo(content);
        }
        // 执行查询
        List<TbUser> list = userMapper.selectByExample(example);

        if (list == null || list.size() == 0) {
            return TaotaoResult.ok(true);
        }

        return TaotaoResult.ok(false);
    }

    @Override
    public TaotaoResult createUser(TbUser user) {
        user.setUpdated(new Date());
        user.setCreated(new Date());
        //spring框架的MD5工具加密
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        userMapper.insert(user);
        return TaotaoResult.ok();
    }
    
    
}

 

5.1.4    Controller层

从url中接收两个参数,调用Service进行校验,在调用Service以前,先对参数进行校验,例如type必须是一、二、3其中之一。

返回TaotaoResult。须要支持jsonp。

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;


    @SuppressWarnings({ "deprecation" })
    @RequestMapping("/check/{param}/{type}")
    public Object checkData(@PathVariable String param, @PathVariable Integer type, String callback) {

        TaotaoResult result = null;

        // 参数有效性校验
        if (StringUtils.isBlank(param)) {
            result = TaotaoResult.build(400, "校验内容参数不能为空!");
        }
        if (type == null) {
            result = TaotaoResult.build(400, "校验内容类型不能为空!");
        }
        if (type != 1 & type != 2 & type != 3) {
            result =  TaotaoResult.build(400, "校验内容类型错误");
        }

        // 校验出错
        if (null != result) {
            if (null != callback) {
                MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(result);
                mappingJacksonValue.setJsonpFunction(callback);
                return mappingJacksonValue;
            } else {
                return result;
            }
        }

        // 调用服务
        try {
            result = userService.checkData(param, type);
        } catch (Exception e) {
            result = TaotaoResult.build(500, ExceptionUtil.getStackTrace(e));
        }

        if (null != callback) {
            MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(result);
            mappingJacksonValue.setJsonpFunction(callback);
            return mappingJacksonValue;
        } else {
            return result;
        }

    }
    
    
    //建立用户的方法
    @RequestMapping("/register")
    public TaotaoResult createUser(TbUser user) {
        try {
            TaotaoResult result = userService.createUser(user);
            return result;
            
        } catch (Exception e) {
            return TaotaoResult.build(500, ExceptionUtil.getStackTrace(e));
        }
        
        
    }

}

 

6   用户登陆接口

是一个post请求,包含用户和密码。接收用户名和密码,到数据库中查询,根据用户名查询用户信息,查到以后进行密码比对,须要对密码进行md5加密后进行比对。比对成功后说明登陆成功,须要生成一个token可使用UUID。须要把用户信息写入redis,key就是token,value就是用户信息。返回token字符串。

是一个post请求,包含用户和密码。接收用户名和密码,到数据库中查询,根据用户名查询用户信息,查到以后进行密码比对,须要对密码进行md5加密后进行比对。比对成功后说明登陆成功,须要生成一个token可使用UUID。须要把用户信息写入redis,key就是token,value就是用户信息。返回token字符串。

    //用户登陆
    @Override
    public TaotaoResult userLogin(String username, String password,
            HttpServletRequest request ,HttpServletResponse response) {
        // 建立查询条件
        TbUserExample example = new TbUserExample();
        TbUserExample.Criteria criteria = example.createCriteria();
        criteria.andUsernameEqualTo(username);
        // 执行查询
        List<TbUser> list = userMapper.selectByExample(example);
        //若是为空没有此用户名
        if(list == null || list.size() == 0) {
            return TaotaoResult.build(400, "用户名错误:不存在");
        }
        TbUser user = list.get(0);
        //System.out.println(user.getPassword());
        String pwd = DigestUtils.md5DigestAsHex(password.getBytes()); //字符串比较用.equals()方法
        if( !pwd.equals(user.getPassword()) ) {
            //控制台输入对比一下
            //System.out.println(DigestUtils.md5DigestAsHex(password.getBytes()));
            
            return TaotaoResult.build(400, "输入的密码错误。");
        }
        
        //生成token
        String token = UUID.randomUUID().toString();
        //存以前把密码清空
        user.setPassword(null);
        //把用户信息写入redis
        jedisClient.set( REDIS_USER_SESSION_KEY + ":" + token, JsonUtils.objectToJson(user));
        //设置缓存过时时长
        jedisClient.expire(REDIS_USER_SESSION_KEY + ":" + token, SSO_SESSION_EXPIRE);
        
        //添加写cookie的逻辑,此处设置是关闭浏览器就失效
        CookieUtils.setCookie(request, response, "TT_TOKEN", token);
        //返回token
        return TaotaoResult.ok(token);
    }

 

 

 

6.3   Controller层

接收表单,包含用户、密码。调用Service进行登陆返回TaotaoResult。

    //用户登陆
    @PostMapping("/login")
    @ResponseBody
    public TaotaoResult userLogin(String username,String password) {
        
        try {
            TaotaoResult result = userService.userLogin(username, password);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return TaotaoResult.build(500, ExceptionUtil.getStackTrace(e));
        }
    }
package com.taotao.common.utils;

import java.io.PrintWriter;
import java.io.StringWriter;

public class ExceptionUtil {

    /**
     * 获取异常的堆栈信息
     * 
     * @param t
     * @return
     */
    public static String getStackTrace(Throwable t) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);

        try {
            t.printStackTrace(pw);
            return sw.toString();
        } finally {
            pw.close();
        }
    }
}

 


12.根据token取用户信息

7  经过token查询用户信息

7.1   业务分析

根据token判断用户是否登陆或者session是否过时。接收token,根据token到redis中取用户信息。判断token字符串是否对应用户信息,若是不对应说明token非法或者session已过时。取到了说明用户就是正常的登陆状态。返回用户信息,同时重置用户的过时时间。

7.2   Dao层

使用JedisClient实现类。

7.3   Service层

接收token,调用dao,到redis中查询token对应的用户信息。返回用户信息并更新过时时间。

 

    @Override
    public TaotaoResult getUserByToken(String token) {
        
        //根据token从redis缓存中查询用户信息
        String json = jedisClient.get(REDIS_USER_SESSION_KEY + ":" + token);
        //判断是否为空
        if(StringUtils.isBlank(json)) {
            return TaotaoResult.build(400, "此session已过时,请从新登陆");
        }else {
            //再次设置过时时长
            jedisClient.expire(REDIS_USER_SESSION_KEY + ":" + token, SSO_SESSION_EXPIRE);        
        }
        
        //返回用户信息
        return TaotaoResult.ok(JsonUtils.jsonToPojo(json, TbUser.class));
        
    }

7.4    Controller层

接收token调用Service返回用户信息,使用TaotaoResult包装。

请求的url:

http://sso.taotao.com/user/token/{token}

    @SuppressWarnings({ "deprecation" })
    @PostMapping("/token/{token}")
    public Object getUserByToken(@PathVariable String token , String callback) {
        TaotaoResult result = null;
        try {
            TaotaoResult taotaoResult = userService.getUserByToken(token);
            result = taotaoResult;
        } catch (Exception e) {
            e.printStackTrace();
            result = TaotaoResult.build(500, ExceptionUtil.getStackTrace(e));
        }

        // 判断是否为jsonp调用
        if (StringUtils.isBlank(callback)) {
            return result;
        } else {
            MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(result);
            mappingJacksonValue.setJsonpFunction(callback);
            return mappingJacksonValue;
        }

    }

 

 

=======================================

参考资料:

 

end