Spring 启动身份验证 - 管理控制台 403 对客户端的响应

Spring boot authentication - admin console 403 response to client

我正在使用 jdk 1.8 和 Spring boot 2.1.2。

我想在 Spring Boot 及其客户端的管理控制台中启用身份验证。

我在管理中设置application.properties:

spring.security.user.name=admin
spring.security.user.password=secret

spring.boot.admin.discovery.enabled=true

management.endpoints.web.exposure.include=*
management.endpoints.web.cors.allowed-methods=GET,POST

Administration 项目中我添加了这个 class:

@EnableWebSecurity
@Configuration
public class SecuritySecureConfig extends WebSecurityConfigurerAdapter {

    private static final Logger logger = (Logger) LoggerFactory.getLogger(SecuritySecureConfig.class);

    private final String adminContextPath;

    public SecuritySecureConfig(AdminServerProperties adminServerProperties) {
        this.adminContextPath = adminServerProperties.getContextPath();
    }

    @Override
protected void configure(HttpSecurity http) throws Exception {

    SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
    successHandler.setTargetUrlParameter("redirectTo");
    successHandler.setDefaultTargetUrl(adminContextPath + "/");

    http.authorizeRequests()
            .antMatchers(adminContextPath + "/assets/**").permitAll()
            .antMatchers(adminContextPath + "/login").permitAll()
            .anyRequest().authenticated()
            .and()
            .formLogin().loginPage(adminContextPath + "/login").successHandler(successHandler).and()
            .logout().logoutUrl(adminContextPath + "/logout").and()
            .httpBasic().and()
            .csrf()
                .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
            .ignoringAntMatchers(
                    adminContextPath + "/instances",
                    adminContextPath + "/actuator/**"
            );

    }

}

管理pom.xml我添加了:

 <dependencies>
      <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
        <groupId>de.codecentric</groupId>
        <artifactId>spring-boot-admin-starter-server</artifactId>      
    </dependency>

    <dependency>
        <groupId>de.codecentric</groupId>
        <artifactId>spring-boot-admin-server-ui</artifactId>
    </dependency>

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

</dependencies>

我被迫在主 class 上添加注释 @EnableWebFluxSecurity 因为没有它,它会给出一个异常:

org.springframework.beans.factory.support.BeanDefinitionOverrideException: Invalid bean definition with name 'springSecurityFilterChain' defined in class path resource [org/springframework/boot/actuate/autoconfigure/security/reactive/ReactiveManagementWebSecurityAutoConfiguration.class]: Cannot register bean definition [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.actuate.autoconfigure.security.reactive.ReactiveManagementWebSecurityAutoConfiguration; factoryMethodName=springSecurityFilterChain; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/actuate/autoconfigure/security/reactive/ReactiveManagementWebSecurityAutoConfiguration.class]] for bean 'springSecurityFilterChain': There is already [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration; factoryMethodName=springSecurityFilterChain; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class]] bound.

客户端application.properties:

spring.security.user.name=joe
spring.security.user.password=my-secret-password

spring.boot.admin.client.username=admin
spring.boot.admin.client.password=secret

spring.boot.admin.client.instance.metadata.user.name=admin
spring.boot.admin.client.instance.metadata.user.password=secret


spring.boot.admin.client.enabled=true

spring.boot.admin.client.auto-registration=true
spring.boot.admin.client.auto-deregistration=true

并且在客户端pom.xml:

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

现在,如果我使用浏览器访问它们,它们会提示我输入登录表单。我输入登录名和密码,一切正常,但客户端的执行器无法访问管理员,它 returns 总是 403 FORBIDDEN。

2019-02-12 15:21:52.004 - [registrationTask1] DEBUG o.s.core.log.CompositeLog.debug 142 - Response 403 FORBIDDEN

我真的无法理解为什么管理控制台和客户端之间的通信不起作用。 有谁知道我错在哪里?

我有同样的问题 所以,使用

@EnableWebFluxSecurity

而不是

@EnableWebSecurity

像这样

@Configuration
@EnableWebFluxSecurity
public class AppSecurityConfig   {

    private final AdminServerProperties adminServer;

    public AppSecurityConfig (AdminServerProperties adminServer) {
        this.adminServer = adminServer;
    }
    @Bean
    public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
        http
            .securityMatcher(new NegatedServerWebExchangeMatcher(
                ServerWebExchangeMatchers.pathMatchers("/instances")))
            .securityMatcher(new NegatedServerWebExchangeMatcher(
                ServerWebExchangeMatchers.pathMatchers("/actuator/**")))
            .authorizeExchange()
            .anyExchange().authenticated()
            .and()
            .formLogin()
            .loginPage(this.adminServer.getContextPath() + "/login")
            .and()
            .logout()
            .logoutUrl(this.adminServer.getContextPath() + "/logout")
            .and()
            .httpBasic()
            .and()
            .csrf().disable();
        return http.build();
    } }

在你application.yml

spring:
  security:
    user:
      password: ${ADMIN_PASSWORD}
      name: ${ADMIN_USER}
  application:
    name: Admin Server 
  boot:
    admin:
      client:
        username: ${ADMIN_USER}
        password: ${ADMIN_PASSWORD}
        url: ${ADMIN_SERVER_URL}
        enabled: true
      ui:
        cache:
          no-cache: true
        title: App Monitoring
        instance:
          name: ${spring.application.name}
  main:
    allow-bean-definition-overriding: true
management:
  endpoints:
    web:
      exposure:
        include: "*"
      cors:
        allowed-origins: "*"
        allowed-methods: GET,POST
  endpoint:
    health:
      show-details: always

它可以根据需要自行监控


在客户端应用程序中

spring:
  boot:
    admin:
      client:
        url: ${ADMIN_SERVER_URL}
        username: ${ADMIN_USER}
        password: ${ADMIN_PASSWORD}
        instance:
          name: ${spring.application.name}
        auto-registration: true
  application:
    name: Client App