简体   繁体   English

Spring Cloud Eureka带有Spring安全性

[英]Spring Cloud Eureka with Spring security

I have a project using a eureka server and client. 我有一个使用eureka服务器和客户端的项目。 The Eureka server is using spring security and users accessing any URL should authenticate themselves. Eureka服务器使用spring安全性,访问任何URL的用户应该自己进行身份验证。 This also applies on the Eureka clients. 这也适用于Eureka客户。

The current configuration looks like the following: 当前配置如下所示:

Eureka Server: 尤里卡服务器:

Java: Java的:

@SpringBootApplication
@EnableEurekaServer
@EnableZuulProxy
@Controller
public class UiApplication {

    @GetMapping("/user")
    @ResponseBody
    public Principal user(Principal user) {
        return user;
    }

    @GetMapping(value = "/{path:[^\\.]*}")
    public String redirect() {
        return "forward:/";
    }

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

    @Configuration
    @Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
    protected static class SecurityConfiguration extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            // @formatter:off
            http
                .httpBasic().and()
                .logout().and()
                .authorizeRequests()
                .antMatchers("/index.html", "/", "/home", "/login").permitAll()
                    .anyRequest().authenticated()
                    .and()
                .csrf()
                    .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
            // @formatter:on
        }
    }

}

Config: 配置:

security:
  basic:
    enabled: true
  user:
    password: password
spring:
  application:
    name: main
  session:
    store-type: redis
zuul:
  routes:
    resource:
      path: /resource/**
      #url: http://localhost:9000
      sensitive-headers:

eureka:
  instance:
    hostname: localhost
  client:
    registerWithEureka: true
    fetchRegistry: true
    serviceUrl:
      defaultZone: http://user:password@localhost:8080/eureka/

Already when starting the server I get an exception, because the eureka client is enabled for the server and tries to connect, but can't because of authentication problems. 在启动服务器时,我得到一个例外,因为eureka客户端已启用服务器并尝试连接,但由于身份验证问题而无法使用。 The exception is the following: 例外情况如下:

com.netflix.discovery.shared.transport.TransportException: Cannot execute request on any known server

If I disable spring security in the server properties everything works fine. 如果我在服务器属性中禁用spring security,一切正常。 How do I authenticate the eureka client if spring security is activated? 如果激活弹簧安全性,如何验证eureka客户端?

You need to explicitly disable CSRF protection Declare the following definitions in the Sprint class: 您需要显式禁用CSRF保护在Sprint类中声明以下定义:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@SpringBootApplication
@EnableEurekaServer
public class EurekaClientApplication {

    @EnableWebSecurity
    static class WebSecurityConfig extends WebSecurityConfigurerAdapter {

        /**
         * disable CSRF
         * @param http
         * @throws Exception
         */
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.csrf().disable();
        }
    }

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

Use this below security configuration. 使用以下安全配置。 Also in your ZUUL server change it to @EnableEurekaClient from @EnableEurekaServer 此外,在您的ZUUL服务器更改它从@EnableEurekaClient @EnableEurekaServer

package com.debopam.discovery;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;

/**
 * @author Debopam
 *
 */
@Configuration
@EnableWebSecurity
@Order(1)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
        .withUser("discUser").password("discPassword").roles("SYSTEM")
        .and()
        .withUser("admin").password("admin").roles("ADMIN")
        .and()
        .withUser("actuator").password("actuator").roles("ACTUATOR");
        ;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.sessionManagement()
                        .sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED).and()
                        .httpBasic().and()/*disable().*/
                        .authorizeRequests()
                            .antMatchers(HttpMethod.GET, "/") .hasRole("ADMIN")
                            .antMatchers("/manage/health**").permitAll()
                            .antMatchers("/manage/**").hasRole("ACTUATOR")
                            .antMatchers("/eureka/css/**","/eureka/images/**","/eureka/fonts/**", "/eureka/js/**").permitAll()
                            .antMatchers("/eureka/**").hasRole("SYSTEM")
                        .anyRequest().denyAll()
                .and().csrf().disable();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM