Страница входа SpringBoot2 OAuth2 AuthorizationServer отображается бесконечным циклом после входа в систему - PullRequest
1 голос
/ 04 мая 2019

Я использую OAuth2 System с Spring Boot 2.1.4 и Spring Security OAuth2.

Я хочу разделить все компоненты Client, ResourceServer, AuthorizationServer)

поэтому я создаю 3 проекта в каждом git-репозитории.

в Client, я запросил защищенный URL.

, и Spring Security перенаправила меня на сервер авторизации /oauth/authorize и перенаправила на вход в систему сервера авторизации.страница.

Я попытался войти, и успех.и я перенаправил на свой Client и снова перенаправил на AuthorizationServer страницу входа в систему agian.(бесконечный цикл)

следующие мои 3 компонента (Client, AuthorizationServer, ResourceServer) 'Конфигурация.

Клиент

  • gradle
    plugins {
        id 'org.springframework.boot' version '2.1.4.RELEASE'
        id 'java'
    }

    ...

    dependencies {
    ...  


    /** Spring Security **/
    implementation 'org.springframework.boot:spring-boot-starter-security'

    // https://mvnrepository.com/artifact/org.springframework.security.oauth.boot/spring-security-oauth2-autoconfigure
    compile group: 'org.springframework.security.oauth.boot', name: 'spring-security-oauth2-autoconfigure', version: '2.1.4.RELEASE'

    // https://mvnrepository.com/artifact/org.springframework.security/spring-security-oauth2-client
    compile group: 'org.springframework.security', name: 'spring-security-oauth2-client', version: '5.1.5.RELEASE'
    }
  • application.yml
    ...

    spring:
        security:
            oauth2:
                client:
                    provider:
                        teemo:
                            authorizationUri: http://localhost:8082/oauth/authorize
                            tokenUri: http://localhost:8082/oauth/token
                            userInfoUri: http://localhost:8081/me


                    registration:
                        teemo:
                            clientId: foo
                            clientSecret: bar
                            provider: teemo
                            authorizationGrantType: authorization_code
                            redirectUri: http://localhost:8080/oauth2/authorization/teemo

    ...
  • WebSecurityConfigurerAdapter config
@Configuration
@EnableOAuth2Client
public class WebSecurityConfigurerAdapterImpl extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .authorizeRequests()
                .antMatchers("/", "/home", "/error", "/webjars/**", "/resources/**", "/login**").permitAll()
                .anyRequest().authenticated()
                .and().oauth2Login();
    }

}

Сервер авторизации

  • gradle
plugins {
    id 'org.springframework.boot' version '2.1.4.RELEASE'
    id 'java'
}

...

dependencies {
    ...

    /** Spring Security **/
    implementation 'org.springframework.boot:spring-boot-starter-security'

    // https://mvnrepository.com/artifact/org.springframework.security.oauth.boot/spring-security-oauth2-autoconfigure
    compile group: 'org.springframework.security.oauth.boot', name: 'spring-security-oauth2-autoconfigure', version: '2.1.4.RELEASE'

    ...
}
  • application.yml
    spring:
        security:
            user:
                name: user
                password: user
    ...
  • WebSecurityConfigurerAdapter config
@Configuration
public class WebSecurityConfigurerAdapterImpl extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .authorizeRequests()
                .antMatchers("/oauth/authorize", "/oauth/token", "/login**").permitAll()
                .and().formLogin().permitAll();
    }
}
  • AuthorizationServerConfigurerAdapter config
@Component
@EnableAuthorizationServer
public class AuthorizationServerConfigurerAdapterImpl extends AuthorizationServerConfigurerAdapter {

    private AuthenticationManager authenticationManager;

    public AuthorizationServerConfigurerAdapterImpl(AuthenticationConfiguration authenticationConfiguration) throws Exception {
        this.authenticationManager = authenticationConfiguration.getAuthenticationManager();
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("foo")
                .secret("bar")
                //.authorities("USER")
                .authorizedGrantTypes("authorization_code", "implicit", "refresh_token")
                .autoApprove(true)
                .redirectUris("http://localhost:8080/oauth2/authorization/teemo")
                .scopes("read");
    }

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

    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer)throws Exception {
        oauthServer
                .tokenKeyAccess("permitAll()")
                .checkTokenAccess("isAuthenticated()");
            }
}

ResourceServer

  • gradle
plugins {
    id 'org.springframework.boot' version '2.1.4.RELEASE'
    id 'java'
}

...
dependencies {
    ...

    /** Spring Security **/
    implementation 'org.springframework.boot:spring-boot-starter-security'

    // https://mvnrepository.com/artifact/org.springframework.security.oauth.boot/spring-security-oauth2-autoconfigure
    compile group: 'org.springframework.security.oauth.boot', name: 'spring-security-oauth2-autoconfigure', version: '2.1.4.RELEASE'

    // https://mvnrepository.com/artifact/org.springframework.security/spring-security-oauth2-resource-server
    //compile group: 'org.springframework.security', name: 'spring-security-oauth2-resource-server', version: '5.1.5.RELEASE'
}
  • application.yml
...
security:
  oauth2:
    resource:
      token-info-uri: http://localhost:8082/oauth/check_token
  • ResourceServerConfigurerAdapter config
@Configuration
@EnableResourceServer
public class ResourceServerConfigurerAdapterImpl extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/me").access("#oauth2.hasScope('read')");
    }

    @Primary
    @Bean
    public RemoteTokenServices tokenService() {
        RemoteTokenServices tokenService = new RemoteTokenServices();
        tokenService.setCheckTokenEndpointUrl("http://localhost:8082/oauth/check_token");
        tokenService.setClientId("foo");
        tokenService.setClientSecret("bar");
        return tokenService;
    }
}

и ниже - скриншот для бесконечного зацикливания после входа в систему.

бесконечно

как я могу это исправить?и я новичок в области безопасности и безопасности.

1 Ответ

1 голос
/ 05 мая 2019

Есть несколько проблем с вашим кодом.Среди них:

  1. У вас должен быть конкретный контекстный путь для каждого проекта (поскольку отслеживание сеанса основано на файлах cookie, а каждый файл cookie сеанса должен иметь уникальный путь)
  2. На сервере ресурсов /me нет сопоставления пути
  3. redirectUri должен иметь формат <client_url>/login/oauth2/code/<provider_name>

Я сделал запрос на выборку для каждого или вашегопроекты, которые исправили проблемы.

Для примера OAUTH2 со String Boot посмотрите здесь

Если вы обнаружите что-то неясное с внесенными мною модификациями, не стесняйтесьспросить меня.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...