Spring Cloud Security - разрешать запросы без аутентификации
У меня есть приложение, которое позволяет пользователям зарегистрировать учетную запись. Наша служба аутентификации и пользователей - UAA, поэтому мне нужно иметь возможность общаться с ее защищенными конечными точками без присутствия пользователя.
Как настроить Spring Cloud Security, чтобы разрешать звонки с 1 микросервиса на другой, который затем связывается с UAA для создания пользователя?
Итак, в игре есть 2 основных микросервиса. Первый размещает веб-приложение и перенаправляет звонки с Zuul во второй микросервис. Этот микросервис связывается с UAA и обрабатывает любые другие пользовательские запросы, связанные с конкретным приложением.
У меня есть этот WebSecurityConfigurerAdapter на первом микросервисе (LandingPage)
@SpringBootApplication
@EnableZuulProxy
@EnableOAuth2Sso
@EnableEurekaClient
@EnableAutoConfiguration
public class LandingPageUiApplication extends WebSecurityConfigurerAdapter {
public static void main(String[] args) {
SpringApplication.run(LandingPageUiApplication.class, args);
}
@Override
public void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests().anyRequest().permitAll();
}
}
и это во втором микросервисе (UserInformation):
@SpringBootApplication
@EnableCircuitBreaker
@EnableFeignClients
public class UserInformationServiceApplication {
public static void main(String[] args) {
SpringApplication.run(UserInformationServiceApplication.class, args);
}
@Bean
public ModelMapper modelMapper() {
return new ModelMapper();
}
}
К сожалению, мне трудно получить доступ к конечной точке REST на первом микросервисе, а также не могу переслать что-либо на второй. Я обычно получаю код ответа 401. Их соответствующие файлы application.yaml настроены для связи с UAA в качестве клиента и сервера ресурсов.
Приложение LandingPage.yaml
spring:
application:
name: Landing Page
aop:
proxy-target-class: true
security:
oauth2:
client:
accessTokenUri: http://localhost:8080/uaa/oauth/token
userAuthorizationUri: http://localhost:8080/uaa/oauth/authorize
clientId: landing-page
clientSecret: landing-page-secret
scope: openid,uaa.admin,uaa.user
resource:
userInfoUri: http://localhost:8080/uaa/userinfo
zuul:
routes:
users:
serviceId: USER-INFO-SERVICE
path: /users/**
server:
port: 8081
eureka:
instance:
hostname: 127.0.0.1
nonSecurePort: ${server.port}
leaseRenewalIntervalInSeconds: 10
metadataMap:
instanceId: ${spring.application.name}:${server.port}
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
region: default
registryFetchIntervalSeconds: 5
и UserInfoSerevice Application.yaml
server:
port: 0
security:
oauth2:
client:
clientId: user-info-service
clientSecret: app-secret
resource:
jwt:
keyUri: http://localhost:8080/uaa/token_key
spring:
application:
name: user-info-service
profiles: development,default
datasource:
url: jdbc:h2:mem:AZ;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
driverClassName: org.h2.Driver
username: sa
password:
database-platform: org.hibernate.dialect.H2Dialect
eureka:
instance:
hostname: 127.0.0.1
nonSecurePort: ${server.port}
leaseRenewalIntervalInSeconds: 10
metadataMap:
instanceId: ${spring.application.name}:${server.port}
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
region: default
registryFetchIntervalSeconds: 5
Любая помощь с благодарностью.
1 ответ
Ответ состоял в том, чтобы поместить эту настройку WebConfigAdapter в родительский MS:
@Configuration
@EnableOAuth2Sso
@EnableAutoConfiguration
protected static class TestConfiguration extends WebSecurityConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http.csrf().disable().antMatcher("/**")
.authorizeRequests()
.anyRequest().permitAll();
}
}
и следующее у ребенка РС:
@Configuration
@Order(-10)
@EnableOAuth2Client
@EnableAutoConfiguration
protected static class TestConfiguration extends WebSecurityConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http.csrf().disable().anonymous().authenticationFilter(new AnonymousAuthenticationFilter("HALLO")) //allow anonymous access
.and()
.authorizeRequests()
.antMatchers("/**")
.permitAll();
}
}