简体   繁体   中英

Spring oauth2 InsufficientAuthenticationException

Having the following web.xml class based configuration:

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/*");
    }

}

When trying to access one of the oauth endpoints I'm getting the following result:

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."}%

The strange this is when I change the servlet's mapping from /api/* to / it works as expected. So something must be wrong but I'm clueless one what ?

You can set a prefix in the FrameworkHandlerMapping , eg through the AuthorizationServerEndpointsConfigurer :

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

One of the solutions to this problem might be checking your pattern settings of your Authentication Server in security.xml :

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

If it is alright when you make your servlet answer to request's /api/* , I guess you need to check your pattern, and remove api from your link in Authentication server pattern: change pattern="/api/oauth/token" to pattern="/oauth/token"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM