由于本系统目前还未集成redis等分布式缓存,目前用的是谷歌的guava做本地缓存来是实现token的时间有效期管理。
实现token生成工类TokenGenerator
public class TokenGenerator { public static String generateValue() { return generateValue(UUID.randomUUID().toString()); } private static final char[] HEX_CODE = "0123456789abcdef".toCharArray(); public static String toHexString(byte[] data) { if(data == null) { return null; } StringBuilder r = new StringBuilder(data.length*2); for ( byte b : data) { r.append(HEX_CODE[(b >> 4) & 0xF]); r.append(HEX_CODE[(b & 0xF)]); } return r.toString(); } public static String generateValue(String param) { try { MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); algorithm.update(param.getBytes()); byte[] messageDigest = algorithm.digest(); return toHexString(messageDigest); } catch (Exception e) { throw new ServerException("token invalid", e); } }}
实现admin关token服务
public interface SysUserTokenService extends IService<SysUserTokenEntity> { /** * 生成token * @param loginUser 登录用户信息 */ RsObject createToken(UserDetail loginUser); /** * 获取用户身份信息 * * @return 用户信息 */ public UserDetail getLoginUser(HttpServletRequest request); /** * 退出 * @param userId 用户ID */ void logout(Long userId);// /**// * 在线用户分页// */// PageData<SysOnlineEntity> onlinePage(Map<String, Object> params);}
新建一个filter用于校验登录信息AuthenticationTokenFilter
@Componentpublic class AuthenticationTokenFilter extends OncePerRequestFilter{ @Autowired private SysUserTokenService tokenService; @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { UserDetail loginUser = tokenService.getLoginUser(request); if (StringUtils.isNotNull(loginUser) && StringUtils.isNull(SecurityUser.getAuthentication())) { UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities()); authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); SecurityContextHolder.getContext().setAuthentication(authenticationToken); } chain.doFilter(request, response); }}
天骄套SecurityConfig 配置
然后把如下配置从白名单中移除
启动服务刷新后台查询接口报错403
修改前端页面把后端返回的token保存下来并放到http请求头里面,如下编码
export const formatToken = (token: string): string => { return "Bearer " + token;};
然后从登录,带上token后就可以正常访问了
版权声明:内容来源于互联网和用户投稿 如有侵权请联系删除