业务
在Portal点击登录跳转到SSO登录页面,登录后,跳转到Portal首页。
实现
在Portal中需要从cookie中把token取出来。所以必须在登录成功后把token写入cookie,且cookie的值必须在系统之间能共享。
要在SsoService加上cookie:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32@Override
public TaotaoResult userLogin(String username, String password, HttpServletRequest request, HttpServletResponse response) {
TbUserExample example = new TbUserExample();
Criteria criteria = example.createCriteria();
// username
criteria.andUsernameEqualTo(username);
List<TbUser> list = userMapper.selectByExample(example);
if (list == null || list.size() == 0) {
return TaotaoResult.build(400, "username or password wrong");
}
// password
TbUser user = list.get(0);
if (!DigestUtils.md5DigestAsHex(password.getBytes()).equals(user.getPassword())) {
return TaotaoResult.build(400, "username or password wrong");
}
// token
String token = UUID.randomUUID().toString();
// add redis
redisPool.set(SSO_SESSION_KEY + ":" + token, JsonUtils.objectToJson(user));
redisPool.expire(SSO_SESSION_KEY + ":" + token, SSO_SESSION_EXPIRE);
// add cookie
CookieUtils.setCookie(request, response, "Z_TOKEN", token);
//return token
return TaotaoResult.ok(token);
}
拦截器
Interceptor拦截器用于拦截Controller层接口,以下3个步骤实现:
- 需要实现HandlerInterceptor接口。
- 实现拦截逻辑
- 需要在springmvc.xml中配置。
实现HandlerInterceptor接口
Service:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26@Service
public class UserServiceImpl implements UserService {
@Value("${SSO_BASE_URL}")
public String SSO_BASE_URL;
@Value("${SSO_USER_TOKEN}")
public String SSO_USER_TOKEN;
@Value("${SSO_USER_LOGIN}")
public String SSO_USER_LOGIN;
@Override
public TbUser getUserByToken(String token) {
try {
String json = HttpClientUtil.doGet(SSO_BASE_URL + SSO_USER_TOKEN + token);
TaotaoResult result = TaotaoResult.formatToPojo(json, TbUser.class);
if (result.getStatus() == 200) {
TbUser user = (TbUser) result.getData();
return user;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
Interceptor:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22public class LoginInterceptor implements HandlerInterceptor {
@Autowired
private UserServiceImpl userService;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
/// get token from cookie
String token = CookieUtils.getCookieValue(request, "Z_TOKEN");
// get user by token
TbUser user = userService.getUserByToken(token);
if (user == null) {
response.sendRedirect(userService.SSO_BASE_URL + userService.SSO_USER_LOGIN
+ "?redirect=" + request.getRequestURI());
return false;
}
return true;
}
}
springmvc.xml:1
2
3
4
5
6
7
8<!-- 拦截器配置 -->
<mvc:interceptors>
<mvc:interceptor>
<!-- 拦截订单类请求 -->
<mvc:mapping path="/item/**"/>
<bean class="com.izheyi.portal.interceptor.LoginInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>