Как выставить конечные точки с помощью пружинной загрузки и oauth2 - PullRequest
0 голосов
/ 15 февраля 2019

Мне нужно выставить несколько конечных точек в моем приложении весенней загрузки.Я использовал oauth2 для реализации безопасности с использованием токенов, но мне нужно, чтобы пара конечных точек была общедоступной и не требовала токена авторизации.

Я пытался (из нескольких найденных статей) реализовать класс конфигурации WebSecurityConfigurerAdapter, подобный этому:

@Configuration
@EnableWebSecurity
class SecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity httpSecurity) {
    httpSecurity
            .antMatcher("/**")
            .authorizeRequests()
            .antMatchers('/actuator/jolokia', '/graphiql', '/voyager')
            .permitAll()
            .anyRequest()
            .authenticated()
}

}, но безрезультатно, конечные точки продолжают запрашивать токен для доступа

Зависимость pom.xml, которую я использовал для включения oauth, такова: <dependency> <groupId>org.springframework.security.oauth.boot</groupId> <artifactId>spring-security-oauth2-autoconfigure</artifactId> <version>${spring-security-oauth2.version}</version> </dependency>

Кроме того, это класс конфигурации для сервера авторизации для oauth:

@Component
@EnableResourceServer
@EnableAuthorizationServer
class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
@Value('${application.oauth.clientId}')
String clientId

@Value('${application.oauth.secret}')
String clientSecret

@Value('${application.oauth.accessTokenExpirationSeconds}')
Integer accessTokenExpirationSeconds

@Value('${application.jwt.key}')
String jwtKey

AuthenticationManager authenticationManager

AuthorizationServerConfiguration(AuthenticationConfiguration authenticationConfiguration) throws Exception {
        this.authenticationManager =     authenticationConfiguration.getAuthenticationManager()
}

@Override
void configure(ClientDetailsServiceConfigurer clients) throws Exception {
    PasswordEncoder passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder()
    String encoded = passwordEncoder.encode(clientSecret)

    clients.inMemory()
            .withClient(clientId)
            .secret(encoded)
            .authorizedGrantTypes("client_credentials")
            .scopes("all")
            .accessTokenValiditySeconds(accessTokenExpirationSeconds)
}

@Override
void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
    endpoints.authenticationManager(authenticationManager)
            .accessTokenConverter(accessTokenConverter())
}

@Bean
JwtAccessTokenConverter accessTokenConverter() {
    JwtAccessTokenConverter converter = new JwtAccessTokenConverter()
    converter.setSigningKey(jwtKey)
    converter.setVerifierKey(jwtKey)

    converter.afterPropertiesSet()
    converter
}

@Bean
TokenStore tokenStore() {
    new JwtTokenStore(accessTokenConverter())
}

1 Ответ

0 голосов
/ 15 февраля 2019

В вашем SecurityConfig вам нужно объединить отдельные операторы вместе с .and (), иначе они все будут объединены вместе в один оператор.

Попробуйте это:

httpSecurity
  .antMatcher("/**")
  .authorizeRequests()
  .and()
  .authorizeRequests().antMatchers('/actuator/jolokia', '/graphiql', '/voyager').permitAll()
  .and()
  .authorizeRequests().anyRequest().authenticated();
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...