programing

Tomcat에서 Spring Boot를 시작할 때 사용자 이름과 비밀번호는 무엇입니까?

shortcode 2022. 10. 26. 23:14
반응형

Tomcat에서 Spring Boot를 시작할 때 사용자 이름과 비밀번호는 무엇입니까?

에서 Spring 하여 Spring Boot에 했을 때localhost:8080인증을 해야 하는데 사용자 이름과 비밀번호는 어떻게 설정하나요?의 는는 my my my에 하려고 했다.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

클래스 경로에 Spring Security가 있고 Spring Security가 기본 사용자 및 생성된 비밀번호로 자동으로 설정됩니다.

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

프롬프트에서 Import가 됩니다.user비밀번호가 콘솔에 출력됩니다.

또는 스프링 보안을 설정하는 경우 스프링 부트 보안의 예를 참조할 수 있습니다.

Spring Boot Reference 의 「Security(보안)」섹션의 메뉴얼에 설명되어 있습니다.다음은 예를 제시하겠습니다.

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

ifspring-security되며 classpath인 에도 classpath에 됩니다.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또 다른 포인트는 raw 비밀번호를 저장하는 대신 bcrypt/scrypt로 암호화하여 다음과 같이 저장합니다.

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

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

Using generated security password: <some UUID>

또, 유저에게 credential의 입력을 요구해, 서버가 기동하면 동적으로 설정할 수도 있습니다(고객 환경에 솔루션을 퍼블리시 할 필요가 있는 경우에 매우 효과적입니다).

@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가 설정되어 있는지 확인합니다.보안 카테고리가 INFO 메시지를 기록하도록 설정되어 있지 않으면 기본 비밀번호가 출력되지 않습니다.

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

먼저 다음 항목을 application.properties 파일에 추가합니다.

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

주의: 큰따옴표 없음

응용 프로그램을 실행하고 자격 정보(사용자, 패스)를 입력합니다.

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)

주의: 이것은 실가동 시에는 사용하지 마십시오.

프로젝트에서 아래 코드 스니펫에서 사용자 이름과 비밀번호를 가져와 로그인하고 이것이 작동하기를 바랍니다.

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

언급URL : https://stackoverflow.com/questions/37285016/what-is-username-and-password-when-starting-spring-boot-with-tomcat

반응형