【问题标题】:Configure Spring Security with Hydra OAuth 2.0使用 Hydra OAuth 2.0 配置 Spring Security
【发布时间】:2018-01-24 15:02:30
【问题描述】:

我使用我的 Spring Boot 应用程序配置了一个 Hydra 实例。我刚刚使用注释@EnableResourceServer 将我的应用程序配置为资源服务器。因此,当我在请求中使用 Bearer 授权标头时,Spring 使用我在属性中指定的值:

security.oauth2.resource.user-info-uri=...

验证令牌是否有效。不幸的是,我没有找到 Hydra OAuth 2.0 (http://docs.hydra13.apiary.io/ / https://github.com/ory/hydra) 的这个 URL

【问题讨论】:

  • 与 Hydra 团队交谈后,他们完全遵循 OAuth2 规范,但大多数库倾向于围绕 Google 等主要 OAuth2 提供商进行设计。
  • 所以 Spring 除了 GET API 和 Hydra 提供了 POST API。

标签: spring-boot oauth-2.0 spring-security-oauth2


【解决方案1】:

首先:在 Ory Hydra 中配置您的资源服务器(您必须使用 client_credentials 和范围“hydra.introspect”将其添加到 Ory Hydra 以便能够请求令牌有效性):

$> hydra clients create --skip-tls-verify \
    --id my-rest-api \
    --secret mypwd \
    --grant-types client_credentials \
    --response-types token \
    --allowed-scopes hydra.introspect

第二:添加一个策略,让你的资源服务器请求令牌有效性。

$> hydra policies create --skip-tls-verify \
    --actions introspect \
    --description "Policy to introspect tokens from my api" \
    --allow \
    --id accesstoken_introsp-policy \
    --resources "rn:hydra:oauth2:tokens" \
    --subjects my-rest-api

第三:在 build.gradle 中添加 oauth2 依赖(如果是 maven,则添加 pom.xml):

编译 'org.springframework.security.oauth:spring-security-oauth2:2.2.1.RELEASE'

第四:配置 application.yml 以使用 Ory Hydra 自省端点获取令牌信息。

security:
  user:
    password: none
  oauth2:
    resource:
      token-info-uri: https://yourserver.com/oauth2/introspect
    client:
      client-id: my-rest-api
      client-secret: mypwd
      scope: [ "hydra.introspect" ]

第五:创建一个类来配置受访问令牌保护的url

@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

    @Autowired
    private RemoteTokenServices tokenServices;

    @Value("${security.oauth2.client.client-id}")
    private String clientId;

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.NEVER)
            .and()
            .authorizeRequests()
            .antMatchers(HttpMethod.OPTIONS).permitAll()
            .antMatchers("/api/v1/**").access("#oauth2.hasScope('my.desired.scope')")
            .and().exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler());
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.resourceId(clientId);
        tokenServices.setAccessTokenConverter(new OryHydraAccessTokenConverter());
        resources.tokenServices(tokenServices);
    }    
}

class OryHydraAccessTokenConverter extends DefaultAccessTokenConverter {
    @Override
    public OAuth2Authentication extractAuthentication(Map<String, ?> map) {
        OAuth2Authentication oAuth2Authentication = super.extractAuthentication(map);
        oAuth2Authentication.setDetails(map.get("ext"));
        return oAuth2Authentication;
    }
}

我需要一个自定义 AccessTokenConverter,因为我的同意应用程序向令牌添加了几个属性,我们需要映射所有这些属性。使用 Ory,我的属性位于“ext”属性下。这是一个示例访问令牌:

{
    "active": true,
    "scope": "my.desired.scope",
    "client_id": "my-mobile-app",
    "sub": "123121e",
    "exp": 1520948372,
    "iat": 1520944772,
    "iss": "https://yourserver.com",
    "ext": {
        "custom_prop1": 12321,
        "custom_prop2": "Name Surname",
        "custom_prop3": false
    }
}

最后一步:现在在您的控制器中,您可以自动装配为参数 Oauth2Authentication 对象。

@GetMapping("/api/v1/data")
public MyBean findDataById(OAuth2Authentication auth,
                           @RequestParam("id") String id) {
    OAuth2AuthenticationDetails oAuth2AuthenticationDetails = (OAuth2AuthenticationDetails) auth.getDetails();
    Map<String, Object> ext = (Map<String, Object>) oAuth2AuthenticationDetails.getDecodedDetails();
    return MyBean.builder().name("Name:"+ext.get("custom_prop1")).build();
}

【讨论】:

  • 你有做上述操作的 github 演示项目吗?
猜你喜欢
  • 1970-01-01
  • 2017-03-31
  • 2017-01-16
  • 2017-01-21
  • 1970-01-01
  • 1970-01-01
  • 2012-08-22
  • 2015-12-29
  • 2014-04-06
相关资源
最近更新 更多