developer tip

Spring Boot : PasswordEncoder를 지정하는 방법은 무엇입니까?

copycodes 2020. 10. 13. 07:55
반응형

Spring Boot : PasswordEncoder를 지정하는 방법은 무엇입니까?


현재 나는 메인 클래스를 얻었다 :

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"를 사용자로, "user"를 암호로 입력 한 다음 하드 코딩 된 Member를 얻습니다. 제대로 작동했지만 프로젝트 실행-Maven 설치를 마우스 오른쪽 버튼으로 클릭했습니다 (종속성을 추가했기 때문에 Maven에서도 처음으로 필요한지 모르겠습니다). 그 이후로 로그인 페이지에 "user"와 "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]

로그인 페이지에 남아 있습니다. 종속성 및 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>

무엇이 잘못 되었나요? 감사


에서 spring-security-core:5.0.0.RC1, 기본값은 PasswordEncoderA와 내장되어 있습니다 DelegatingPasswordEncoder. 사용자를 메모리에 저장할 때 일반 텍스트로 암호를 제공하고 암호 DelegatingPasswordEncoder를 확인 하기 위해 인코더를 검색 할 때 이러한 암호가 저장된 방식과 일치하는 암호를 찾을 수 없습니다.

대신이 방법을 사용하여 사용자를 만듭니다.

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

사용하여 이러한 암호의 유효성을 검사 {noop}하기 위해 단순히 암호 앞에 접두사 붙일 수도 있습니다 . 공지 사항 은 일반 텍스트로 저장 암호에 좋은 방법이 아닙니다으로,하지만 사용되지 않습니다.DelegatingPasswordEncoderNoOpPasswordEncoderNoOpPasswordEncoder

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


사용 NoOpPasswordEncoder을위한inMemoryAuthentication

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

일종의 암호 인코더가 필요하지만

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


나는 단순히 추가했다

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

구성 클래스로


당신은이를 사용할 수 있지만, 그 통보 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);
}

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

이것을 시도하십시오 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");
}

나를 위해 일


다음 중 하나를 사용하면 잘 작동합니다.

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

또는

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

감사!


다음과 같이 암호 인코더를 설정해야합니다.

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

사용자와 Spring Boot 2의 클라이언트에 대해 passwordEncoder를 사용해야합니다.

이 저장소 https://github.com/dzinot/spring-boot-2-oauth2-authorization-jwt를 확인 하십시오.

passwordEncoder가 설정되는 방법과 데이터베이스의 사용자 및 클라이언트와 함께 사용하는 방법을 볼 수 있습니다.


Spring Security 5의 기본 인코더를 유지하기 위해 모든 기존 비밀번호 앞에 {noop}를 붙입니다.

예:

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

스프링 보안 5.0의 새로운 기능 에 따르면 . 그들은 이것을 씁니다 .

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"));}
   }
}

Sorry for my english and thanks for read my answer.


A few days ago I have to face the same problem on spring security version (5.0.8). See the example version here:

code:

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

auth
                .inMemoryAuthentication()
                .passwordEncoder(NoOpPasswordEncoder.getInstance())
                .withUser("farid").password("farid").roles("USER")
                .and()
                .withUser("admin").password("admin").roles("ADMIN");
    }

OR

When you are configuring the ClientDetailsServiceConfigurer, you have to also apply the new password storag`enter code here`e format to the client secret.

.secret("{noop}secret")

you can see the link: enter link description here


You need to set Password encoder , check the following sample

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

Had IllegalArgumentException: There is no PasswordEncoder mapped for the id "null" exception in my initial app loading startup housekeeper. (Just needed to normalize data in DB before the app start.) With this (manually set an authenticated user) approach you can create UsernamePasswordAuthenticationToken and setAuthentication. You can get IllegalArgumentException, if you don't specify 3-rd argument AuthorityList.

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);

Maybe some other setup steps could also work, but setting AuthorityList is good enough for me. And you can at least dig in this direction if can't find a solution on this page.

참고URL : https://stackoverflow.com/questions/46999940/spring-boot-how-to-specify-the-passwordencoder

반응형