【问题标题】:Spring Boot- Invalid access token errorSpring Boot-无效的访问令牌错误
【发布时间】:2023-04-02 11:53:02
【问题描述】:

我目前正在开发一个简单的 Spring Boot 应用程序,我在其中传递 client_id 和 secret 来获取访问令牌,从而获得刷新和访问令牌。

但是当我尝试使用该令牌访问资源(我的 REST API)时(使用此 URL:curl -H "Authorization: Bearer ead8ba5d-88ad-4531-a821-db08bf25e888" localhost:8081/my-端点 ),它对我不起作用并给我以下错误-

{"error":"invalid_token","error_description":"无效的访问令牌:ead8ba5d-4531-db08bf2fe888"}

这就是我的端点的样子 -

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.security.Principal;

@RestController
@RequestMapping(path = "/my-end-point")
public class PrincipalResource {

    @RequestMapping(method = RequestMethod.POST)
    public Principal oauth(Principal principal) {
        /*
         * Translate the incoming request, which has an access token
         * Spring security takes the incoming request and injects the Java Security Principal
         * The converter inside Spring Security will handle the to json method which the Spring Security
         * Oauth client will know how to read
         *
         * The @EnableResourceServer on the application entry point is what makes all this magic happen.
         * If there is an incoming request token it will check the token validity and handle it accordingly
         *
         *
         */


        return principal;
    }
} `

【问题讨论】:

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


【解决方案1】:

确保在您的 AuthServerOAuth2Config security.allowFormAuthenticationForClients().checkTokenAccess("permitAll()");

@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {     
    security.allowFormAuthenticationForClients().checkTokenAccess("permitAll()");       
}

并通过向您的服务器发出 POST 请求开始生成一些令牌:localhost:yourport/oauth/token

例如:

http://localhost:8085/oauth/token?client_secret=secret&client_id=web&grant_type=password&username=kalaiselvan&password=kalaiselvan

它会返回令牌

 {
   "access_token": "8b816685-b7da-4996-a3e2-ff18b4538a2b",
   "token_type": "bearer",
   "refresh_token": "f458c09b-f739-4488-be0f-2b0e3c5a62d1",
   "expires_in": 637,
   "scope": "read"
 }

从响应数据中复制 access_token 并发出新的 POST 请求 http://localhost:8085/account

希望对你有帮助

【讨论】:

  • 基于我的发布请求响应 -> access_token 来自 localhost:8085/oauth/token?client_secret=secret&client_id=web&grant_type=password&username=kalaiselvan&password=kalaiselvan
  • 你如何获得这个令牌9e3cee66-ebd9-4e0e-acd1-718152794552
  • 使用此查询:localhost:8081/oauth/token?client_secret=secret10&client_id=web10&grant_type=password&username=2871&password=631356
  • 有一件事,当我第一次点击 oauth/token api 时,它为我生成了刷新令牌。但现在它甚至不适用于新用户
  • 但它在我的数据库 web10 和 secret10 中
猜你喜欢
  • 2021-12-26
  • 2018-12-26
  • 2020-11-05
  • 2019-03-13
  • 2023-03-09
  • 1970-01-01
  • 2018-12-01
  • 2018-05-03
  • 1970-01-01
相关资源
最近更新 更多