Spring oauth2 InsufficientAuthenticationException

时间:2014-12-05 07:09:01

标签: spring spring-mvc spring-security spring-security-oauth2

具有以下基于web.xml类的配置:

public class WebApp extends AbstractDispatcherServletInitializer {

    @Override
    protected WebApplicationContext createServletApplicationContext() {
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.scan(ClassUtils.getPackageName(getClass()));
        return context;
    }

    @Override
    protected String[] getServletMappings() {
        return new String[]{"/api/*"};
    }

    @Override
    protected WebApplicationContext createRootApplicationContext() {
        return null;
    }

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        super.onStartup(servletContext);
        DelegatingFilterProxy filter = new DelegatingFilterProxy("springSecurityFilterChain");
        filter.setServletContext(servletContext);
        filter.setContextAttribute("org.springframework.web.servlet.FrameworkServlet.CONTEXT.dispatcher");
        servletContext.addFilter("springSecurityFilterChain", filter).addMappingForUrlPatterns(null, false, "/api/*");
    }

}

当尝试访问其中一个oeuth端点时,我得到以下结果:

curl -u core:secret "http://localhost:8081/api/oauth/token?client_id=core&grant_type=password&username=user&password=123&response_type=token&scope=admin" 

{"error":"unauthorized","error_description":"There is no client authentication. Try adding an appropriate authentication filter."}%

奇怪的是,当我将servlet的映射从/ api / *更改为/它按预期工作时。所以有些事情一定是错的,但我什么都不知道呢?

2 个答案:

答案 0 :(得分:4)

您可以在FrameworkHandlerMapping中设置前缀,例如通过AuthorizationServerEndpointsConfigurer

@Configuration
@EnableAuthorizationServer
public class OAuth2Config extends AuthorizationServerConfigurerAdapter {
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        String prefix = "/api";
        endpoints.prefix(prefix);
    }
}

答案 1 :(得分:0)

此问题的解决方案之一可能是在security.xml中检查您的身份验证服务器的模式设置:

    <http pattern="/oauth/token"
      create-session="stateless"
      authentication-manager-ref="clientAuthenticationManager"
      use-expressions="true"
      xmlns="http://www.springframework.org/schema/security">

如果你的servlet回答请求的/api/*是正常的,我想你需要检查你的模式,并从认证服务器模式中的链接中删除api:更改{{1} } pattern="/api/oauth/token"