Spring Boot-无效的访问 token 错误

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

我目前正在做一个简单的 Spring Boot 应用 我通过 client_id 和 secret 来获取访问 token ,这使我获得刷新和访问 token 。

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

{"error":"invalid_token","error_description":"无效的访问 token :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;
    }
} `

最佳答案

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

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

并通过制作 开始生成一些 token 发布 向您的服务器发出请求,网址为:本地主机:您的端口/oauth/ token

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

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

enter image description here

复制 access_token 从响应数据中生成新的 发布 要求
http://localhost:8085/account
enter image description here

希望对你有帮助

关于Spring Boot-无效的访问 token 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48761624/

相关文章:

java - 将复杂的 json 对象发送到 Spring MVC Controller

spring - 在 Application.doWithSpring() 中访问环境属性

java - Java中如何检查JsonNode是单个元素还是数组?

Spring 启动 : how to set a common path for multiple RestControllers

java - Spring NTLM NtlmProcessingFilter 做缓存

java - 获取值配置服务器Spring Boot

java - 如何创建实体并将其保存到数据库?

java - 使用 Spring boot 的 RSS 提要

angularjs - 在 Spring Security 或 Angular 中注销时清除 Cookie

spring - 在 “OAUTH2” 启用的启动应用程序中禁用身份验证