【问题标题】:Need help in validating access token在验证访问令牌方面需要帮助
【发布时间】:2022-07-08 06:34:46
【问题描述】:

我已将访问令牌作为不记名令牌从 UI 传递到我的 API。使用该不记名令牌、客户端 ID 和客户端密码,我可以进行自省。但是如何使用 SpringBoot 验证访问令牌?我在网上找不到任何示例。

我想要的是,在向我的控制器发送请求之前验证传递的访问令牌是否有效。

请帮忙。一个星期以来我一直坚持这一点

【问题讨论】:

  • 你是直接调用服务,还是使用api网关?
  • 我直接打电话给@Mauricio
  • 这是一个反应式应用程序吗?还是一个简单的 MVC?
  • 反应性应用程序@Mauricio

标签: spring-boot spring-security-oauth2


【解决方案1】:

鉴于您提供的信息,您可以简单地使用 org.springframework.web.server.WebFilter 来实现您的自定义验证器:

声明

@Component
public class CredentialFilter implements WebFilter

里面,覆盖过滤方法:

    @Override
    public Mono<Void> filter(final ServerWebExchange serverWebExchange, final WebFilterChain webFilterChain) {
    
        //gets the header called bearer_token, or however you store it. You can also use any of the request properties.
        return Mono.just(serverWebExchange.getRequest().getHeaders().getFirst("bearer_token"))
           //if no bearer token throw a simple exception.
           .switchIfEmpty(Mono.defer(() -> Mono.error(new Exception("Unauthorized"))))
           //validate token with your custom method. If not valid, deals same as before.
           .filter(token -> validateToken(token))
           .switchIfEmpty(Mono.defer(() -> Mono.error(new Exception("Unauthorized"))))
           .onErrorResume(e -> {
              throw managedException(e);
           })
           //continue the request.
           .then(webFilterChain.filter(serverWebExchange));

}

        //method to escape throw check.
        protected RuntimeException managedException(final Throwable e) {

        if (e instanceof ISSException.GenericException) {
            return (ISSException.GenericException) e;
        }
        return (RuntimeException) e;
    }

当然,使用异常处理程序是不完整的。幸运的是,我们有 org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler 接口:

@Component
public class WebfluxExceptionHandler implements ErrorWebExceptionHandler

并重写handle方法来捕获我们的异常:

@Override
public Mono<Void> handle(final ServerWebExchange serverWebExchange, final Throwable throwable) {
    if (throwable.getMessage().equals("Unauthorized")) {
       //put an unauthorized code serverWebExchange.getResponse().setStatusCode(org.springframework.http.HttpStatus.UNAUTHORIZED);
    }
    return Mono.error(throwable);
}

【讨论】:

    猜你喜欢
    • 2021-09-21
    • 2012-12-26
    • 1970-01-01
    • 1970-01-01
    • 2012-08-26
    • 1970-01-01
    • 2012-03-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多