Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Spring安全OAuth stackoverflowException_Java_Spring_Spring Security_Oauth 2.0 - Fatal编程技术网

Java Spring安全OAuth stackoverflowException

Java Spring安全OAuth stackoverflowException,java,spring,spring-security,oauth-2.0,Java,Spring,Spring Security,Oauth 2.0,我想将Spring安全性与OAuth和JWT令牌一起使用。 我目前的配置是: @Configuration @EnableResourceServer public class OAuth2ServerConfig { @Configuration @EnableWebSecurity protected static class ResourceServer extends WebSecurityConfigurerAdapter { @Override publi

我想将Spring安全性与OAuth和JWT令牌一起使用。 我目前的配置是:

@Configuration
@EnableResourceServer
public class OAuth2ServerConfig {

@Configuration
@EnableWebSecurity
protected static class ResourceServer extends WebSecurityConfigurerAdapter {
    
    @Override
    public void configure(HttpSecurity http) throws Exception {
        // @formatter:off   
        http.anonymous().disable()
        .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .and()
            .exceptionHandling()
            .accessDeniedHandler(accessDeniedHandler()) // handle access denied in general (for example comming from @PreAuthorization
            .authenticationEntryPoint(entryPointBean()) // handle authentication exceptions for unauthorized calls.
            .and()
        .authorizeRequests()
            // only allow this three endpoint to NOT be authenticated.
            .antMatchers(HttpMethod.POST, "/users").permitAll()
            .antMatchers(HttpMethod.POST, "/users/authenticate").permitAll()
             .antMatchers(HttpMethod.GET, "/users/inviationCode/{code}").permitAll()
            .antMatchers(HttpMethod.POST, "/**").fullyAuthenticated()
            .antMatchers(HttpMethod.GET, "/**").fullyAuthenticated()
            .antMatchers(HttpMethod.PUT, "/**").fullyAuthenticated()
            .antMatchers(HttpMethod.DELETE, "/**").fullyAuthenticated()
            .antMatchers(HttpMethod.OPTIONS, "/**").fullyAuthenticated()
            .and()
            .addFilterBefore(filterBean(), AbstractPreAuthenticatedProcessingFilter.class)
            .requestMatcher(new NegatedRequestMatcher(new AntPathRequestMatcher("/oauth/**")))
            .authorizeRequests().anyRequest().authenticated().expressionHandler(new OAuth2WebSecurityExpressionHandler())
            .and()
        .csrf().disable(); // for chrome/FF plugins to work. for now we shouldn't face any problem since there is no point that JS can be injected into our page...
        // @formatter:on
    }
    
    @Bean(name="authenticationManager")
    @Override
    public AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManagerBean();
    }
    
    @Bean
    @Autowired
    AccessDeniedHandler accessDeniedHandler() {
        return new AccessDeniedExceptionHandler();
    }
    
    @Bean
    @Autowired
    AuthenticationEntryPoint entryPointBean() {
        return new UnauthorizedEntryPoint();
    }
    
    @Bean
    @Autowired
    GenericFilterBean filterBean() {
        return new XAuthTokenFilter();
    }
    
    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
    
    @Bean(name="userAuthenticationManager")
    public UserAuthenticationService userAuthenticationManager() throws Exception {
        return new UserAuthenticationService();
    }

}


@Configuration
@EnableAuthorizationServer
public static class OAuth2Config extends AuthorizationServerConfigurerAdapter {

    @Autowired
    @Qualifier("authenticationManager")
    private AuthenticationManager authenticationManager;
    
    @Autowired
    @Qualifier("restDataSource")
    private BasicDataSource restDataSource;

    @Bean
    public JwtAccessTokenConverter accessTokenConverter() {
        return new JwtAccessTokenConverter();
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
        oauthServer.tokenKeyAccess("isAnonymous() || hasAuthority('ROLE_TRUSTED_CLIENT')").checkTokenAccess(
                "hasAuthority('ROLE_TRUSTED_CLIENT')");
    }

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

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
            .withClient("test")
                .authorizedGrantTypes("client_credentials", "password")
                .authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
                .scopes("read", "write")
                .secret("secret");
    }

  }
}
这些配置基于官方的spring 我现在面临的问题是,每当我尝试使用此url获取令牌时:

我得到以下错误:

java.lang.StackOverflowError
at org.apache.commons.logging.impl.Jdk14Logger.isDebugEnabled(Jdk14Logger.java:214)
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:144)
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter$AuthenticationManagerDelegator.authenticate(WebSecurityConfigurerAdapter.java:427)
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:177)
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter$AuthenticationManagerDelegator.authenticate(WebSecurityConfigurerAdapter.java:427)
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:177)
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter$AuthenticationManagerDelegator.authenticate(WebSecurityConfigurerAdapter.java:427)
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:177)
这似乎是身份验证过程中的一个循环,但老实说,我可以找到它的根源。 我想使用的流程如下:

  • 用户请求传递用户名、密码和客户端的令牌(可能在base64中)。(方法岗)
  • 正在对用户进行身份验证
  • 向用户返回一个JWT令牌
  • 用户在报头中携带令牌
有人能就适当的配置提供建议吗


Best

发现了问题,它是针对身份验证管理器的。 这是我的工作配置:

@Configuration
@ComponentScan
@EnableResourceServer
@Import({SecurityConfig.class})
public class OAuth2ServerConfig {

@Configuration
@EnableAuthorizationServer
protected static class OAuth2Config extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;

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

    @Bean
    public JwtAccessTokenConverter accessTokenConverter() {
        return new JwtAccessTokenConverter();
    }

    @Bean
    public CustomJwtTokenStore tokenStore() {
        return new CustomJwtTokenStore();
    }

//      @Bean
//      public JdbcTokenStore tokenStore() {
//          return new JdbcTokenStore(datasource);
//      }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
        oauthServer.tokenKeyAccess("isAnonymous() || hasAuthority('ROLE_TRUSTED_CLIENT')").checkTokenAccess(
                "hasAuthority('ROLE_TRUSTED_CLIENT')");
    }

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

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
            .withClient("my-trusted-client")
                .authorizedGrantTypes("password", "authorization_code", "refresh_token", "implicit")
                .authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
                .scopes("read", "write", "trust")
                .accessTokenValiditySeconds(60)
        .and()
            .withClient("my-client-with-registered-redirect")
                .authorizedGrantTypes("authorization_code")
                .authorities("ROLE_CLIENT")
                .scopes("read", "trust")
                .redirectUris("http://anywhere?key=value")
        .and()
            .withClient("my-client-with-secret")
                .authorizedGrantTypes("client_credentials", "password")
                .authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
                .scopes("read", "write")
                .secret("secret");
    }

}
}
使用安全配置:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private AuthenticationEntryPoint authenticationEntryPoint;

@Autowired
private AccessDeniedHandler accessDeniedHandler;

@Autowired
private GenericFilterBean filter;


@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/webjars/**", "/images/**", "/oauth/uncache_approvals", "/oauth/cache_approvals");
}

@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
    return super.authenticationManagerBean();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userAuthenticationManager()).passwordEncoder(passwordEncoder());
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
      .sessionManagement()
      .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
    .and()
      .exceptionHandling()
        .accessDeniedHandler(accessDeniedHandler) // handle access denied in general (for example comming from @PreAuthorization
        .authenticationEntryPoint(authenticationEntryPoint) // handle authentication exceptions for unauthorized calls.
    .and()
      .authorizeRequests()
        .antMatchers("/xxx/**").fullyAuthenticated()
        .antMatchers("/xxx/**").fullyAuthenticated()
        .antMatchers("/xxx/**").fullyAuthenticated()
     .and()
       .csrf().disable();;
}

@Bean
@Autowired
ApplicationListener<AbstractAuthenticationEvent> loggerBean() {
    return new org.springframework.security.authentication.event.LoggerListener();
}

@Bean
@Autowired
AccessDeniedHandler accessDeniedHandler() {
    return new AccessDeniedExceptionHandler();
}

@Bean
@Autowired
AuthenticationEntryPoint entryPointBean() {
    return new UnauthorizedEntryPoint();
}

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

@Bean(name="userAuthenticationManager")
public UserDetailsService userAuthenticationManager() throws Exception {
    return new UserServiceImpl();
}

@Bean
public UserService userService() {
    return new UserServiceImpl();
}   
}
@配置
@启用Web安全性
公共类SecurityConfig扩展了WebSecurity配置适配器{
@自动连线
私有身份验证入口点身份验证入口点;
@自动连线
私有AccessDeniedHandler AccessDeniedHandler;
@自动连线
私有泛型过滤器bean过滤器;
@凌驾
public void configure(WebSecurity web)引发异常{
忽略().antMatchers(“/webjars/**”,“/images/**”,“/oauth/uncache\u approvals”,“/oauth/cache\u approvals”);
}
@凌驾
@豆子
公共AuthenticationManager authenticationManagerBean()引发异常{
返回super.authenticationManagerBean();
}
@凌驾
受保护的无效配置(AuthenticationManagerBuilder auth)引发异常{
auth.userDetailsService(userAuthenticationManager()).passwordEncoder(passwordEncoder());
}
@凌驾
受保护的无效配置(HttpSecurity http)引发异常{
http
.会议管理()
.sessionCreationPolicy(sessionCreationPolicy.STATELESS)
.及()
.例外处理()
.accessDeniedHandler(accessDeniedHandler)//处理一般拒绝的访问(例如从@PreAuthorization提交)
.authenticationEntryPoint(authenticationEntryPoint)//处理未经授权调用的身份验证异常。
.及()
.授权请求()
.antMatchers(“/xxx/**”).fullyaauthenticated()
.antMatchers(“/xxx/**”).fullyaauthenticated()
.antMatchers(“/xxx/**”).fullyaauthenticated()
.及()
.csrf().disable();;
}
@豆子
@自动连线
ApplicationListener loggerBean(){
返回新的org.springframework.security.authentication.event.LoggerListener();
}
@豆子
@自动连线
AccessDeniedHandler AccessDeniedHandler(){
返回新的AccessDeniedExceptionHandler();
}
@豆子
@自动连线
AuthenticationEntryPoint entryPointBean(){
返回新的UnauthorizedEntryPoint();
}
@豆子
公共BCryptPasswordEncoder passwordEncoder(){
返回新的BCryptPasswordEncoder();
}
@Bean(name=“userAuthenticationManager”)
public UserDetails服务userAuthenticationManager()引发异常{
返回新的UserServiceImpl();
}
@豆子
公共用户服务用户服务(){
返回新的UserServiceImpl();
}   
}

这里有一个更详细的要点