Springboot + Oauth2-无法找到访问令牌

时间:2020-06-14 11:19:11

标签: spring-boot spring-security oauth-2.0 access-token spring-security-oauth2

我正在找不到调用我的 http://localhost:8081/oauth/token 控制台中打印的令牌9ccc7637-04af-469d-93b8-209cbfac4e49 的访问令牌。请找到所附图片以供参考。

我竭尽所能,但可以找到问题所在。

在我单击 oauth \ token 的位置,令牌详细信息正在存储在数据库中,但仍然会引发错误。

无法使用创建的访问令牌进行API调用。

请找到以下代码并纠正我。

Configuration
public class AppConfig {

    @Value("${spring.datasource.url}")
    private String datasourceUrl;

    @Value("${spring.datasource.driver-class-name}")
    private String dbDriverClassName;

    @Value("${spring.datasource.username}")
    private String dbUsername;

    @Value("${spring.datasource.password}")
    private String dbPassword;

    @Bean
    public DataSource dataSource() {
        final DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(dbDriverClassName);
        dataSource.setUrl(datasourceUrl);
        dataSource.setUsername(dbUsername);
        dataSource.setPassword(dbPassword);
        return dataSource;
    }

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


@Configuration
@EnableAuthorizationServer
public class OAuthConfiguration extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private final AuthenticationManager authenticationManager;
    @Autowired
    private final BCryptPasswordEncoder passwordEncoder;
    @Autowired
    private final UserDetailsService userService;

    @Autowired
    private TokenStore tokenStore;


    public OAuthConfiguration(AuthenticationManager authenticationManager, BCryptPasswordEncoder passwordEncoder, UserDetailsService userService) {
        this.authenticationManager = authenticationManager;
        this.passwordEncoder = passwordEncoder;
        this.userService = userService;
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
         clients
         .inMemory()
         .withClient("my-trusted-client")
         .authorizedGrantTypes("password", "authorization_code", "refresh_token", "implicit")
         .scopes("read","write","trust")
         .resourceIds("oauth2-resource")
         .accessTokenValiditySeconds(50)
         .refreshTokenValiditySeconds(1000)
         .secret(passwordEncoder.encode("secret"));
    }

    @Override
    public void configure(final AuthorizationServerEndpointsConfigurer endpoints) {
        endpoints
                .userDetailsService(userService)
                .authenticationManager(authenticationManager)
                .tokenStore(tokenStore);
    }



    @Bean
    public OAuth2AccessDeniedHandler oauthAccessDeniedHandler() {
        return new OAuth2AccessDeniedHandler();
    }


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



}


@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {


    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()

                .requestMatchers().antMatchers("/**").and()
                .authorizeRequests()
                .antMatchers("/**").access("hasRole('ADMIN') or hasRole('USER')")
                .and().exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler());
    }

}

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    UserDetailsService userDetails;

    @Autowired
    DataSource dataSource;


      @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
          auth.jdbcAuthentication().dataSource(dataSource).
             usersByUsernameQuery("select username, password, enabled from users where username=?").
             authoritiesByUsernameQuery("select username, roles from users where username=?");

          }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
        .authorizeRequests()
            .antMatchers("/oauth/token").permitAll()
            .antMatchers("/**").authenticated()
            .anyRequest().authenticated()
            .and()
        .httpBasic()
            .and()
        .csrf().disable();
    }

    @Bean
    public DaoAuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
        provider.setPasswordEncoder( bCryptPasswordEncoder() );
        provider.setUserDetailsService(userDetails);
        return provider;
      }

    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
      }


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


    /*
     * @Autowired // here is configuration related to spring boot basic public void
     * configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
     * auth.inMemoryAuthentication() // static users
     * .withUser("User").password(bCryptPasswordEncoder().encode("User")).
     * roles("USER") .and()
     * .withUser("Admin").password(bCryptPasswordEncoder().encode("Admin[")).
     * roles("ADMIN"); }
     */

      @Autowired
        public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
            auth.userDetailsService(userDetails)
                    .passwordEncoder(bCryptPasswordEncoder());
        }
}

控制台错误:

enter image description here

enter image description here

0 个答案:

没有答案