【问题标题】:How to validate a token from a OAuth server?如何验证来自 OAuth 服务器的令牌?
【发布时间】:2017-06-10 19:21:56
【问题描述】:

我创建了一个拥有授权和资源服务器的 Spring Boot 应用程序,这是我的主类:

@SpringBootApplication
@EnableResourceServer
@EnableAuthorizationServer
public class OauthServerApplication {

    public static void main(String[] args) {
        SpringApplication.run(OauthServerApplication.class, args);
    }
}

这是我的 application.yml:

security:
  user:
    name: guest
    password: guest123
  oauth2:
    client:
      client-id: trustedclient
      client-secret: trustedclient123
      authorized-grant-types: authorization_code,refresh_token,password
      scope: openid

要生成访问令牌,我只执行这个 url (POST):

http://trustedclient:trustedclient123@localhost:8080/oauth/token?username=guest&password=guest123&grant_type=password

返回:

{
  "access_token": "f2e722b7-3807-4a27-9281-5b28b7bd3d0d",
  "token_type": "bearer",
  "refresh_token": "f96d472c-8259-42e2-b939-4963dfeeb086",
  "scope": "openid"
}

现在我需要知道如何验证令牌是否正确,有什么帮助吗?

【问题讨论】:

  • 为什么您响应令牌请求获得的令牌无效?
  • 我不是说无效,我想把这个token交给客户端,然后验证token是否正确,如果无效我会拒绝请求

标签: spring-boot oauth-2.0


【解决方案1】:

您有多种可能性,您可以:

1) 将令牌存储在TokenStore 中,并在资源服务器的授权服务器上打开一个安全的验证令牌端点。

2)如果授权服务器和资源服务器可以共享一个数据源,(在您的情况下这很容易,因为两者都在同一个应用程序中)。它们都可以使用JdbcTokenStore 指向同一个数据库,并且资源服务器可以直接检查此令牌存储中令牌的有效性。看这个教程:Spring REST API + OAuth2 + AngularJS

3) 您可以将签名的 JWT 令牌与 JwtTokenStoreJwtAccessTokenConverter 一起使用。看这个教程:Using JWT with Spring Security OAuth

这两个教程都基于以下 github 存储库:https://github.com/Baeldung/spring-security-oauth

【讨论】:

    【解决方案2】:

    为了验证令牌,我通常使用 Authorization 标头中的访问令牌向 /user 发出请求。

    在 Spring Oauth 服务器中,我添加了以下端点。

    @GetMapping("/user")
    public Principal user(Principal user) {
        return user;
    }
    

    这就是发送给它的请求。

    GET http://localhost:8443/v1/auth/user
    Authorization: Bearer some-access-token
    

    这具有返回通常需要的用户对象的额外好处。所以一石两鸟。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-31
      • 2012-08-28
      • 2019-02-15
      • 2016-01-27
      • 2013-04-22
      • 1970-01-01
      • 2017-10-30
      相关资源
      最近更新 更多