安全管理面板(Spring Security)

时间:2015-10-27 10:56:16

标签: spring hibernate spring-mvc spring-security

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

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

我的用户模型包含(实现UserDetails):

    @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;
    }

授权模型包含(实现GrantedAuthority):

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

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

问题:当我添加此行并使用andMatchers并尝试访问此控制器时,会显示错误:

<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 个答案:

答案 0 :(得分: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;
}