Spring Boot身份验证 - 管理控制台向客户端返回403响应

5

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

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

我在应用程序属性中设置了管理

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

在我的管理项目中,我添加了这个类:
@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>

我被迫在主类上添加注释@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.

clientapplication.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>

现在,如果我使用浏览器访问它们两个,它们都会提示我输入登录表单。我输入用户名和密码后一切正常,但客户端的执行器无法访问管理员,总是返回403 FORBIDDEN。
2019-02-12 15:21:52.004 - [registrationTask1] DEBUG o.s.core.log.CompositeLog.debug 142 - 响应 403 FORBIDDEN
我真的不明白为什么管理控制台和客户端之间的通信不起作用。 有没有人知道我哪里错了?
1个回答

1

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

@EnableWebFluxSecurity

and not

@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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接