当前位置: 首页 > 知识库问答 >
问题:

验证登录crendentials时在loadUserByUsername方法中获取nullpointer异常

段溪叠
2023-03-14

我有一个Spring Boot web应用程序,我试图在其中集成Spring Security性,但我面临的问题是在UserDetailsService方法的loadUserByUsername中出现nullpointer异常。我已经在我的mysql数据库中检查了给定的用户名是否存在,尝试添加和删除BCrypt编码密码和纯文本密码,但仍然得到这个错误。我在下面发布详细信息

例外情况

2019-04-11 13:51:50.457[0;39m [31mERROR[0;39m [35m5856[0;39m [2m---[0;39m [2m[nio-8080-exec-3][0;39m [36mw.a.UsernamePasswordAuthenticationFilter[0;39m [2m:[0;39m An internal error occurred while trying to authenticate the user.

org.springframework.security.authentication.InternalAuthenticationServiceException: null
    at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:123) ~[spring-security-core-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider.authenticate(AbstractUserDetailsAuthenticationProvider.java:144) ~[spring-security-core-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:175) ~[spring-security-core-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:200) ~[spring-security-core-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter.attemptAuthentication(UsernamePasswordAuthenticationFilter.java:94) ~[spring-security-web-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:212) ~[spring-security-web-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116) [spring-security-web-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.security.web.csrf.CsrfFilter.doFilterInternal(CsrfFilter.java:124) [spring-security-web-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:74) [spring-security-web-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105) [spring-security-web-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56) [spring-security-web-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215) [spring-security-web-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178) [spring-security-web-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:357) [spring-web-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:270) [spring-web-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-9.0.16.jar:9.0.16]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-9.0.16.jar:9.0.16]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) [spring-web-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-9.0.16.jar:9.0.16]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-9.0.16.jar:9.0.16]
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:92) [spring-web-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-9.0.16.jar:9.0.16]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-9.0.16.jar:9.0.16]
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93) [spring-web-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-9.0.16.jar:9.0.16]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-9.0.16.jar:9.0.16]
    at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.filterAndRecordMetrics(WebMvcMetricsFilter.java:117) [spring-boot-actuator-2.1.3.RELEASE.jar:2.1.3.RELEASE]
    at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:106) [spring-boot-actuator-2.1.3.RELEASE.jar:2.1.3.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-9.0.16.jar:9.0.16]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-9.0.16.jar:9.0.16]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) [spring-web-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-9.0.16.jar:9.0.16]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-9.0.16.jar:9.0.16]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:200) [tomcat-embed-core-9.0.16.jar:9.0.16]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-9.0.16.jar:9.0.16]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490) [tomcat-embed-core-9.0.16.jar:9.0.16]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) [tomcat-embed-core-9.0.16.jar:9.0.16]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) [tomcat-embed-core-9.0.16.jar:9.0.16]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) [tomcat-embed-core-9.0.16.jar:9.0.16]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) [tomcat-embed-core-9.0.16.jar:9.0.16]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408) [tomcat-embed-core-9.0.16.jar:9.0.16]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-9.0.16.jar:9.0.16]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:834) [tomcat-embed-core-9.0.16.jar:9.0.16]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1415) [tomcat-embed-core-9.0.16.jar:9.0.16]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.16.jar:9.0.16]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [na:1.8.0_201]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [na:1.8.0_201]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.16.jar:9.0.16]
    at java.lang.Thread.run(Unknown Source) [na:1.8.0_201]
Caused by: java.lang.NullPointerException: null
    at com.amoksha.service.UserSecurityService.loadUserByUsername(UserSecurityService.java:18) ~[classes/:na]
    at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:108) ~[spring-security-core-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    ... 62 common frames omitted

1.SecurityConfig

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private UserSecurityService userSecurityService;


// once defined, salt value should never be changed,,, should be as random as
// possible
private static final String SALT="JHBLGO&AJS70&";

@Bean
public BCryptPasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder(12, new SecureRandom(SALT.getBytes()));
}

/* Public URLS */
private static final String[] PUBLIC_MATCHERS = { "/webjars/**", "/i18n/**", "/css/**", "js/**", "/images/**", "/",
        "/errors/**" };

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests().antMatchers(PUBLIC_MATCHERS).permitAll().anyRequest().authenticated().and().formLogin()
            .loginPage("/login").defaultSuccessUrl("/admin/").failureUrl("/loginerror").permitAll().and().logout()
            .permitAll();
}

@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.authenticationProvider(authenticationProvider());
}

@Bean
public DaoAuthenticationProvider authenticationProvider(){
    DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
    provider.setUserDetailsService(userSecurityService);
    System.out.println();
    provider.setPasswordEncoder(passwordEncoder());//(NoOpPasswordEncoder.getInstance());
    return provider;
}

}

@Service
public class UserSecurityService implements UserDetailsService{

private UserRepository userRepository;

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    User user = userRepository.findByUsername(username);
    return user;
}}
public interface UserRepository extends JpaRepository<User, Long> {
User findByUsername(String username);
}
@Entity
public class User implements UserDetails {

private static final long serialVersionUID = 1L;
public User() {}

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;

@Column(nullable = false, unique = true)
private String username;

private String password;

@Column(unique = true)
private String email;

private boolean enabled;

@OneToMany(mappedBy = "user", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private Set<UserRole> userRoles = new HashSet<>();

@Override
public boolean isAccountNonExpired() {
    return true;
}

@Override
public boolean isAccountNonLocked() {
    return true;
}

@Override
public boolean isCredentialsNonExpired() {
    return true;
}

@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
    Set<GrantedAuthority> authorities = new HashSet<>();
    userRoles.forEach(ur -> authorities.add(new Authority(ur.getRole().getName())));
    return authorities;
}

//Other getters and setter
//......

5.login.html(thymeleaf)

<form th:action="@{/login}" method="post">
<div class="form-group">
    <label for="username">UserName</label>
    <input type="text" id="username" name="username" class="form-control">
</div>
<div class="form-group">
    <label for="password">Password</label>
    <input type="password" class="form-control" id="password" name="password">
</div>
<input type="submit" value="Login" class="btn btn-primary btn-block">

UserService公共用户createUser(User User,Set userRoles){

User localUser = userRepository.findByEmail(user.getEmail());

if (localUser != null) {
    /*
     * LOG.
     * info("User with username {} and email {} already exist. Nothing will be done. "
     * , user.getUsername(), user.getEmail());
     */
} else {

    String encryptedPassword = passwordEncoder.encode(user.getPassword());
    user.setPassword(encryptedPassword);

    for (UserRole ur : userRoles) {
        roleRepository.save(ur.getRole());
    }

    user.getUserRoles().addAll(userRoles);

    localUser = userRepository.save(user);

}

return localUser;

}

7.创建用户方法:

@Override
public void run(String... args) throws Exception {
    User user = new User();

    user.setUsername("test");
    user.setEmail("test@test.com");
    user.setPassword("{bcrypt}test");
    user.setEnabled(true);
    Set<UserRole> roles = new HashSet<>();
    roles.add(new UserRole(user, new Role(RolesEnum.BASIC)));
    userRep.createUser(user, roles);

}

如何删除/调试此异常?

共有1个答案

隆璞
2023-03-14

首先,您在usersecurityservice中的userrepository上缺少@autowired。因此不会注入任何东西。

其次,UserSecurityService的实现存在缺陷,因为它违反了UserDetailsService的约定。当找不到用户时,必须抛出UsernameNotFoundException

因此您的完整实现应该如下所示。

@Service
public class UserSecurityService implements UserDetailsService{

  private final UserRepository userRepository;

  public UserSecurityService(UserRepository userRepository) {
    this.userRepository=userRepository;
  }

  @Override
  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    User user = userRepository.findByUsername(username);
    if (user == null) {
      throw new UsernameNotFoundException("No user found for "+ username + ".");
    }
    return user;
  }
}

与字段注入相比,我更喜欢构造函数注入,因此使用userrepository的构造函数和较新版本的Spring(4.3或更高版本),您不需要在单个构造函数上使用@autowired

 类似资料:
  • 错误: TypeError:无法读取未定义的LoginForm c:/reactjs/hello-world/src/components/accountbox/LoginForm.js的属性“state”:23 2023 value={this.state.input.email}^24 onchange={this.handlechange}25 class=“form-control”26

  • 我正在构建一个网络应用程序,用户可以在其中注册和发布问题。一切顺利,直到我试图开发一个功能,用户将在注册时自动登录。我使用了Auth::log()类,就像我以前使用Laravel 3一样,但是我得到了以下错误: 而我用注册用户的凭证实现了类。我想Laravel 4已经改变了类的工作方式,在它的以前的版本,但我不能在他们的留档以及在我发布这个问题之前在StackExchange这里搜索。 这是我的U

  • 本文向大家介绍asp.net登录验证码实现方法,包括了asp.net登录验证码实现方法的使用技巧和注意事项,需要的朋友参考一下 前端添加的标签和方法: 验证码: 然后在项目中在新建一个VerifyCode.aspx,下面是aspx的代码: 接着是aspx.cs的代码: 于是!就可以生成验证码了,然后自己再把编写验证版的判断逻辑写好就可以啦! 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望

  • 我使用下面的命令进行了mockito-junit测试。变量serviceTask是接口的实例,称为serviceTask。我在申报中使用了@Mock 声明: 命令行: 堆栈跟踪: Java语言lang.NullPointerException在sun。反映NativeMethodAccessorImpl。sun上的invoke0(本机方法)。反映NativeMethodAccessorImpl。在

  • 问题内容: 所以我的Android Gallery中有3个文件夹。我正在尝试将这些文件夹的文件读入File数组,然后从那里将图像源转换为real 。 我的问题是引用文件数组时遇到问题。这是一些代码: 使用这些图像文件数组… 我的CreateList方法。错误是当我引用list.length时。 就像我说的那样,错误是当我使用list.length引用一个File数组时,例如我在第一个代码段中创建的

  • @FacesConverter(“ContactConverter”)公共类ContactConverter实现转换器{ 我正在使用primefaces orderlist示例。但我面临这个空指针异常。谷歌后,我发现这个问题是一些与conveter有关的事情,但我不确定。谁能帮助我与转换器的简单的primeface orderlist。