Tomcat으로 Spring Boot를 시작할 때 사용자 이름과 비밀번호는 무엇입니까? 액세스 할 localhost:8080때

Spring Boot를 통해 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?



답변

클래스 경로에 스프링 보안이 있고 스프링 보안이 자동으로 기본 사용자 및 생성 된 비밀번호로 구성되어 있다고 생각합니다.

pom.xml 파일에서 다음을 찾으십시오.

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

Pom에 다음과 같은 로그 콘솔 메시지가 있어야합니다.

Using default security password: ce6c3d39-8f20-4a41-8e01-803166bb99b6

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

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

보안 섹션 의 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


답변

경우 spring-security항아리가 클래스 경로에 추가되고이 경우에도 spring-boot응용 프로그램이 모든 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=<>


답변

재정의 할 때

spring.security.user.name=
spring.security.user.password=

application.properties , 당신은 필요가 없습니다 "주위에 "username"단지 사용 username. 또 다른 요점은 원시 비밀번호 를 저장하는 대신 bcrypt / scrypt로 암호화하여 다음과 같이 저장합니다.

spring.security.user.password={bcrypt}encryptedPassword


답변

기본 답변을 가리키는 다른 답변을 기반으로 비밀번호를 찾을 수없는 경우 최근 버전의 로그 메시지 문구가

Using generated security password: <some UUID>


답변

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

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


답변

허용 된 답변에 추가-

로그에 비밀번호가 없으면 “org.springframework.boot.autoconfigure.security”로그를 활성화하십시오.

로깅 구성을 미세 조정하는 경우 org.springframework.boot.autoconfigure.security 범주가 INFO 메시지를 로그하도록 설정되어 있는지 확인하십시오. 그렇지 않으면 기본 비밀번호가 인쇄되지 않습니다.

https://docs.spring.io/spring-boot/docs/1.4.0.RELEASE/reference/htmlsingle/#boot-features-security


답변

Spring Security를 ​​배우기 시작했을 때 아래 코드 스 니펫과 같이 userDetailsService () 메소드를 재정의했습니다 .

@Configuration
@EnableWebSecurity
public class ApplicationSecurityConfiguration extends WebSecurityConfigurerAdapter{

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .authorizeRequests()
                .antMatchers("/", "/index").permitAll()
                .anyRequest().authenticated()
                .and()
                .httpBasic();
    }

    @Override
    @Bean
    public UserDetailsService userDetailsService() {
        List<UserDetails> users= new ArrayList<UserDetails>();
        users.add(User.withDefaultPasswordEncoder().username("admin").password("nimda").roles("USER","ADMIN").build());
        users.add(User.withDefaultPasswordEncoder().username("Spring").password("Security").roles("USER").build());
        return new InMemoryUserDetailsManager(users);
    }
}

따라서 위에서 언급 한 자격 증명을 사용하여 응용 프로그램에 로그인 할 수 있습니다. (예 : admin / nimda)

참고 : 프로덕션 환경에서는 사용하지 않아야합니다.