복붙노트

[SPRING] Tomcat으로 Spring Boot를 시작할 때 username과 password는 무엇입니까?

SPRING

Tomcat으로 Spring Boot를 시작할 때 username과 password는 무엇입니까?

Spring 부트를 통해 Spring 애플리케이션을 배치하고 localhost : 8080에 액세스 할 때 인증해야하지만 사용자 이름과 비밀번호는 무엇이며 어떻게 설정할 수 있습니까? 이 파일을 내 tomcat-users 파일에 추가하려고 시도했지만 작동하지 않았습니다.

<role rolename="manager-gui"/>
    <user username="admin" password="admin" roles="manager-gui"/>

이것은 응용 프로그램의 시작점입니다.

@SpringBootApplication
public class Application extends SpringBootServletInitializer {

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

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }
}

그리고 이것은 Tomcat 종속성입니다.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-tomcat</artifactId>
    <scope>provided</scope>
</dependency>

localhost : 8080에서 어떻게 인증합니까?

해결법

  1. ==============================

    1.나는 당신이 클래스 패스에 Spring Security를 ​​가지고 있다고 생각하고 스프링 보안은 디폴트 사용자와 생성 된 패스워드로 자동 설정된다.

    나는 당신이 클래스 패스에 Spring Security를 ​​가지고 있다고 생각하고 스프링 보안은 디폴트 사용자와 생성 된 패스워드로 자동 설정된다.

    다음을 위해 pom.xml 파일을 살펴보십시오.

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    

    만약 당신이 당신의 pom에 다음과 같은 로그 콘솔 메시지가 있어야합니다 :

    기본 보안 암호 사용 : ce6c3d39-8f20-4a41-8e01-803166bb99b6

    그리고 브라우저 프롬프트에서 콘솔에 인쇄 된 사용자 사용자와 암호를 가져옵니다.

    또는 스프링 보안을 설정하려면 스프링 부트 보안 예제를 살펴보십시오.

    이 문서는 보안 섹션의 Spring Boot Reference 문서에서 설명합니다.

    The default AuthenticationManager has a single user (‘user’ username and random password, printed at `INFO` level when the application starts up)
    
    Using default security password: 78fa095d-3f4c-48b1-ad50-e24c31d5cf35
    
  2. ==============================

    2.스프링 보안 jar가 클래스 경로에 추가되고 스프링 부트 응용 프로그램 인 경우 모든 http 엔드 포인트는 기본적으로 보안 구성 클래스 인 SecurityAutoConfiguration에 의해 보안됩니다

    스프링 보안 jar가 클래스 경로에 추가되고 스프링 부트 응용 프로그램 인 경우 모든 http 엔드 포인트는 기본적으로 보안 구성 클래스 인 SecurityAutoConfiguration에 의해 보안됩니다

    그러면 브라우저 팝업에서 자격 증명을 요청합니다.

    각 응용 프로그램의 암호 변경이 다시 시작되고 콘솔에서 찾을 수 있습니다.

    Using default security password: 78fa095d-3f4c-48b1-ad50-e24c31d5cf35
    

    기본값 앞에 자신 만의 응용 프로그램 보안 계층을 추가하려면,

    @EnableWebSecurity
    public class SecurityConfig {
    
        @Autowired
        public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
            auth
                .inMemoryAuthentication()
                    .withUser("user").password("password").roles("USER");
        }
    }
    

    또는 암호를 변경하려는 경우 기본값을 무시할 수 있습니다.

    application.xml

    security.user.password = new_password

    또는

    application.properties

    spring.security.user.name=<>
    spring.security.user.password=<>
    
  3. ==============================

    3.따라서 스프링 부트 보안 스타터 종속성을 추가하기 만하면 기본적으로 기본 보안이 이미 구성되었습니다.

    따라서 스프링 부트 보안 스타터 종속성을 추가하기 만하면 기본적으로 기본 보안이 이미 구성되었습니다.

    우리는 자체 인증 및 인증을 작성하여 보안 구성을 사용자 정의 할 수 있습니다. 이를 위해 WebSecurityConfigurerAdapter를 확장하고 해당 메서드를 재정의하는 새 클래스 SecurityConfig를 만듭니다.

    @Override
        public void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.inMemoryAuthentication().withUser("javainuse")
                    .password("javainuse").roles("USER");
        }
    

    참조 - 봄 부팅 보안 예제

  4. ==============================

    4.또한 사용자에게 자격 증명을 요청하고 서버가 시작되면 동적으로 자격 증명을 설정할 수 있습니다 (고객 환경에서 솔루션을 게시해야 할 때 매우 효과적입니다).

    또한 사용자에게 자격 증명을 요청하고 서버가 시작되면 동적으로 자격 증명을 설정할 수 있습니다 (고객 환경에서 솔루션을 게시해야 할 때 매우 효과적입니다).

    @EnableWebSecurity
    public class SecurityConfig {
    
        private static final Logger log = LogManager.getLogger();
    
        @Autowired
        public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
            log.info("Setting in-memory security using the user input...");
    
            Scanner scanner = new Scanner(System.in);
            String inputUser = null;
            String inputPassword = null;
            System.out.println("\nPlease set the admin credentials for this web application");
            while (true) {
                System.out.print("user: ");
                inputUser = scanner.nextLine();
                System.out.print("password: ");
                inputPassword = scanner.nextLine();
                System.out.print("confirm password: ");
                String inputPasswordConfirm = scanner.nextLine();
    
                if (inputUser.isEmpty()) {
                    System.out.println("Error: user must be set - please try again");
                } else if (inputPassword.isEmpty()) {
                    System.out.println("Error: password must be set - please try again");
                } else if (!inputPassword.equals(inputPasswordConfirm)) {
                    System.out.println("Error: password and password confirm do not match - please try again");
                } else {
                    log.info("Setting the in-memory security using the provided credentials...");
                    break;
                }
                System.out.println("");
            }
            scanner.close();
    
            if (inputUser != null && inputPassword != null) {
                 auth.inMemoryAuthentication()
                    .withUser(inputUser)
                    .password(inputPassword)
                    .roles("USER");
            }
        }
    }
    

    (2018 년 5 월) 업데이트 - 스프링 부트 2.x에서 작동합니다.

    @Configuration
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
        private static final Logger log = LogManager.getLogger();
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            // Note: 
            // Use this to enable the tomcat basic authentication (tomcat popup rather than spring login page)
            // Note that the CSRf token is disabled for all requests
            log.info("Disabling CSRF, enabling basic authentication...");
            http
            .authorizeRequests()
                .antMatchers("/**").authenticated() // These urls are allowed by any authenticated user
            .and()
                .httpBasic();
            http.csrf().disable();
        }
    
        @Bean
        public UserDetailsService userDetailsService() {
            log.info("Setting in-memory security using the user input...");
    
            String username = null;
            String password = null;
    
            System.out.println("\nPlease set the admin credentials for this web application (will be required when browsing to the web application)");
            Console console = System.console();
    
            // Read the credentials from the user console: 
            // Note: 
            // Console supports password masking, but is not supported in IDEs such as eclipse; 
            // thus if in IDE (where console == null) use scanner instead:
            if (console == null) {
                // Use scanner:
                Scanner scanner = new Scanner(System.in);
                while (true) {
                    System.out.print("Username: ");
                    username = scanner.nextLine();
                    System.out.print("Password: ");
                    password = scanner.nextLine();
                    System.out.print("Confirm Password: ");
                    String inputPasswordConfirm = scanner.nextLine();
    
                    if (username.isEmpty()) {
                        System.out.println("Error: user must be set - please try again");
                    } else if (password.isEmpty()) {
                        System.out.println("Error: password must be set - please try again");
                    } else if (!password.equals(inputPasswordConfirm)) {
                        System.out.println("Error: password and password confirm do not match - please try again");
                    } else {
                        log.info("Setting the in-memory security using the provided credentials...");
                        break;
                    }
                    System.out.println("");
                }
                scanner.close();
            } else {
                // Use Console
                while (true) {
                    username = console.readLine("Username: ");
                    char[] passwordChars = console.readPassword("Password: ");
                    password = String.valueOf(passwordChars);
                    char[] passwordConfirmChars = console.readPassword("Confirm Password: ");
                    String passwordConfirm = String.valueOf(passwordConfirmChars);
    
                    if (username.isEmpty()) {
                        System.out.println("Error: Username must be set - please try again");
                    } else if (password.isEmpty()) {
                        System.out.println("Error: Password must be set - please try again");
                    } else if (!password.equals(passwordConfirm)) {
                        System.out.println("Error: Password and Password Confirm do not match - please try again");
                    } else {
                        log.info("Setting the in-memory security using the provided credentials...");
                        break;
                    }
                    System.out.println("");
                }
            }
    
            // Set the inMemoryAuthentication object with the given credentials:
            InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
            if (username != null && password != null) {
                String encodedPassword = passwordEncoder().encode(password);
                manager.createUser(User.withUsername(username).password(encodedPassword).roles("USER").build());
            }
            return manager;
        }
    
        @Bean
        public PasswordEncoder passwordEncoder() {
            return new BCryptPasswordEncoder();
        }
    }
    
  5. ==============================

    5.기본 응답을 가리키는 다른 대답을 기반으로 암호를 찾을 수없는 경우 최근 버전의 로그 메시지 문구가 다음으로 변경되었습니다.

    기본 응답을 가리키는 다른 대답을 기반으로 암호를 찾을 수없는 경우 최근 버전의 로그 메시지 문구가 다음으로 변경되었습니다.

    Using generated security password: <some UUID>
    
  6. from https://stackoverflow.com/questions/37285016/what-is-username-and-password-when-starting-spring-boot-with-tomcat by cc-by-sa and MIT license