提问者:小点点

安全管理面板(Spring Security)


我想保护管理面板。我已添加到Spring Security:

 .antMatchers("/admin/**").hasAuthority("ADMIN")

我的用户模型包含(实现用户详细信息):

    @Override
    @OneToMany(fetch=FetchType.LAZY, mappedBy = "user", cascade = CascadeType.ALL)
    @JsonIgnore
    public Set<Authority> getAuthorities() {
        return authorities;
    }

    public void setAuthorities(Set<Authority> authorities){
        this.authorities = authorities;
    }

权威模型包含(实现GrantedAuthure):

@ManyToOne
    @JoinColumn(name="user_id")
    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

问题:当我添加,这一行andMatcher并尝试访问此控制器时,它显示错误:

<pre>java.lang.NullPointerException
    org.springframework.security.core.authority.AuthorityUtils.authorityListToSet(AuthorityUtils.java:39)
    org.springframework.security.access.expression.SecurityExpressionRoot.getAuthoritySet(SecurityExpressionRoot.java:128)
    org.springframework.security.access.expression.SecurityExpressionRoot.hasRole(SecurityExpressionRoot.java:60)
    org.springframework.security.access.expression.SecurityExpressionRoot.hasAuthority(SecurityExpressionRoot.java:52)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:483)

共1个答案

匿名用户

由于安全评估可能是在事务之外进行的,因此使用EAGER获取权限。我还建议延迟初始化,以便该方法永远不会返回null

@OneToMany(fetch=FetchType.EAGER, mappedBy = "user", cascade = CascadeType.ALL)
public Set<Authority> getAuthorities() {
    if (authorities == null)
        authorities = new HashSet<Authority>();
    return authorities;
}