无效的访问令牌Spring Boot资源服务器

时间:2018-07-18 20:36:40

标签: spring spring-boot oauth-2.0

我有一个Spring Boot资源服务器,像这样:

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
}

和这样的端点:

@RestController
public class TestResourceOne {

    private static final Logger log = Logger.getLogger(TestResourceOne.class);

    @RequestMapping(value = "/calcsqrt")
    public Double calcSqtr(@RequestParam("value") Double value) {
        return Math.sqrt(value);
    }

    @RequestMapping(value = "/sum")
    public Double calcSqtr(@RequestParam("value1") Double value1, @RequestParam("value2") Double value2) {
        return value1 + value2;
    }
}

我的授权服务器位于Azure AD中,因此当我将此终结点称为“ / calcsqrt”时,我会传递Azure生成的承载令牌。这是我的要求:

GET /serviceone/calcsqrt?value=3 HTTP/1.1
Host: localhost:8080
Authorization: Bearer MY_ACCESS_TOKEN_HERE
Cache-Control: no-cache
Postman-Token: ef5d493c-39f1-4bc4-9084-4ea510ac1255

但是我总是从春天得到以下错误:

{
    "error": "invalid_token",
    "error_description": "Invalid access token: MY_ACCESS_TOKEN_HERE"
}

1 个答案:

答案 0 :(得分:0)

似乎您的资源配置类错误。我已经实现了这样的资源配置

package com.ig.user.config;

import org.springframework.boot.autoconfigure.security.oauth2.resource.UserInfoTokenServices;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;

/**
 * @author Jai
 *
 */
@Configuration
@EnableResourceServer
@EnableWebSecurity
public class ResourceConfig extends ResourceServerConfigurerAdapter {

    private final String userInfoUri = "url";

    private final String clientId = "foo";

    @Override
    public void configure(final ResourceServerSecurityConfigurer resources) throws Exception {
        resources.resourceId("user");
    }

    @Override
    public void configure(final HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/api/v1/user/activate/**").permitAll()//
                .anyRequest().authenticated();
    }

    @Primary
    @Bean
    public UserInfoTokenServices tokenService() {
        final UserInfoTokenServices tokenService = new UserInfoTokenServices(userInfoUri, clientId);
        return tokenService;
    }
}

EDIT-1

  • userInfoUri 是提供此资源授权的URL
  • resourceId 对于每个资源服务器,我们必须创建一个resourceId,并且必须将相同的ID保留在您存储客户端详细信息的位置

希望它会帮助您