Micronaut安全无法“安全”

问题描述 投票:0回答:1

我有一个简单的基于Micronaut的“hello world”服务,它内置了一个简单的安全性(为了测试和说明Micronaut安全性)。下面提供了实现hello服务的服务中的控制器代码:

@Controller("/hello")
public class HelloController
{
   public HelloController()
   {
      // Might put some stuff in in the future
   }

    @Get("/")
    @Produces(MediaType.TEXT_PLAIN)
    public String index()
    {
       return("Hello to the World of Micronaut!!!");
    }
}

为了测试安全机制,我遵循了Micronaut教程说明并创建了一个安全服务类:

@Singleton
public class SecurityService
{
    public SecurityService()
    {
       // Might put in some stuff in the future
    }

    Flowable<Boolean> checkAuthorization(HttpRequest<?> theReq)
    {
        Flowable<Boolean> flow = Flowable.fromCallable(()->{
           System.out.println("Security Engaged!");
           return(false);    <== The tutorial says return true
        }).subscribeOn(Schedulers.io());

        return(flow);
    }

}

应该注意的是,与教程不同,flowable.fromCallable()lambda返回false。在本教程中,它返回true。我假设如果返回false则安全检查会失败,并且失败会导致hello服务无法响应。

根据教程,为了开始使用Security对象,必须有一个过滤器。我创建的过滤器如下所示:

@Filter("/**")
public class HelloFilter implements HttpServerFilter
{
   private final SecurityService secService;

   public HelloFilter(SecurityService aSec)
   {
      System.out.println("Filter Created!");
      secService = aSec;
   }

   @Override
   public Publisher<MutableHttpResponse<?>> doFilter(HttpRequest<?> theReq, ServerFilterChain theChain)
   {
      System.out.println("Filtering!");
      Publisher<MutableHttpResponse<?>> resp = secService.checkAuthorization(theReq)
                                                         .doOnNext(res->{
                                                            System.out.println("Responding!");
                                                         });

      return(resp);
   }
}

当我运行微服务并访问Helo world URL时会出现问题。 (http://localhost:8080/hello)我无法使访问服务失败。过滤器捕获所有请求,并且安全对象已启用,但它似乎不会阻止访问hello服务。我不知道如何使访问失败。

有人可以帮忙解决这个问题吗?谢谢。

java security micronaut
1个回答
2
投票

当您无法像往常一样访问资源或流程请求时,您需要在过滤器中更改请求。你的HelloFilter看起来像这样:

@Override
public Publisher<MutableHttpResponse<?>> doFilter(HttpRequest<?> theReq, ServerFilterChain theChain) {
    System.out.println("Filtering!");
    Publisher<MutableHttpResponse<?>> resp = secService.checkAuthorization(theReq)
            .switchMap((authResult) -> { // authResult - is you result from SecurityService
                if (!authResult) {
                    return Publishers.just(HttpResponse.status(HttpStatus.FORBIDDEN)); // reject request
                } else {
                    return theChain.proceed(theReq); // process request as usual
                }
            })
            .doOnNext(res -> {
                System.out.println("Responding!");
            });

    return (resp);
}

在最后 - micronaut具有SecurityFilter的安全模块,您可以在配置文件中使用@Secured注释或写入访问规则more examples in the doc

© www.soinside.com 2019 - 2024. All rights reserved.