如何使用Java Spring Boot框架在OAuth2.0中开发资源服务器?

时间:2020-04-10 22:10:40

标签: java spring-boot spring-security-oauth2

我正在尝试开发资源服务器,该资源服务器提供各种应用程序都会使用的API。 我正在使用java spring boot oauth2.0框架。这些应用程序是Web应用程序,它们是典型的符合OpenID Connect的Web应用程序,将使用授权代码流经过/ oauth / authorize端点。授予授权后,授权服务器会将访问令牌返回给应用程序。然后,应用程序使用访问令牌访问受保护的资源(例如API)。

我的重点是资源服务器本身。授权服务器位于云的其他外部。

从API的角度来看,这些是使用@RestController注释公开的REST API,如下所示-

@RestController
@RequestMapping("/myapi")

以下是我在资源服务器代码中的application.properties中拥有的属性-

spring.security.oauth2.resourceserver.jwt.jws-algorithm=RS256
spring.security.oauth2.resourceserver.jwt.issuer-uri=
spring.security.oauth2.resourceserver.jwt.jwk-set-uri=

主要类别如下-

SpringBootApplication
@EnableResourceServer
public class myApplication {
    public static void main(String[] args) {
        SpringApplication.run(myApplication .class, args);
    }
}

以及扩展ResourceServerConfigurerAdapter的类

@Configuration
public class OAuth2ResourceServer extends ResourceServerConfigurerAdapter 
{

    private static final String RESOURCE_ID = "resource-server-rest-api";
    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources.resourceId(RESOURCE_ID);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
            .antMatchers("/").permitAll()
            .antMatchers("/myapi/**").authenticated();
    }
}

每当我在Authorization标头中传递AccessToken时使用POSTMAN调用API时,都会收到invalid_token错误。 以下是日志的摘要-

DEBUG 25536 --- [nio-8080-exec-1] p.a.OAuth2AuthenticationProcessingFilter : Authentication request failed: error="invalid_token"

我已经验证了jwt令牌,它具有正确的声明和范围。

现在的问题是

  1. 从代码的角度来看,资源服务器中是否缺少某些东西?
  2. 应用程序属性正确还是需要添加更多内容?

资源服务器是否需要在运行时与授权服务器进行交互?如果是,在哪里指定?

0 个答案:

没有答案