Oauth“在SecurityContext中找不到身份验证对象”

时间:2014-10-24 20:52:34

标签: java spring oauth spring-security

我正在使用this code作为指南,使用Spring Server设置Oauth安全配置。我已经将ResourceServerConfigurationAdapter修改为这样,基本上添加了一个类以允许匿名访问我的API路径。

protected static class ResourceServer extends
        ResourceServerConfigurerAdapter {

    // This method configures the OAuth scopes required by clients to access
    // all of the paths in the video service.
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();

        http.authorizeRequests()
            .antMatchers("/oauth/token").anonymous();

        http.authorizeRequests()
            .antMatchers(HttpMethod.GET,"/gift/**").anonymous();

        //Other additions will be made that require username/password combinations, but I want to start simple first
    }

我通过网络浏览器访问我服务器的/gift文件夹,看到此错误:

<oauth>
    <error_description>
        An Authentication object was not found in the SecurityContext
    </error_description>
    <error>unauthorized</error>
</oauth>

我的服务器控制台日志显示了这个:

2014-10-24 16:48:32.895  WARN 8908 --- [io-8443-exec-10] o.s.c.s.ResourceBundleMessageSource      : ResourceBundle [messages] not found for MessageSource: Can't find bundle for base name messages, locale en_US
2014-10-24 16:48:32.895  INFO 8908 --- [io-8443-exec-10] o.s.b.a.audit.listener.AuditListener     : AuditEvent [timestamp=Fri Oct 24 16:48:32 EDT 2014, principal=<unknown>, type=AUTHENTICATION_FAILURE, data={message=An Authentication object was not found in the SecurityContext, type=org.springframework.security.authentication.AuthenticationCredentialsNotFoundException}]

将错误引导至this site,即

  

这是第一次出现的另一个调试级别消息   匿名用户尝试访问受保护的资源,但是当您   您的过滤器链中没有AnonymousAuthenticationFilter   配置。

但是,由于我永远无法建立连接,因此似乎存在根本性错误。此外,我没有丝毫的线索,我会在我的过滤器链配置中放置AnonymousAuthenticationFilter,因为我不知道哪里甚至包括过滤器链配置。我该怎么办?

2 个答案:

答案 0 :(得分:1)

您可以尝试以下代码:

    @Override
public void configure(HttpSecurity http) throws Exception {
    http.csrf().disable()
        .anonymous().and()
        .authorizeRequests()
        .antMatchers("/oauth/token").permitAll()
        .antMatchers(HttpMethod.GET,"/gift/**").permitAll();
}

答案 1 :(得分:0)

您需要在web.xml文件中添加以下过滤器,并尝试使用新的tomcat

<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>        
<listener>
  <listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
  </listener>