spring security demo
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

54 lines
2.1 KiB

package com.aiprose.scauth.handler;
import com.aiprose.scauth.entity.Jwt;
import com.aiprose.scauth.entity.User;
import com.aiprose.scauth.util.JwtUtils;
import com.alibaba.fastjson.JSONObject;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author nelson
* @desc TODO
* @company 北京中经网软件有限公司
* @date 2020/11/27 16:15
* @since 1.0
*/
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
// 获取登录成功信息
response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
boolean loginBoolean = true;
User user = (User) authentication.getPrincipal();
user.setPassword(null);
long now = System.currentTimeMillis();
JSONObject payload = new JSONObject();
payload.put("iss", "sys"); //签发人
payload.put("aud", user.getUsername()); //受众
payload.put("exp", now + JwtUtils.EXPIRE_TIME); //过期时间
payload.put("nbf", now); //生效时间
payload.put("iat", now); //签发时间
payload.put("jti", user.getId()); //编号
payload.put("sub", "JWT-TEST"); //主题
payload.put("user", user); //用户对象
try {
String token = new Jwt(payload.toJSONString()).toString();
response.setHeader(JwtUtils.HEADER_TOKEN_NAME, token);
if (loginBoolean) {
response.getWriter().write("{\"code\": \"200\", \"msg\": \"登录成功\", \"token\": \"" + token + "\"}");
} else {
response.getWriter().write("{\"code\": \"500\", \"msg\": \"登录失败\"}");
}
} catch (Exception e) {
loginBoolean = false;
}
}
}