LoginSuccessHandler.java 1.63 KB
package com.objecteye.handle;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.objecteye.utils.GlobalUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.security.jwt.crypto.sign.RsaSigner;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录成功处理
 */
public class LoginSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

    private RsaSigner signer;

    private RedisTemplate redisTemplate;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        String userJsonStr = JSON.toJSONString(authentication.getPrincipal());
        JSONObject userJson = JSON.parseObject(userJsonStr);
        // 保存登录存根
        redisTemplate.opsForHash().put(GlobalUtil.LOGIN_USER_TOKEN, userJson.getString("username"), userJson.getLongValue("createTime"));
        String token = JwtHelper.encode(userJsonStr, signer).getEncoded();
        //签发token
        response.getWriter().write("token=" + token);
    }

    public void setSigner(RsaSigner signer) {
        this.signer = signer;
    }

    public void setRedisTemplate(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }
}