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

java.lang.IllegalArgumentException:没有为id“null”映射PasswordEncoder[重复]

徐洋
2023-03-14

我是springsecurity的新手,尝试在我的项目中使用springstecurity,因为这个错误不断出现

这是我的道课

package com.voicechat.dao;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import com.voicechat.entities.Credentials;
import com.voicechat.entities.Robi_nav;

public interface Robi_Dao_logIn extends JpaRepository<Credentials, Integer> {

    @Query("select c from Credentials c where c.uname = :uname")
    public Credentials getbyUname(@Param("uname") String uname);

}

这是我的凭证类

package com.voicechat.entities;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "credentials")
public class Credentials {

    @GeneratedValue
    @Id
    private int Id;
    private String uname;
    private String password;
    private String role;
    public int getId() {
        return Id;
    }
    public void setId(int id) {
        Id = id;
    }
    public String getUname() {
        return uname;
    }
    public void setUname(String uname) {
        this.uname = uname;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    
    
    
    
    
    public String getRole() {
        return role;
    }
    public void setRole(String role) {
        role = role;
    }
    
    
    public Credentials(int id, String uname, String password, String role) {
        super();
        Id = id;
        this.uname = uname;
        this.password = password;
        role = role;
    }
    public Credentials() {
        super();
        // TODO Auto-generated constructor stub
    }
    @Override
    public String toString() {
        return "Credentials [Id=" + Id + ", uname=" + uname + ", password=" + password + ", role=" + role + "]";
    }
}

我认为错误存在于此代码中

package com.voicechat.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableWebSecurity
public class MyConfig extends WebSecurityConfigurerAdapter {
    
    @Bean
    public UserDetailsService getUserDetailService() {

        return new UserDetailsServiceImpl();

    }

    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();

    }

    @Autowired
    public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {

        auth.jdbcAuthentication().passwordEncoder(new BCryptPasswordEncoder());

    }

    @Bean
    public DaoAuthenticationProvider provider() {
        DaoAuthenticationProvider daoautpro = new DaoAuthenticationProvider();
        daoautpro.setUserDetailsService(this.getUserDetailService());
        return daoautpro;

    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(provider());

    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("//**").hasRole("ADMIN").and().formLogin().and().csrf().disable();

    }

}

这是用户详细信息

package com.voicechat.config;

import java.util.Collection;
import java.util.List;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import com.voicechat.entities.Credentials;

public class CustomUserDetails implements UserDetails {

    private Credentials cred;

    public CustomUserDetails(Credentials cred) {
        super();
        this.cred = cred;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        SimpleGrantedAuthority simple = new SimpleGrantedAuthority(cred.getRole());

        return List.of(simple);

    }

    @Override
    public String getPassword() {
        return cred.getPassword();
    }

    @Override
    public String getUsername() {

        return cred.getUname();
    }

    @Override
    public boolean isAccountNonExpired() {
        // TODO Auto-generated method stub
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        // TODO Auto-generated method stub
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        // TODO Auto-generated method stub
        return true;
    }

    @Override
    public boolean isEnabled() {
        // TODO Auto-generated method stub
        return true;
    }

}

这是用户详细信息的实现

package com.voicechat.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.voicechat.dao.Robi_Dao_logIn;
import com.voicechat.entities.Credentials;



public class UserDetailsServiceImpl implements UserDetailsService{

    
    @Autowired
    private Robi_Dao_logIn login;
    
    
    
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        
        
        Credentials cred = (Credentials) login.getbyUname(username);
        System.out.println(" "+username);
        if (cred == null) {
            throw new UsernameNotFoundException("User Not Found");

        }
        CustomUserDetails custom=new CustomUserDetails(cred);

        return custom;
    }
    

}

这就是正在流行的错误

java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id "null"
    at org.springframework.security.crypto.password.DelegatingPasswordEncoder$UnmappedIdPasswordEncoder.matches(DelegatingPasswordEncoder.java:254) ~[spring-security-core-5.4.5.jar:5.4.5]
    at org.springframework.security.crypto.password.DelegatingPasswordEncoder.matches(DelegatingPasswordEncoder.java:202) ~[spring-security-core-5.4.5.jar:5.4.5]
    at org.springframework.security.authentication.dao.DaoAuthenticationProvider.additionalAuthenticationChecks(DaoAuthenticationProvider.java:76) ~[spring-security-core-5.4.5.jar:5.4.5]
    at org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider.authenticate(AbstractUserDetailsAuthenticationProvider.java:147) ~[spring-security-core-5.4.5.jar:5.4.5]
    at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:182) ~[spring-security-core-5.4.5.jar:5.4.5]
    at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:201) ~[spring-security-core-5.4.5.jar:5.4.5]
    at org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter.attemptAuthentication(UsernamePasswordAuthenticationFilter.java:85) ~[spring-security-web-5.4.5.jar:5.4.5]
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:222) ~[spring-security-web-5.4.5.jar:5.4.5]
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:212) ~[spring-security-web-5.4.5.jar:5.4.5]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.4.5.jar:5.4.5]
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:103) ~[spring-security-web-5.4.5.jar:5.4.5]
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:89) ~[spring-security-web-5.4.5.jar:5.4.5]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.4.5.jar:5.4.5]
    at org.springframework.security.web.header.HeaderWriterFilter.doHeadersAfter(HeaderWriterFilter.java:90) ~[spring-security-web-5.4.5.jar:5.4.5]
    at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:75) ~[spring-security-web-5.4.5.jar:5.4.5]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.4.jar:5.3.4]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.4.5.jar:5.4.5]
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:110) ~[spring-security-web-5.4.5.jar:5.4.5]
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:80) ~[spring-security-web-5.4.5.jar:5.4.5]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.4.5.jar:5.4.5]
    at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:55) ~[spring-security-web-5.4.5.jar:5.4.5]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.4.jar:5.3.4]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.4.5.jar:5.4.5]
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:211) ~[spring-security-web-5.4.5.jar:5.4.5]
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:183) ~[spring-security-web-5.4.5.jar:5.4.5]
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:358) ~[spring-web-5.3.4.jar:5.3.4]
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:271) ~[spring-web-5.3.4.jar:5.3.4]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.43.jar:9.0.43]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.43.jar:9.0.43]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.3.4.jar:5.3.4]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.4.jar:5.3.4]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.43.jar:9.0.43]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.43.jar:9.0.43]
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-5.3.4.jar:5.3.4]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.4.jar:5.3.4]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.43.jar:9.0.43]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.43.jar:9.0.43]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.3.4.jar:5.3.4]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.4.jar:5.3.4]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.43.jar:9.0.43]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.43.jar:9.0.43]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) ~[tomcat-embed-core-9.0.43.jar:9.0.43]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97) ~[tomcat-embed-core-9.0.43.jar:9.0.43]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542) ~[tomcat-embed-core-9.0.43.jar:9.0.43]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143) ~[tomcat-embed-core-9.0.43.jar:9.0.43]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) ~[tomcat-embed-core-9.0.43.jar:9.0.43]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) ~[tomcat-embed-core-9.0.43.jar:9.0.43]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:346) ~[tomcat-embed-core-9.0.43.jar:9.0.43]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:374) ~[tomcat-embed-core-9.0.43.jar:9.0.43]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) ~[tomcat-embed-core-9.0.43.jar:9.0.43]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:887) ~[tomcat-embed-core-9.0.43.jar:9.0.43]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1684) ~[tomcat-embed-core-9.0.43.jar:9.0.43]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) ~[tomcat-embed-core-9.0.43.jar:9.0.43]
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130) ~[na:na]
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630) ~[na:na]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-embed-core-9.0.43.jar:9.0.43]
    at java.base/java.lang.Thread.run(Thread.java:832) ~[na:na]

最后,这是我的数据库,其中存储了用户名和密码的数据库表

这个错误让我发疯,我做了一切事情来阻止这一点,但这是一次又一次的弹出,基本上我的项目是logIn系统,其中一个uname和密码被手动存储,uname和密码用于登录Web服务

共有2个答案

施飞鸿
2023-03-14

从你的代码中,我可以看到你正在使用Bcrypt编码器。你告诉Spring Security密码是使用它编码的(但实际上你并没有对其进行编码)。

 @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();

    }

在这种情况下,您需要使用BCrypt密码编码器对密码进行编码,就像loadUserByUsername方法中这样

cred.setPassword(bCryptPasswordEncoder.encode(cred.getPassword()))

也在同一个类中自动连接BCryptPasswordEncoder。

@Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder

注意:最好在将密码保存到数据库的同时对其进行编码(使用Bcrypt编码器)。所以loadUserByUsername中不需要这样做。

益何平
2023-03-14

您已经将密码定义为纯字符串,但随后您说要使用BCrypt密码编码器

如果您阅读密码格式的官方Spring引导留档,您可以看到在数据库中存储密码时需要使用的格式是:

{id}encodedPassword

这意味着在括号中,您需要定义解码密码时要使用的编码器的ID。

下面是som示例密码,其编码器id写在括号之间。

{bcrypt}$2a$10$dXJ3SW6G7P50lGmMkkmwe.20cQQubK3.HZWzG3YB1tlRy.fqvM/BG 
{noop}password 
{pbkdf2}5d923b44a6d129f3ddf3e3c8d29412723dcbde72445e8ef6bf3b508fbf17fa4ed4d6b99ca763d8dc 
{scrypt}$e0801$8bWJaSu2IKSn9Z9kM+TPXfOc/9bdYSrN1oD9qfVThWEwdRTnO7re7Ei+fUZRJ68k9lTyuTeUp4of4g24hHnazw==$OAOec05+bXxvuu/1qZ6NUR+xQYvYv7BeL1QxwRpY5Pc=  
{sha256}97cde38028ad898ebc02e690819fa220e88c62e0699403e94fff291cfffaf8410849f27605abcbc0

这意味着在您的情况下,您的密码需要以以下格式存储:

{bcrypt}YourLongEncryptedPasswordAndNotPlainText.

您得到的错误是因为spring获取您的用户,然后检查用户密码以查看其前缀是什么,所以它可以使用相同的加密对传入密码进行编码,然后与数据库中的密码进行匹配。但是当它查看定义的密码时,没有定义的编码器(没有括号定义编码器),因此它抛出一个异常,表示找不到。

最简单的解决方案是使用bcrypt使用在线服务或在Spring启动中加密密码,然后将加密版本打印到控制台。获取该密码,确保它以 {bcrypt} 开头,然后将其插入数据库。

 类似资料:
  • 我是Spring安全的新手。使用Spring 4.3和Spring Security 5.0。一切都在运行。登录页面也出现了。如果您输入了错误的密码,则表明您的登录尝试未成功,请重试。好但正确的密码引发异常 我的Spring\u安全。XML是 我的网站。xml 我的控制器类 .一旦获得正确的凭据,就没有为id“null”映射的密码编码器

  • 问题内容: 我正在从Spring Boot 1.4.9迁移到Spring Boot 2.0,还迁移到Spring Security 5,并且正在尝试通过OAuth 2进行身份验证。但是我收到此错误: java.lang.IllegalArgumentException:没有为id“ null映射的PasswordEncoder 从Spring Security 5的文档中,我知道密码的存储格式已更

  • 我正在从Spring Boot1.4.9迁移到Spring Boot2.0,也迁移到Spring Security5,我试图通过OAuth2进行身份验证。但是我得到了这个错误: IllegalArgumentException:没有为id“null”映射的PasswordEncoder 编码密码不像BCrypt 因此,我根据Spring Security5文档将编码器更新为: 现在,如果我能在数据

  • 我正在从Spring Boot 1.5.12迁移到Spring Boot 2.0和Spring Security 5,并试图通过OAuth 2进行身份验证。但即使在使用委托{noop}之后,我也会遇到这个错误: Java语言lang.IllegalArgumentException:没有为id“null”映射的PasswordEncoder 这是我的代码: SecurityConfig安全配置 O

  • 我的代码在spring版本1.5.6中运行良好。释放。但当我将版本升级到2.0.0时,我的一些方法已被弃用,但效果很好。当我通过查看没有为id“null”映射的PasswordEncoder和数据库身份验证来更改我不推荐的方法时,它开始给我错误“没有PasswordEncoder” 这是我的代码。 网络配置 账户控制员 用户服务 我看到了所有相关的答案,但它们可用于inMemory身份验证。Spr

  • 我目前正在使用h2数据库学习SpringSecurity和spring boot。 当我尝试通过它抛出的用户名和密码登录时,我使用jdbcAuthentication进行身份验证: <代码>java。lang.IllegalArgumentException:没有为id“null”映射的密码编码器 我使用密码编码器作为:。 这是错误日志 这是我的SpringSecurity课程 SpringSec