laitimes

Spring Security 6.0.2 Custom tokens to implement permission control

author:astevencui

Since the system has not yet integrated distributed caches such as redis, Google's Guava is currently used as a local cache to realize the time expiration date management of tokens.

Implement the token generator 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);
        }
    }
}           

Implement the admin token service

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);

}
           

Create a new filter to verify the login information AuthenticationTokenFilter

@Component
public 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);
    }
}           

Tianjiao set of SecurityConfig configuration

Spring Security 6.0.2 Custom tokens to implement permission control

Then remove the following configuration from the whitelist

Spring Security 6.0.2 Custom tokens to implement permission control

Start the service to refresh the background query interface and report error 403

Spring Security 6.0.2 Custom tokens to implement permission control

Modify the front-end page to save the token returned by the backend and put it in the HTTP request header, as follows

Spring Security 6.0.2 Custom tokens to implement permission control
export const formatToken = (token: string): string => {
  return "Bearer " + token;
};           

Then from the login, after bringing the token, you can access normally

Spring Security 6.0.2 Custom tokens to implement permission control