Spring Boot:如何指定PasswordEncoder?

时间:2017-10-29 12:02:53

标签: spring maven spring-boot spring-security

目前我获得了主要课程:

package com.recweb.springboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;


@SpringBootApplication
/*@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})*/
public class SpringbootApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootApplication.class, args);
    }
}

成员类(id,firstname ..),MemberController类:

package com.recweb.springboot;

import java.util.Arrays;
import java.util.List;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MemberController {
    @GetMapping("/members")
    public List<Member> getAllUsers() {
        return Arrays.asList(new Member(1, "amit"));
    }
}

和WebSecurityConfig类:

package com.recweb.springboot;

import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public UserDetailsService userDetailsService() {
        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
        manager.createUser(User.withUsername("user").password("user").roles("USER").build());
        return manager;
    }
}

当我运行“http://localhost:8080/members”时,我会收到一个登录页面,我输入“user”作为用户&amp; “用户”作为密码,然后我得到硬编码的成员。 它工作正常,但后来我右键单击我的项目 - 运行as-Maven安装(因为我添加了一个依赖项,我不知道是否有必要,第一次使用Maven)。 从那时起,当我进入“用户”&amp;登录页面上的“user”我收到此错误:

java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id "null"
    at org.springframework.security.crypto.password.DelegatingPasswordEncoder$UnmappedIdPasswordEncoder.matches(DelegatingPasswordEncoder.java:233) ~[spring-security-core-5.0.0.BUILD-SNAPSHOT.jar:5.0.0.BUILD-SNAPSHOT]
    at org.springframework.security.crypto.password.DelegatingPasswordEncoder.matches(DelegatingPasswordEncoder.java:196) ~[spring-security-core-5.0.0.BUILD-SNAPSHOT.jar:5.0.0.BUILD-SNAPSHOT]
    at org.springframework.security.authentication.dao.DaoAuthenticationProvider.additionalAuthenticationChecks(DaoAuthenticationProvider.java:86) ~[spring-security-core-5.0.0.BUILD-SNAPSHOT.jar:5.0.0.BUILD-SNAPSHOT]
    at org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider.authenticate(AbstractUserDetailsAuthenticationProvider.java:166) ~[spring-security-core-5.0.0.BUILD-SNAPSHOT.jar:5.0.0.BUILD-SNAPSHOT]
    at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:174) ~[spring-security-core-5.0.0.BUILD-SNAPSHOT.jar:5.0.0.BUILD-SNAPSHOT]
    at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:199) ~[spring-security-core-5.0.0.BUILD-SNAPSHOT.jar:5.0.0.BUILD-SNAPSHOT]
    at org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter.attemptAuthentication(UsernamePasswordAuthenticationFilter.java:94) ~[spring-security-web-5.0.0.BUILD-SNAPSHOT.jar:5.0.0.BUILD-SNAPSHOT]
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:212) ~[spring-security-web-5.0.0.BUILD-SNAPSHOT.jar:5.0.0.BUILD-SNAPSHOT]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) ~[spring-security-web-5.0.0.BUILD-SNAPSHOT.jar:5.0.0.BUILD-SNAPSHOT]
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116) ~[spring-security-web-5.0.0.BUILD-SNAPSHOT.jar:5.0.0.BUILD-SNAPSHOT]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) ~[spring-security-web-5.0.0.BUILD-SNAPSHOT.jar:5.0.0.BUILD-SNAPSHOT]
    at org.springframework.security.web.csrf.CsrfFilter.doFilterInternal(CsrfFilter.java:124) ~[spring-security-web-5.0.0.BUILD-SNAPSHOT.jar:5.0.0.BUILD-SNAPSHOT]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.1.RELEASE.jar:5.0.1.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) ~[spring-security-web-5.0.0.BUILD-SNAPSHOT.jar:5.0.0.BUILD-SNAPSHOT]
    at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64) ~[spring-security-web-5.0.0.BUILD-SNAPSHOT.jar:5.0.0.BUILD-SNAPSHOT]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.1.RELEASE.jar:5.0.1.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) ~[spring-security-web-5.0.0.BUILD-SNAPSHOT.jar:5.0.0.BUILD-SNAPSHOT]
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105) ~[spring-security-web-5.0.0.BUILD-SNAPSHOT.jar:5.0.0.BUILD-SNAPSHOT]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) ~[spring-security-web-5.0.0.BUILD-SNAPSHOT.jar:5.0.0.BUILD-SNAPSHOT]
    at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56) ~[spring-security-web-5.0.0.BUILD-SNAPSHOT.jar:5.0.0.BUILD-SNAPSHOT]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.1.RELEASE.jar:5.0.1.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) ~[spring-security-web-5.0.0.BUILD-SNAPSHOT.jar:5.0.0.BUILD-SNAPSHOT]
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:214) ~[spring-security-web-5.0.0.BUILD-SNAPSHOT.jar:5.0.0.BUILD-SNAPSHOT]
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:177) ~[spring-security-web-5.0.0.BUILD-SNAPSHOT.jar:5.0.0.BUILD-SNAPSHOT]
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:357) ~[spring-web-5.0.1.RELEASE.jar:5.0.1.RELEASE]
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:270) ~[spring-web-5.0.1.RELEASE.jar:5.0.1.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-5.0.1.RELEASE.jar:5.0.1.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.1.RELEASE.jar:5.0.1.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:108) ~[spring-web-5.0.1.RELEASE.jar:5.0.1.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.1.RELEASE.jar:5.0.1.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81) ~[spring-web-5.0.1.RELEASE.jar:5.0.1.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.1.RELEASE.jar:5.0.1.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) ~[spring-web-5.0.1.RELEASE.jar:5.0.1.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.1.RELEASE.jar:5.0.1.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_131]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_131]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.23.jar:8.5.23]
    at java.lang.Thread.run(Thread.java:748) [na:1.8.0_131]

并保留在登录页面上。 我试图删除依赖&amp; Maven再次安装,但没有运气。 这是我的POM:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.recweb</groupId>
    <artifactId>springboot</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>springboot</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.0.BUILD-SNAPSHOT</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-rest</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
                </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-validator -->
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>5.3.0.Final</version>
</dependency>
        <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
<!--         <scope>provided</scope> -->
</dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>

    <pluginRepositories>
        <pluginRepository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </pluginRepository>
        <pluginRepository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </pluginRepository>
    </pluginRepositories>


</project>

出了什么问题? 感谢

16 个答案:

答案 0 :(得分:117)

spring-security-core:5.0.0.RC1中,默认PasswordEncoder构建为DelegatingPasswordEncoder。当您将用户存储在内存中时,您将以纯文本形式提供密码,并且在尝试从DelegatingPasswordEncoder检索编码器以验证密码时,找不到与这些密码的存储方式相匹配的密码。

使用这种方式代替创建用户。

User.withDefaultPasswordEncoder().username("user").password("user").roles("USER").build(); 

您也可以简单地在{noop}前加密码,以便DelegatingPasswordEncoder使用NoOpPasswordEncoder验证这些密码。请注意,NoOpPasswordEncoder已被弃用,因为以纯文本格式存储密码不是一个好习惯。

User.withUsername("user").password("{noop}user").roles("USER").build();

有关详细信息,请查看此信息。

https://spring.io/blog/2017/11/01/spring-security-5-0-0-rc1-released#password-encoding

答案 1 :(得分:65)

NoOpPasswordEncoder用于inMemoryAuthentication

auth.inMemoryAuthentication()
    .withUser("user")
    .password("{noop}password")
    .roles("USER")

答案 2 :(得分:11)

你需要有某种密码编码器,但是

withDefaultPasswordEncoder()

已弃用,不再适合生产。请改用:

PasswordEncoder encoder =
     PasswordEncoderFactories.createDelegatingPasswordEncoder();

...

UserDetails user = User.withUsername("someusername")
                       .password(encoder.encode("somepassword"))
                       .roles("USER").build();

参考:https://docs.spring.io/spring-security/site/docs/5.0.2.BUILD-SNAPSHOT/api/index.html?org/springframework/security/core/userdetails/User.html

答案 3 :(得分:8)

您可以使用此功能,但请注意User.withDefaultPasswordEncoder() 已弃用

@Bean
@Override
public UserDetailsService userDetailsService() {

    PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();

    final User.UserBuilder userBuilder = User.builder().passwordEncoder(encoder::encode);
    UserDetails user = userBuilder
            .username("user")
            .password("password")
            .roles("USER")
            .build();

    UserDetails admin = userBuilder
            .username("admin")
            .password("password")
            .roles("USER","ADMIN")
            .build();

    return new InMemoryUserDetailsManager(user, admin);
}

答案 4 :(得分:8)

我只是添加了

 @Bean
public static NoOpPasswordEncoder passwordEncoder() {
 return (NoOpPasswordEncoder) NoOpPasswordEncoder.getInstance();
}

到配置类

答案 5 :(得分:8)

@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception{    
    auth.inMemoryAuthentication().passwordEncoder(NoOpPasswordEncoder.getInstance())
            .withUser("test").password("test123").roles("USER").and()
            .withUser("test1").password("test123").roles("ADMIN");
}

答案 6 :(得分:8)

SecurityConfig extends WebSecurityConfigurerAdapter中尝试一下:

@Bean
public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
}
@Override
protected void configure(final AuthenticationManagerBuilder auth) throws Exception{        
    auth
        .inMemoryAuthentication()
            .withUser("user")
            .password(passwordEncoder().encode("password"))
            .roles("USER")
        .and()
            .withUser("admin")
            .password(passwordEncoder().encode("admin"))
            .roles("USER", "ADMIN");
}

为我工作

答案 7 :(得分:5)

使用以下任何一种方法都可以正常工作:-

if(!orderHistoryPage.verifyProduct(colour)){
   throw new Exception();
}

@Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("admin").password("{noop}admin@123").roles("admin");
    }

@Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("admin").password("{noop}admin").roles("admin");
    }

谢谢!

答案 8 :(得分:1)

您需要设置密码编码器,如下所示:

@Bean
public PasswordEncoder passwordEncoder() {
  return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}

需要为用户和Spring Boot 2中的客户端使用passwordEncoder

查看此存储库https://github.com/dzinot/spring-boot-2-oauth2-authorization-jwt

您可以看到如何设置passwordEncoder以及如何将其与数据库中的用户和客户端一起使用。

答案 9 :(得分:1)

使用{noop}前缀所有现有密码,以保留Spring Security 5的默认编码器。

示例:

auth.inMemoryAuthentication()
    .withUser("admin").password("{noop}admin!234").roles("ADMIN");

答案 10 :(得分:0)

根据spring security 5.0 's new feature. 他们写this

  

Spring Security的PasswordEncoder接口用于执行一个   方式转换密码以允许密码存储   牢固。鉴于PasswordEncoder是单向转换,它不是   密码转换需要双向时(即   存储用于对数据库进行身份验证的凭据)。通常   PasswordEncoder用于存储需要的密码   与身份验证时用户提供的密码进行比较。

所以我尝试了这个Mutiple HttpSecurity。 这是我的安全配置。希望对你有所帮助。

@Configuration
@EnableWebSecurity
public class SecurityConfig
{
  private final EdminService edminService;
  public SecurityConfig ( final EdminService edminService ){
    this.edminService=edminService;
  }
  @Bean
  public UserDetailsService userDetailsService() throw Exception {
    UserBuilder users= Users.withDefaultPasswordEncoder;
    InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
    List<EdminEntity> edminList=this.edminService.findAll();
    for(EdminEntity edmin: edminList){
     manager.createUser(users.username(edmin.getEdminname())
     .password(edmin.getEdminrpass()).roles("EDMIN_ROLE").build());
    }
    return manager;
  }
  @Configuration
  @Order(1)
  public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
    protected void configure(HttpSecurity http) throws Exception {
       http
       .authorizeRequests()
       .antMatchers("/home","/vendor/**","/image/**","/home/**").permitAll()
       .antMatchers("/admin/**").hasRole("EDMIN_ROLE")
       .anyRequest().authenticated()
       .and()
       .formLogin()
       .loginPage("/login")
       .permitAll()
       .defaultSuccessUrl("/home")
       .and()
       .logout()
       .logoutRequestMatcher(new AntPathRequestMatcher("/logout"));}
   }
}

对不起我的英文,感谢您阅读我的回答。

答案 11 :(得分:0)

%prec '*'

您可以看到链接:enter link description here

答案 12 :(得分:0)

您需要设置密码编码器,请检查以下示例

PasswordEncoder encoder =
             PasswordEncoderFactories.createDelegatingPasswordEncoder();
    auth.inMemoryAuthentication().passwordEncoder(encoder).withUser("Ahmad")
            .password("1600").roles("USER", "ADMIN").and().withUser("Belal").password("1515").roles("USER");

答案 13 :(得分:0)

我的初始应用加载启动管家中出现IllegalArgumentException: There is no PasswordEncoder mapped for the id "null"异常。 (只需在应用启动之前对数据库中的数据进行规范化。)使用this (manually set an authenticated user)方法,您可以创建UsernamePasswordAuthenticationToken和setAuthentication。如果未指定第3个参数AuthorityList,则可以获取IllegalArgumentException。

UsernamePasswordAuthenticationToken authReq = new UsernamePasswordAuthenticationToken(
        admin.getEmail(), 
        UserServiceImpl.PASSWORD_ENCODER.encode(admin.getPassword()),
        AuthorityUtils.createAuthorityList(admin.getRoles()) // <= had to add this line to resolve the exception
);

SecurityContextHolder.getContext().setAuthentication(authReq);

也许其他一些设置步骤也可以工作,但是设置AuthorityList对我来说已经足够了。如果在此页面上找不到解决方案,您至少可以朝这个方向进行挖掘。

答案 14 :(得分:0)

如果您正在执行“内存身份验证”,那么这里是有关如何执行此操作的代码。在Spring Boot 2.3.3.RELEASE上进行了测试

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    static PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("testuser").password(encoder.encode("testpassword")).roles("ADMIN");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.authorizeRequests().antMatchers("/sites.xhtml/**").hasRole("ADMIN").anyRequest().fullyAuthenticated().and()
                .httpBasic();
    }

    @Bean
    public static PasswordEncoder passwordEncoder() {
        return encoder;

    }
}
    

答案 15 :(得分:0)

由于我发现了许多不同的赞成的答案,而且解释很少,因此我决定提供我自己的答案,这应该可以更深入地了解 Spring Security 密码编码的工作原理。我花了一些时间调试 Spring 代码以找出所有细节。

在内部,Spring Security 在对用户进行身份验证时使用 DelegatingPasswordEncoder。假设在登录期间提供了凭据 user:passwordDelegatingPasswordEncoder 会加载此特定用户的存储密码并尝试确定其编码。 DelegatingPasswordEncoder 期望密码以 {type}hash 的形式存储:

{bcrypt}hash
{scrypt}hash
{MD5}hash
{noop}hash
...

如果默认 DelegatingPasswordEncoder 现在遇到没有 {type} 的存储密码,它无法推断要使用哪个编码器,而是使用 UnmappedIdPasswordEncoder 抛出异常。这意味着发生异常是因为密码存储时没有任何编码信息,而 Spring Security 使用的 DelegatingPasswordEncoder 无法处理。

解决此问题的一种方法是还使用 DelegatingPasswordEncoder 对密码进行编码和存储。使用 PasswordEncoderFactories.createDelegatingPasswordEncoder() 检索的编码器将使用 bcrypt 作为默认编码,因此密码将存储为 {bcrypt}hash:

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {

    PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();

    auth.inMemoryAuthentication()
        .withUser("user")
        .password(encoder.encode("password"))
        .roles("USER");
}

当您想要处理项目中的不同编码时,DelegatingPasswordEncoder 很有用。例如,假设旧密码以纯文本形式存储,而新密码现在使用 bcrypt 进行编码。您只需要在所有旧的存储密码前加上 {noop} 前缀就可以了。如果您存储了用 MD5 编码的密码,它也会起作用,只需在它们前面加上 {MD5}

在一个新项目中,也可以定义一个特定的编码,如 BCryptPasswordEncoder 而不是使用委托编码。当编码器注册为 bean 时,Spring Security 也将使用此编码器而不是 DelegatingPasswordEncoder 进行身份验证。密码现在存储为 bcrypt hash,没有 {type}

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

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {

    auth.inMemoryAuthentication()
        .withUser("user")
        .password(passwordEncoder().encode("password"))
        .roles("USER");
}

因此您可以选择所描述的变体之一。我最近使用了 PasswordEncoderFactories.createDelegatingPasswordEncoder(),因为它只需要一行代码,不需要创建 bean。