找不到令牌的访问令牌

时间:2018-12-17 08:10:17

标签: java spring spring-boot oauth-2.0

我使用postMan,输入请求地址http://localhost:8011/umrah/oauth/token?client_id=client_2&username=1234567&password=123456&grant_type=password&client_secret=123456,单击发送按钮,发生错误,在内存中工作正常,当我要使用Jdbc令牌存储时,想法控制台错误:无法找到访问令牌对于令牌,我找到了一些信息,但没有找到合适的解决方案。

POSTMAN request params

oauth_client_token table is null

console error

@Configuration
@EnableWebSecurity
@Slf4j
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Resource(name = "userService")
    private UserService userService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService).passwordEncoder(passwordEncoder());
    }


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

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // @formatter:off
        http
                .logout()
                .clearAuthentication(true)
                .and()
                .requestMatchers().anyRequest()
                .and()
                .authorizeRequests()
                .antMatchers("/oauth/*", "/webjars/**", "/resources/**", "/swagger-ui.html"
                        , "/swagger-resources/**", "/v2/api-docs", "index.html", "/logout"
                        , "/swagger","/user/loginIn").permitAll()
                .and()
                .csrf()
                .disable();
    }

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

}



@Configuration
public class OAuth2ServerConfig {

    private static final String DEMO_RESOURCE_ID = "order";

    @Configuration
    @EnableResourceServer
    protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

        @Override
        public void configure(ResourceServerSecurityConfigurer resources) {
            resources.resourceId(DEMO_RESOURCE_ID).stateless(true);
        }

        @Override
        public void configure(HttpSecurity http) throws Exception {
            // @formatter:off
            http
                    .logout()
                    .clearAuthentication(true)
                    .and()
                    // Since we want the protected resources to be accessible in the UI as well we need
                    // session creation to be allowed (it's disabled by default in 2.0.6)
                    .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
//                    .and()
//                    .requestMatchers().anyRequest()
                    .and()
                    .anonymous()
                    .and()
                    .authorizeRequests()
                    .antMatchers("/base/**", "/oauth/*", "/webjars/**", "/resources/**", "/swagger-ui.html"
                            , "/swagger-resources/**", "/v2/api-docs", "index.html", "/swagger/**","/user/loginIn").permitAll()
                    .anyRequest().authenticated()
                    .and()
                    .cors()
                    .and()
                    .csrf()
                    .disable();//配置order访问控制,必须认证过后才可以访问
            // @formatter:on
        }
    }

    @Configuration
    @EnableAuthorizationServer
    @Slf4j
    protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

        @Autowired
        AuthenticationManager authenticationManager;
        @Autowired
        RedisConnectionFactory redisConnectionFactory;

        @Autowired
        UserDetailsService userDetailsService;
//        @Autowired
//        @Qualifier("myMemoryTokenStore")
//        TokenStore myTokenStore;

        @Autowired
        private DataSource dataSource;

        @Bean // 声明TokenStore实现
        public TokenStore tokenStore() {
            return new JdbcTokenStore(dataSource);
        }

        @Bean
        public ClientDetailsService clientDetails() {
            return new JdbcClientDetailsService(dataSource);
        }

        @Override
        public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
            //配置两个客户端,一个用于password认证一个用于client认证
//            clients.inMemory().withClient("client_1")
////                    .resourceIds(DEMO_RESOURCE_ID)
//                    .authorizedGrantTypes("client_credentials")
//                    .scopes("select")
//                    .authorities("ROLE_ADMIN","ROLE_USER")
//                    .secret("123456")
//                    .and().withClient("client_2")
////                    .resourceIds(DEMO_RESOURCE_ID)
//                    .authorizedGrantTypes("password", "refresh_token")
//                    .scopes("select")
//                    .accessTokenValiditySeconds(1800)
//                    .refreshTokenValiditySeconds(3600)
//                    .authorities("ROLE_ADMIN","ROLE_USER")
//                    .secret("123456");


            clients.withClientDetails(clientDetails());
        }

        @Override
        public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
            endpoints
                    .tokenStore(tokenStore())
                    .authenticationManager(authenticationManager)
                    .userDetailsService(userDetailsService)
                    // 2018-4-3 增加配置,允许 GET、POST 请求获取 token,即访问端点:oauth/token
                    .allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST);


            // 配置TokenServices参数
            DefaultTokenServices tokenServices = (DefaultTokenServices) endpoints.getDefaultAuthorizationServerTokenServices();
            tokenServices.setTokenStore(endpoints.getTokenStore());
            tokenServices.setSupportRefreshToken(true);
            // 复用refresh token
            tokenServices.setReuseRefreshToken(true);
            tokenServices.setRefreshTokenValiditySeconds(3600);
            tokenServices.setClientDetailsService(endpoints.getClientDetailsService());
            tokenServices.setTokenEnhancer(endpoints.getTokenEnhancer());
            tokenServices.setAccessTokenValiditySeconds((int) TimeUnit.DAYS.toSeconds(1)); // 1天
            endpoints.tokenServices(tokenServices);

            super.configure(endpoints);

        }

        @Override
        public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
            //允许表单认证
            oauthServer.allowFormAuthenticationForClients();
        }
    }


    @FrameworkEndpoint
    public class LogoutEndpoint {
        @Qualifier("myMemoryTokenStore")
        @Autowired
        private TokenStore tokenStore;

        @RequestMapping(value = "/oauth/logout", method= RequestMethod.POST)
        @ResponseStatus(HttpStatus.OK)
        public void logout(HttpServletRequest request, HttpServletResponse response){
            String authHeader = request.getHeader("Authorization");
            if (authHeader != null) {
                String tokenValue = authHeader.replace("Bearer", "").trim();
                OAuth2AccessToken accessToken = tokenStore.readAccessToken(tokenValue);
                tokenStore.removeAccessToken(accessToken);
            }
        }
    }
}


@Service("userService")
@Slf4j
public class UserService implements UserDetailsService {
    @Resource(name = "service.UserService")
    private com.jolly.atplan.umrah.service.service.UserService userService;


    @Override
    public UserDetails loadUserByUsername(String loginId) throws UsernameNotFoundException {
        log.info("LoginID : {}",loginId);
        User user = userService.getUserByLoginId(loginId);

        if(Objects.isNull(user)){
            throw new UsernameNotFoundException("User " + loginId + " was not found in the database");
        }

        Collection<GrantedAuthority> grantedAuthorities = new ArrayList<>();
//        List<UserAuthority> authorityList = userAuthorityDao.getAuthorityListByUser(loginId);
//        for (UserAuthority authority : authorityList) {
//            GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(authority.getAuthority());
//            grantedAuthorities.add(grantedAuthority);
//        }

        //返回一个SpringSecurity需要的用户对象
        return new org.springframework.security.core.userdetails.User(
                user.getLoginId(),
                user.getPwd(),
                grantedAuthorities);
    }
}

1 个答案:

答案 0 :(得分:0)

已经在工作,我重写了JdbcTokenStore的readAccessToken方法,感谢Rest service with oauth2: Failed to find access token for token

`public class JdbcTokenStores extends JdbcTokenStore {
    private static final Log LOG = LogFactory.getLog(JdbcTokenStores.class);

    public JdbcTokenStores(DataSource dataSource) {
        super(dataSource);
    }

    @Override
    public OAuth2AccessToken readAccessToken(String tokenValue) {
        OAuth2AccessToken accessToken = null;

        try {
            accessToken = new DefaultOAuth2AccessToken(tokenValue);
        }
        catch (EmptyResultDataAccessException e) {
            if (LOG.isInfoEnabled()) {
                LOG.info("Failed to find access token for token "+tokenValue);
            }
        }
        catch (IllegalArgumentException e) {
            LOG.warn("Failed to deserialize access token for " +tokenValue,e);
            removeAccessToken(tokenValue);
        }

        return accessToken;
    }
}`