当前位置: 代码迷 >> 综合 >> 解决:java.lang.IllegalArgumentException: Cannot pass a null GrantedAuthority collection
  详细解决方案

解决:java.lang.IllegalArgumentException: Cannot pass a null GrantedAuthority collection

热度:32   发布时间:2023-11-24 01:23:03.0

深入了解 java.lang.IllegalArgumentException: Cannot pass a null GrantedAuthority collection

异常:IllegalArgumentException: Cannot pass a null GrantedAuthority collection

异常信息:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'springSecurityFilterChain' defined in class path resource [org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is java.lang.IllegalArgumentException: Cannot pass a null GrantedAuthority collectionat org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:656) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:484) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1338) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1177) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:557) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:226) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:310) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:895) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:878) ~[spring-context-5.2.6.RELEASE.jar:5.2.6.RELEASE]at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550) ~[spring-context-5.2.6.RELEASE.jar:5.2.6.RELEASE]at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:143) ~[spring-boot-2.3.0.RELEASE.jar:2.3.0.RELEASE]at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:758) [spring-boot-2.3.0.RELEASE.jar:2.3.0.RELEASE]at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:750) [spring-boot-2.3.0.RELEASE.jar:2.3.0.RELEASE]at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) [spring-boot-2.3.0.RELEASE.jar:2.3.0.RELEASE]at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) [spring-boot-2.3.0.RELEASE.jar:2.3.0.RELEASE]at org.springframework.boot.SpringApplication.run(SpringApplication.java:1237) [spring-boot-2.3.0.RELEASE.jar:2.3.0.RELEASE]at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) [spring-boot-2.3.0.RELEASE.jar:2.3.0.RELEASE]at com.ssymon.study.springbootstudy.SpringBootStudyApplication.main(SpringBootStudyApplication.java:14) [classes/:na]
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is java.lang.IllegalArgumentException: Cannot pass a null GrantedAuthority collectionat org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:651) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]... 22 common frames omitted
Caused by: java.lang.IllegalArgumentException: Cannot pass a null GrantedAuthority collectionat org.springframework.util.Assert.notNull(Assert.java:198) ~[spring-core-5.2.6.RELEASE.jar:5.2.6.RELEASE]at org.springframework.security.core.userdetails.User.sortAuthorities(User.java:163) ~[spring-security-core-5.3.2.RELEASE.jar:5.3.2.RELEASE]at org.springframework.security.core.userdetails.User.<init>(User.java:123) ~[spring-security-core-5.3.2.RELEASE.jar:5.3.2.RELEASE]at org.springframework.security.core.userdetails.User$UserBuilder.build(User.java:535) ~[spring-security-core-5.3.2.RELEASE.jar:5.3.2.RELEASE]at org.springframework.security.config.annotation.authentication.configurers.provisioning.UserDetailsManagerConfigurer$UserDetailsBuilder.build(UserDetailsManagerConfigurer.java:279) ~[spring-security-config-5.3.2.RELEASE.jar:5.3.2.RELEASE]at org.springframework.security.config.annotation.authentication.configurers.provisioning.UserDetailsManagerConfigurer.initUserDetailsService(UserDetailsManagerConfigurer.java:60) ~[spring-security-config-5.3.2.RELEASE.jar:5.3.2.RELEASE]at org.springframework.security.config.annotation.authentication.configurers.userdetails.UserDetailsServiceConfigurer.configure(UserDetailsServiceConfigurer.java:47) ~[spring-security-config-5.3.2.RELEASE.jar:5.3.2.RELEASE]at org.springframework.security.config.annotation.authentication.configurers.userdetails.UserDetailsServiceConfigurer.configure(UserDetailsServiceConfigurer.java:34) ~[spring-security-config-5.3.2.RELEASE.jar:5.3.2.RELEASE]at org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder.configure(AbstractConfiguredSecurityBuilder.java:383) ~[spring-security-config-5.3.2.RELEASE.jar:5.3.2.RELEASE]at org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder.doBuild(AbstractConfiguredSecurityBuilder.java:329) ~[spring-security-config-5.3.2.RELEASE.jar:5.3.2.RELEASE]at org.springframework.security.config.annotation.AbstractSecurityBuilder.build(AbstractSecurityBuilder.java:41) ~[spring-security-config-5.3.2.RELEASE.jar:5.3.2.RELEASE]at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.authenticationManager(WebSecurityConfigurerAdapter.java:272) ~[spring-security-config-5.3.2.RELEASE.jar:5.3.2.RELEASE]at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.getHttp(WebSecurityConfigurerAdapter.java:202) ~[spring-security-config-5.3.2.RELEASE.jar:5.3.2.RELEASE]at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.init(WebSecurityConfigurerAdapter.java:322) ~[spring-security-config-5.3.2.RELEASE.jar:5.3.2.RELEASE]at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.init(WebSecurityConfigurerAdapter.java:94) ~[spring-security-config-5.3.2.RELEASE.jar:5.3.2.RELEASE]at com.ssymon.study.springbootstudy.config.SecurityConfig$$EnhancerBySpringCGLIB$$a1741648.init(<generated>) ~[classes/:na]at org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder.init(AbstractConfiguredSecurityBuilder.java:370) ~[spring-security-config-5.3.2.RELEASE.jar:5.3.2.RELEASE]at org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder.doBuild(AbstractConfiguredSecurityBuilder.java:324) ~[spring-security-config-5.3.2.RELEASE.jar:5.3.2.RELEASE]at org.springframework.security.config.annotation.AbstractSecurityBuilder.build(AbstractSecurityBuilder.java:41) ~[spring-security-config-5.3.2.RELEASE.jar:5.3.2.RELEASE]at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration.springSecurityFilterChain(WebSecurityConfiguration.java:104) ~[spring-security-config-5.3.2.RELEASE.jar:5.3.2.RELEASE]at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_112]at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_112]at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_112]at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_112]at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]... 23 common frames omitted

异常原因及解决方法

在学习SpringSecurity时,配置类中配置自定义用户但没有设置用户的角色,不设置角色会出现这个异常?

//自定义用户设置
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.inMemoryAuthentication().withUser("symon").password("000000");}

security在在验证时会调用UserDetailsServiceloadUserByUsername()方法,这里没用自定义,使用的是基于内存的验证auth.inMemoryAuthentication(),我们点进去看下源码

//auth.inMemoryAuthentication()进去之后,这里返回了用户内存管理配置器:InMemoryUserDetailsManagerConfigurer
public InMemoryUserDetailsManagerConfigurer<AuthenticationManagerBuilder> inMemoryAuthentication() throws Exception {
    return (InMemoryUserDetailsManagerConfigurer)this.apply(new InMemoryUserDetailsManagerConfigurer());}//继续往下走,进去apply方法发现,这里调用了configurer.getUserDetailsService()
//则在验证的时候使用的是管理配置器的UserDetailsService
private <C extends UserDetailsAwareConfigurer<AuthenticationManagerBuilder, ? extends UserDetailsService>> C apply(C configurer) throws Exception {
    this.defaultUserDetailsService = configurer.getUserDetailsService();return (UserDetailsAwareConfigurer)super.apply(configurer);}//那我们进去InMemoryUserDetailsManagerConfigurer中可以看到构造器中默认传入了InMemoryUserDetailsManager
public InMemoryUserDetailsManagerConfigurer() {
    super(new InMemoryUserDetailsManager(new ArrayList()));}//继续进去InMemoryUserDetailsManager看下,这个类实现了loadUserByUsername方法,终于找到的验证的地方
//该方法验证之后返回用户信息
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    UserDetails user = (UserDetails)this.users.get(username.toLowerCase());if (user == null) {
    throw new UsernameNotFoundException(username);} else {
    return new User(user.getUsername(), user.getPassword(), user.isEnabled(), user.isAccountNonExpired(), user.isCredentialsNonExpired(), user.isAccountNonLocked(), user.getAuthorities());}}//进去User构造器之后,我们就能发现,这个异常的信息终于出现了Cannot pass null or empty values to constructor
public User(String username, String password, boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked, Collection<? extends GrantedAuthority> authorities) {
    if (username != null && !"".equals(username) && password != null) {
    this.username = username;this.password = password;this.enabled = enabled;this.accountNonExpired = accountNonExpired;this.credentialsNonExpired = credentialsNonExpired;this.accountNonLocked = accountNonLocked;this.authorities = Collections.unmodifiableSet(sortAuthorities(authorities));} else {
    throw new IllegalArgumentException("Cannot pass null or empty values to constructor");}}//上面构造器中调用了sortAuthorities方法,authorities为null的话就会抛出该异常
private static SortedSet<GrantedAuthority> sortAuthorities(Collection<? extends GrantedAuthority> authorities) {
    Assert.notNull(authorities, "Cannot pass a null GrantedAuthority collection");SortedSet<GrantedAuthority> sortedAuthorities = new TreeSet(new User.AuthorityComparator());Iterator var2 = authorities.iterator();while(var2.hasNext()) {
    GrantedAuthority grantedAuthority = (GrantedAuthority)var2.next();Assert.notNull(grantedAuthority, "GrantedAuthority list cannot contain any null elements");sortedAuthorities.add(grantedAuthority);}return sortedAuthorities;}//而authorities是通过User中User.UserBuilder的roles方式构建
public User.UserBuilder roles(String... roles) {
    List<GrantedAuthority> authorities = new ArrayList(roles.length);String[] var3 = roles;int var4 = roles.length;for(int var5 = 0; var5 < var4; ++var5) {
    String role = var3[var5];Assert.isTrue(!role.startsWith("ROLE_"), () -> {
    return role + " cannot start with ROLE_ (it is automatically added)";});authorities.add(new SimpleGrantedAuthority("ROLE_" + role));}return this.authorities((Collection)authorities);

那么如何设置roles呢?

//只需要在自定义设置之后继续设置就好啦
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.inMemoryAuthentication().withUser("symon").password("000000").roles("admin");}

ok,搞定!遇到问题不仅要知道解决办法,更要知道其背后的原因,这样才能提升自己!

  相关解决方案