Baeldung / spring-security-oauth

Just Announced - "Learn Spring Security OAuth":
http://bit.ly/github-lsso
MIT License
1.99k stars 1.95k forks source link

Failed to find access token for token #51

Closed junneyang closed 3 years ago

junneyang commented 7 years ago

curl "http://localhost:8081/spring-security-oauth-server/employee" -H "Authorization: Bearer $TOKEN" -si

return 302 Location: http://localhost:8081/spring-security-oauth-server/login

log says: 2017-09-13 10:42:49.381 INFO 2157 --- [nio-8081-exec-5] o.s.s.o.p.token.store.JdbcTokenStore : Failed to find access token for token 810917c4-bb75-431b-96aa-974685d907cd

thanks for your help!

eugenp commented 7 years ago

Thanks for the feedback @junneyang - it's on our internal list to deal with. Cheers, Eugen.

eugenp commented 7 years ago

Hey @junneyang - can you pull and give it a try now? Thanks, Eugen.

springapidev commented 6 years ago

Hi I have followed you. Everything works fine, only problem is that when I want to browse http://localhost:8080/api/v2/user/test/?access_token=216fdd45-bc15-46e1-93fd-917867b976b7, it says invalid access token in the browser and in the console, I see, INFO 6464 --- [nio-8080-exec-2] o.s.s.o.p.token.store.JdbcTokenStore : Failed to find access token for token fa8af88f-a264-4fac-ab72-8f675cf56ad5, I discover, token does not store in the database table like oauth_access_token, so I guess, resource server does not find in the database. Please help me to solve the issue.

`@Configuration @PropertySource({ "classpath:application.properties" }) @EnableAuthorizationServer public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter { @Autowired private Environment env;

@Autowired
@Qualifier("authenticationManagerBean")
private AuthenticationManager authenticationManager;

@Value("classpath:schema.sql")
private Resource schemaScript;

@Value("classpath:data.sql")
private Resource dataScript;

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

@Override
public void configure(final ClientDetailsServiceConfigurer clients) throws Exception {// @formatter:off
     clients.jdbc(dataSource());

/ clients.inMemory().withClient("client") .authorizedGrantTypes("password", "refresh_token") .authorities("ROLE_CLIENT", "ROLE_ANDROID_CLIENT") .scopes("read", "write", "trust") .resourceIds("oauth2-resource") .accessTokenValiditySeconds(5000) .secret("secret").refreshTokenValiditySeconds(50000);/

} // @formatter:on

@Override
public void configure(final AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
    endpoints.authenticationManager(authenticationManager)
            .allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST)
            .tokenEnhancer(new CustomTokenEnhancer());
}

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

@Bean
public TokenEnhancer tokenEnhancer() {
    return new CustomTokenEnhancer();
}

// JDBC token store configuration

@Bean
public DataSourceInitializer dataSourceInitializer() {
    final DataSourceInitializer initializer = new DataSourceInitializer();
    initializer.setDataSource(dataSource());
    initializer.setDatabasePopulator(databasePopulator());
    return initializer;
}

private DatabasePopulator databasePopulator() {
    final ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
    populator.addScript(schemaScript);
    populator.addScript(dataScript);
    return populator;
}

@Bean
public DataSource dataSource() {
    final DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName(env.getProperty("spring.datasource.driver-class-name"));
    dataSource.setUrl(env.getProperty("spring.datasource.url"));
    dataSource.setUsername(env.getProperty("spring.datasource.username"));
    dataSource.setPassword(env.getProperty("spring.datasource.password"));
    return dataSource;
}

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

@Bean
public CorsFilter corsFilter() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);
    config.addAllowedOrigin("*");
    config.addAllowedHeader("*");
    config.addAllowedMethod("OPTIONS");
    config.addAllowedMethod("GET");
    config.addAllowedMethod("POST");
    config.addAllowedMethod("PUT");
    config.addAllowedMethod("DELETE");
    source.registerCorsConfiguration("/**", config);
    return new CorsFilter(source);
}

//http://www.baeldung.com/spring-security-oauth-dynamic-client-registration `

eugenp commented 6 years ago

Hey @springapidev - quick question - is this happening on this codebase? I'm asking because that URL does't look like one of the URLs this project exposes.

springapidev commented 6 years ago

I have followed you, and it works fine in memory , when I want to use Jdbc token store, I see, the issue. I use IntelliJ IDE, Spring boot 1.5.8 and oauth 2, sweargar 2 for api doc.

kofidan commented 6 years ago

@eugenp : o.s.s.o.p.token.store.JdbcTokenStore : Failed to find access token for token 6ce7d163-a7a5-4734-86cb-c0c3d64fdd52. Aside the error above, is there a way to trap the current token 6ce7d163-a7a5-4734-86cb-c0c3d64fdd52. One of your articles shows how to retrieve all the tokens for a particular user...i will however be glaid if you could share a code on how to trap or intercept the current token.

lor6 commented 6 years ago

No longer reproducible. Closing.

icemagno commented 6 years ago

Please reopen because I've receiving this error too.

lor6 commented 6 years ago

@icemagno Sure. But please add the steps to reproduce or at least the exact modules you're running.

icemagno commented 6 years ago

Thanks for reopen. Actualy I have not receiving this error after set “permit all” for “/oauth/**” in my server. Can’t tell if it is somehow related. Anyway you can find my project at my repository “geoinfra/cerberus/guardiao”. It is a simple OAuth2 server. As I am very newbie in Spring I can’t tell exactly what I have done.

lor6 commented 6 years ago

Hey @icemagno So this isn't an issue with one of our projects?

If not, it's pretty difficult to look through someone's code and try to figure out what might be wrong. My suggestion is to post a more focused question on stack overflow.

Since our modules are working fine, you can start with the configuration here, then modify it for your needs.

icemagno commented 6 years ago

@lor6 hard to say. I'm following closer any tutorial and documentation and doble checked the code. I put a reference to this in https://github.com/spring-projects/spring-security-oauth/issues/788 because I don't know the real project owner. There you can see this came from 2016 and there is no solution yet.

More:

https://github.com/spring-projects/spring-security-oauth/issues/846

https://github.com/spring-projects/spring-security-oauth/issues/703

@reenolesigues Yes, "refresh_token" is right. Regarding the log "Failed to find access token for token", this is NORMAL during refresh since the new generated access token will be queried from the database to check for duplicates (hence the log). In case another entry is found that uses the same access token, it will be removed (see JdbcTokenStore.java line 144). If no record is found, the access token will be updated to the new generated access token.

ricardopt commented 6 years ago

I'm having exactly the same error on my logs but I'm able to send the access_token to the requester. Does anyone knows how to handle this error?

icemagno commented 6 years ago

@ricardopt actualy it's a warning.

ricardopt commented 6 years ago

@icemagno thanks for the correction I think the point here is solving the issue not the level of the log that it sends (and actually it's an INFO).

INFO 56692 --- [nio-8080-exec-5] o.s.s.o.p.token.store.JdbcTokenStore : Failed to find access token for token 704c867d-2289-4c11-af11-632598212c6d

icemagno commented 6 years ago

It is an info indeed. Thanks. And I have no Idea of how to solve it. I am starting to think we have to not care. As @reenolesigues said above it is just normal. I think these two words (INFO and FAILED) must not come at same time in a line. It is causing too stress for an info.

And about your access token it must be related to other problem because mine is working fine.

You can check it at my ‘geoinfra/cerberus/guardiao’ repository. Em português.

lor6 commented 6 years ago

Ok, guys @icemagno @ricardopt I'm trying to determine if this is an issue with this repository that I can reproduce or an error that's not happening in this project, but in your own code.

icemagno commented 6 years ago

Thanks @lor6 but as you can see in the links I ref above we have a lot of people having the same issue. Or it is a very common mistake or there is a problem in JdbcTokenStore.

skazaruddin commented 6 years ago

https://github.com/skazaruddin/spring-boot-oauth-postgres-jdbc-tokenstore

working fully

Schizhande commented 4 years ago

Add the following in your bootstrap files

security: oauth2: resource: userInfoUri: http://localhost:8089/v1/user

marlonalexis commented 4 years ago

I solved it by setting reuseRefreshTokens false in AuthorizationServerEndpointsConfigurer and setSupportRefreshToken true in DefaultTokenServices


    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        TokenEnhancerChain enhancerChain = new TokenEnhancerChain();
        enhancerChain.setTokenEnhancers(Arrays.asList(accessTokenConverter));
        endpoints.prefix("/ws/book").tokenStore(tokenStore).reuseRefreshTokens(false).exceptionTranslator(exception -> {
            return exceptionOAuth(exception);
        }).accessTokenConverter(accessTokenConverter).tokenEnhancer(enhancerChain).authenticationManager(authenticationManager);
    }

        @Bean
    @Primary
    public DefaultTokenServices tokenServices() {
        DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
        defaultTokenServices.setTokenStore(tokenStore());
        defaultTokenServices.setSupportRefreshToken(true);
        return defaultTokenServices;
    }`
akoua commented 4 years ago

It's give you this message because firstly token not present in the database when you generate it or when you generate token it 's call the method storeAccessToken() which call readAccessToken(String tokenValue) where emit EmptyResultDataAccessException when it null.

yellapusony229 commented 4 years ago

Hello Team,

Excellent Post !

I am trying to implement logout for oauth2 client application and my client application is a spring boot project with no frontend UI. I want include the logout logic in one of my API. And want to expose this API to call from other modules. I am using ADFS as my authorization server. I tried calling authorization-server logout endpoint by sending id-token-hint and post-redirect-uri and the logout is happening but still when I am trying to access my OAuth protected API's with old access token it considering as valid token.

Could you please provide some assistance on the above query. Thanks In Advance.

zhang19970916 commented 3 years ago

set : tokenServices.setReuseRefreshToken(false);

log is right

org.springframework.cloud spring-cloud-starter-oauth2 2.2.5.RELEASE 2.4.2
chaos2418 commented 3 years ago

Hi All, We tried to reproduce this issue again using oauth-authorization-server-legacy, oauth-resource-server-legacy-1, and oauth-ui-password-angular-legacy projects from this repository: Spring Security OAuth - Legacy

We didn't see any issues with the configs we have in these projects. On using the JDBC-backed token store, the authorization server was able to generate the token, and the resource server was able to get that validated. Although, we saw this log in the authorization server when a new access token gets generated: 2021-10-09 20:54:03.137 INFO 27632 --- [nio-8081-exec-1] o.s.s.o.p.token.store.JdbcTokenStore : Failed to find access token for token 7daa601c-e799-4bbe-ad9a-0c3bd33d542c

However, this is expected as JdbcTokenStore tries to search for an access token before storing it in the database. And in this case, as it won't find the same, it will print this INFO level log message.

As this is not an issue in our code we are closing this issue.

dkapil commented 3 years ago

Based on the comments from @chaos2418 , closing this one.