You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring OAuth2授权服务器:/info/**端点带Token仍返回401问题

Spring OAuth2 授权服务器端点认证失败(401未授权)

我搭建了Spring OAuth2 Authorization Server并配置了Rest Controller,端点为/info/**。设置为permitAll时能正常访问,但配置为需认证(authenticated)并携带Token访问时,返回401未授权。

我的SecurityFilterChain配置代码

@Bean
public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {

    OAuth2AuthorizationServerConfigurer authorizationServerConfigurer = new OAuth2AuthorizationServerConfigurer();

    authorizationServerConfigurer.tokenIntrospectionEndpoint(a ->
            a.authenticationProvider(new CustomOAuth2TokenIntrospectionAuthenticationProvider(authorizationService())));
    httpSecurity.apply(authorizationServerConfigurer);


    httpSecurity
            .authorizeHttpRequests(requests -> requests
                    .requestMatchers(new AntPathRequestMatcher("/info/**")).authenticated()
                    .anyRequest().permitAll())
            .cors(AbstractHttpConfigurer::disable)
            .httpBasic(withDefaults())
            .formLogin(withDefaults())
            .addFilterBefore(logRequestResponseFilter, UsernamePasswordAuthenticationFilter.class)
            .csrf(AbstractHttpConfigurer::disable)
            ;
    return httpSecurity.build();
}

相关日志信息

2024-05-09T00:00:26.883+08:00 DEBUG 14264 --- [               ] o.s.web.servlet.DispatcherServlet        : Completed 401 UNAUTHORIZED
2024-05-09T00:00:26.890+08:00 DEBUG 14264 --- [               ] o.s.security.web.FilterChainProxy        : Securing GET /error?userId=5532f935-ca36-4768-87fa-b65fe8741bbf
2024-05-09T00:00:26.893+08:00 DEBUG 14264 --- [               ] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController#error(HttpServletRequest)
2024-05-09T00:00:26.894+08:00 DEBUG 14264 --- [               ] o.s.security.web.FilterChainProxy        : Secured GET /error?userId=5532f935-ca36-4768-87fa-b65fe8741bbf
2024-05-09T00:00:26.895+08:00 DEBUG 14264 --- [               ] o.s.web.servlet.DispatcherServlet        : "ERROR" dispatch for GET "/error?userId=5532f935-ca36-4768-87fa-b65fe8741bbf", parameters={masked}
2024-05-09T00:00:26.895+08:00 DEBUG 14264 --- [               ] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController#error(HttpServletRequest)
2024-05-09T00:00:26.904+08:00 DEBUG 14264 --- [               ] o.s.w.s.m.m.a.HttpEntityMethodProcessor  : Using 'application/json', given [*/*] and supported [application/json, application/*+json]
2024-05-09T00:00:26.904+08:00 DEBUG 14264 --- [               ] o.s.w.s.m.m.a.HttpEntityMethodProcessor  : Writing [{timestamp=Thu May 09 00:00:26 SGT 2024, status=401, error=Unauthorized, path=/info/}]
2024-05-09T00:00:26.910+08:00 DEBUG 14264 --- [               ] o.s.web.servlet.DispatcherServlet        : Exiting from "ERROR" dispatch, status 401
2024-05-09T00:00:26.911+08:00 DEBUG 14264 --- [               ] o.s.s.w.a.AnonymousAuthenticationFilter  : Set SecurityContextHolder to anonymous SecurityContext
2024-05-09T00:00:26.911+08:00  INFO 14264 --- [               ] c.e.O.filter.LogRequestResponseFilter    : LoggingFilterRequestResponse: Servlet Path: /error Request parameter [Key: userId, Value: 5532f935-ca36-4768-87fa-b65fe8741bbf]  Response status code: 401 Response Body: {"timestamp":"2024-05-08T16:00:26.902+00:00","status":401,"error":"Unauthorized","path":"/info/"}

问题排查与解决方案

你的配置缺少OAuth2资源服务器的认证过滤器——Spring OAuth2 Authorization Server默认只处理授权相关端点,不会自动验证API请求的Token,需要添加资源服务器配置来解析和验证请求中的Token:

1. 引入资源服务器依赖

如果项目还未添加,先引入依赖(以Maven为例):

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>

2. 修改SecurityFilterChain配置

添加资源服务器支持,根据Token类型选择对应配置:

@Bean
public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {

    OAuth2AuthorizationServerConfigurer authorizationServerConfigurer = new OAuth2AuthorizationServerConfigurer();

    authorizationServerConfigurer.tokenIntrospectionEndpoint(a ->
            a.authenticationProvider(new CustomOAuth2TokenIntrospectionAuthenticationProvider(authorizationService())));
    httpSecurity.apply(authorizationServerConfigurer);

    // 添加资源服务器配置:如果使用JWT Token
    httpSecurity.oauth2ResourceServer(oauth2 -> oauth2.jwt(withDefaults()));

    // 如果使用引用式Token(Opaque Token),替换上面的JWT配置为以下内容
    // httpSecurity.oauth2ResourceServer(oauth2 -> oauth2.opaqueToken(withDefaults()));

    httpSecurity
            .authorizeHttpRequests(requests -> requests
                    .requestMatchers(new AntPathRequestMatcher("/info/**")).authenticated()
                    .anyRequest().permitAll())
            .cors(AbstractHttpConfigurer::disable)
            .httpBasic(withDefaults())
            .formLogin(withDefaults())
            .addFilterBefore(logRequestResponseFilter, UsernamePasswordAuthenticationFilter.class)
            .csrf(AbstractHttpConfigurer::disable);

    return httpSecurity.build();
}

3. 配置Token验证参数

在application.yml或application.properties中添加对应配置:

  • 若使用JWT Token:
spring:
  security:
    oauth2:
      resourceserver:
        jwt:
          issuer-uri: http://localhost:8080/oauth2/token  # 你的授权服务器地址
          # 也可直接配置公钥路径
          # public-key-location: classpath:public.key
  • 若使用引用式Token:
spring:
  security:
    oauth2:
      resourceserver:
        opaque-token:
          introspection-uri: http://localhost:8080/oauth2/introspect
          client-id: 你的客户端ID
          client-secret: 你的客户端密钥

4. 检查请求Token携带

确保请求头包含正确的Token:Authorization: Bearer <你的Token>,同时确认Token未过期、拥有访问/info/**端点的权限。

内容的提问来源于stack exchange,提问作者RedBlue

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 14:04:55