首页 > 解决方案 > Spring 自定义身份验证令牌从未 GCed

问题描述

我已经实现了自定义 AuthenticationProvider:

 @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String name = authentication.getName();
        String password = authentication.getCredentials().toString();

        List<GrantedAuthority> grantedAuths = new ArrayList<>();
        grantedAuths.add(new SimpleGrantedAuthority("ROLE_USER"));

        return new PassthroughAuthentication(name, password, grantedAuths);
    }

直通身份验证:

public class PassthroughAuthentication implements Authentication {
    private static final long serialVersionUID = 1L;

    private String username;
    private boolean authenticated;
    private Object password;
    private List<GrantedAuthority> grantedAuthorities;

    public PassthroughAuthentication(String username, String password, List<GrantedAuthority> grantedAuthorities){
        super();
        this.username = username;
        this.password = password;
        this.grantedAuthorities = grantedAuthorities;
    }

    @Override
    public String getName() {
        return this.username;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return this.grantedAuthorities;
    }

    @Override
    public Object getCredentials() {
        return this.password;
    }

    @Override
    public Object getDetails() {
        return null;
    }

    @Override
    public Object getPrincipal() {
        return new User(username, password.toString(), grantedAuthorities );
    }

    @Override
    public boolean isAuthenticated() {
        return authenticated;
    }

    @Override
    public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
        this.authenticated = isAuthenticated;       
    }   
}

而且我可以使用 VisualVM 看到PassthroughAuthentication每个请求的对象都保留在内存中,并且永远不会被 GC 处理。

但是我的请求是无状态的,并且我禁用了会话管理。

什么可以举办这个班?

标签: javaspringspring-securitymemory-leaks

解决方案


想通了。

代替:

http.sessionManagement().disable();

无状态会话创建解决了这个问题:

http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

推荐阅读