0

У меня есть приложение zuul OAuth2 для весны.весна OAuth2 zuul - токен доступа истек, invalid_token

authServer--

OAuth2ServerConfiguration:

@Configuration 
public class { 
    @Bean 
    public TokenStore tokenStore() { 
     return new InMemoryTokenStore(); 
    } 

    @Configuration 
    @EnableResourceServer 
    protected static class ResourceServerConfiguration extends 
      ResourceServerConfigurerAdapter { 

     @Override 
     public void configure(ResourceServerSecurityConfigurer resources) { 
      resources.resourceId(RESOURCE_ID); 
     } 

     @Override 
     public void configure(HttpSecurity http) throws Exception {   http .authorizeRequests() 
        .antMatchers("/oauth/authorize/**","/oauth/check_token/**").permitAll() 

        .anyRequest().authenticated(); 
      // @formatter:on 
     } 

    } 

    @Configuration 
    @EnableAuthorizationServer 
    protected static class AuthorizationServerConfiguration extends 
      AuthorizationServerConfigurerAdapter { 

     //private TokenStore tokenStore = new InMemoryTokenStore(); 
     @Autowired 
     @Qualifier("authenticationManagerBean") 
     private AuthenticationManager authenticationManager; 


     @Autowired 
     TokenStore tokenStore; 

     @Autowired 
     private CustomUserDetailService customUserDetailService; 



     @Override 
     public void configure(AuthorizationServerEndpointsConfigurer endpoints) 
       throws Exception { 
      // @formatter:off 
      endpoints 
        .tokenStore(this.tokenStore) 
        .authenticationManager(this.authenticationManager) 
        .userDetailsService(customUserDetailService); 
      // @formatter:on 
     } 

     @Override 
     public void configure(ClientDetailsServiceConfigurer clients) throws Exception { 
      // @formatter:off 
      clients 
        .inMemory() 
        .withClient("kksdi2388wmkwe") 
        .authorizedGrantTypes("authorization_code","password", "refresh_token") 
        .scopes("read", "write") 
        .resourceIds("ReadAndWriteResource") 
        .secret("kksd23isdmsisdi2") 
        .autoApprove(true) 
        .accessTokenValiditySeconds(120) 
        .refreshTokenValiditySeconds(1200); 
      // @formatter:on 
     } 

     @Bean 
     @Primary 
     public DefaultTokenServices tokenServices() { 
      DefaultTokenServices tokenServices = new DefaultTokenServices(); 
      tokenServices.setSupportRefreshToken(true); 
      tokenServices.setTokenStore(this.tokenStore); 
      return tokenServices; 
     } 

    } 
} 

WebSecurity:

@Configuration 
@EnableWebSecurity 
@Order(-20) 
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { 

    @Autowired 
    private CustomAuthenticationProvider customAuthenticationProvider; 



    @Override 
    protected void configure(AuthenticationManagerBuilder auth) throws Exception { 
    auth.authenticationProvider(customAuthenticationProvider); 

    } 

    @Override 
    @Bean 
    public AuthenticationManager authenticationManagerBean() throws Exception { 
     return super.authenticationManagerBean(); 
    } 



    @Override 
    protected void configure(HttpSecurity http) throws Exception { 
     // @formatter:off 
     http 
       .authorizeRequests() 
       .antMatchers("/login", "/").permitAll() 
       .and() 
       .formLogin() 
       .loginPage("/login") 
       .permitAll() 

       .and() 
       .csrf().disable() 
       .requestMatchers().antMatchers("/login", "/oauth/authorize", "/oauth/confirm_access") 
       .and() 
       .authorizeRequests().anyRequest().authenticated() 
     ; 

     // @formatter:on 
    } 


    @Bean 
    public PasswordEncoder passwordEncoder() { 
     return new BCryptPasswordEncoder(11); 
    } 


} 

Zuul Сервер:

security: 
    user: 
    password: none 
    oauth2: 
    client: 
     accessTokenUri: http://localhost:9999/uaa/oauth/token 
     userAuthorizationUri: http://localhost:9999/uaa/oauth/authorize 
     clientId: kksdi2388wmkwe 
     clientSecret: kksd23isdmsisdi2 
     resource: 
     userInfoUri: http://localhost:9999/uaa/user 


zuul: 
    routes: 
    auth-server: /auth-server/** 
    resource: /resource/** 

Zuul приложение:

@SpringBootApplication 
@EnableZuulProxy 
@EnableOAuth2Sso 
public class Application extends WebSecurityConfigurerAdapter { 

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

    @Override 
    public void configure(HttpSecurity http) throws Exception { 


    http 
      .logout().permitAll() 
      .and().authorizeRequests() 
      .mvcMatchers("/login/**").permitAll() 
         .anyRequest().authenticated(); 
    } 


} 

проблема:

после авторизовались:

доступ: AuthServer "http://localhost:8080/auth-server/uaa/user" и "http://localhost:8080/api/test"


, но когда access_token истек, может Oly доступ: "http://localhost:8080/api/test", при доступе к AuthServer "http://localhost:8080/auth-server/uaa/user" встретились error--

<error_description> 
Access token expired: 530c9247-2331-47e3-a6c0-ed61814642f5 
</error_description> 
<error>invalid_token</error> 

, и я не могу получить access_token из заголовка запроса,

Как разрешить?

ответ

0

Перед тем, как проверить сервер приложений сервера OAUTH и время и часовой пояс сервера приложений клиента, если они разделены на две разные машины.

Конфигурация сервера OAUTH У меня есть некоторые проблемы. Сам OAuth-сервер защищен 'BASIC ACCESS аутентичности': https://en.wikipedia.org/wiki/Basic_access_authentication

Который работает с маркером на его запросы заголовков: 'Authorization': Basic = Base64.encode (имя пользователя +»«+ пароль). Если вы пропустите этот токен, вы не сможете получить доступ к какой-либо конечной точке на сервере OAUTH. Mine прекрасно работает, вы можете проверить его:

@Override 
protected void configure(HttpSecurity http) throws Exception { 
    // @formatter:off 
    http.formLogin().loginPage("/login").permitAll() 
      .and().requestMatchers().antMatchers("/login", "/oauth/authorize", "/oauth/confirm_access", "/fonts/**", "/css/**") 
      .and().authorizeRequests().antMatchers("/fonts/**", "/css/**").anonymous().anyRequest().authenticated(); 
    // @formatter:on 
} 

А почему у вас отключил защиту CSRF?

+0

Привет, спасибо Ваш ответ, для того чтобы упростить проблемы, CSRF был disabled.I может войти в систему, а также доступ: 'AuthServer«HTTP: // локальный : 8080/auth-server/uaa/user "' by zuul proxy and' "http: // localhost: 8080/api/test", но после 120-х годов срок действия access_token истек, он может только "http: // localhost: 8080/api/test "', но 'AuthServer" http: // localhost: 8080/auth-server/uaa/user "' не может быть доступен.и ошибка: «Истек токен доступа: a09e4446-a01c-4e8a-86c4-635c1a30c4fb invalid_token' –

+0

У меня тоже есть эта проблема! access_token не обновляется, и мне нужно повторно отправить authorization_code, чтобы получить новый access_token. –

+0

Извините, что слышал ... Я столкнулся с этой проблемой два дня ... Я использовал JWT без этой проблемы, но вместо customTokenStore или InMemoryTokenStore возникает проблема. –

0

это мой маркер конфигурации магазина:

@Autowired 
    @Qualifier("datasource") 
    private DataSource dataSource; 

    @Bean 
    public TokenStore tokenStore() { 
     return new JdbcTokenStore(dataSource); 
    } 


    @Bean 
    protected AuthorizationCodeServices authorizationCodeServices() { 
     return new JdbcAuthorizationCodeServices(dataSource); 
    } 

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

    @Override 
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) 
      throws Exception { 
     endpoints.authorizationCodeServices(authorizationCodeServices()) 
       .authenticationManager(authenticationManager).tokenStore(tokenStore()) 
       .approvalStoreDisabled(); 
    } 
+0

jdbcTokenStore? когда токен доступа еще истек. может ли он получить доступ к данным AuthServer или ResourceServer? –

+0

да, это работает, вы должны добавить некоторую конфигурацию в свой ресурс. –

+0

Я не знаком с jdbc, я пытаюсь хранить токен mongodb, но не устанавливаю 'authorizationCodeService' и' assertStoreDisabled() ',, вы можете попробовать отменить set' authorizationCodeService', чтобы узнать, работает ли он? –