package com.monkeylessey.framework.security.handler; import com.monkeylessey.sys.service.SysUserService; import com.monkeylessey.framework.utils.RedisUtil; import com.monkeylessey.framework.utils.TokenUtil; import org.springframework.beans.factory.annotation.Autowired; 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; //@Component public class XpAuthenticationSuccessHandler implements AuthenticationSuccessHandler { @Autowired private TokenUtil tokenUtil; @Autowired private RedisUtil redisUtil; @Autowired private SysUserService userService; @Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { // // 生成token // String token = tokenUtil.createToken(authentication.getName()); // // // 将token存入redis // String key = RedisKeyPrefixConstants.USER_TOKEN_PREFIX + authentication.getName() ; // redisUtil.saveForValue(key, token); // // // redis中token的过期时间 // redisUtil.setExpire(key, Long.valueOf(tokenUtil.getExpire()), TimeUnit.MINUTES); // // Result success = Result.ok("登录成功"); // // 用户名查找用户可使用的菜单 // success.data(userService.getMenus(authentication.getName())); // String s = new ObjectMapper().writeValueAsString(success); // // response.setCharacterEncoding("utf-8"); // response.getWriter().print(s); // // // 将token放入响应头 // // 因为默认只有7种简单响应头可以暴露出去,要使用自定义响应头,需添加如下两行代码 // response.addHeader("Access-Control-Expose-Headers","authentication"); // response.addHeader("authentication",token); // response.setStatus(HttpStatus.OK.value()); // response.setContentType(MediaType.APPLICATION_JSON_VALUE); } }