Micronaut安全性无法“安全”

时间:2018-09-01 02:31:47

标签: java security micronaut

我有一个基于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。我以为如果返回假,安全检查将失败,并且失败将导致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世界URL时出现问题。 (http://localhost:8080/hello)我不能使对服务的访问失败。筛选器捕获所有请求,并且使用了安全对象,但是它似乎并不能阻止对hello服务的访问。我不知道如何使访问失败。

有人可以帮忙吗?谢谢。

1 个答案:

答案 0 :(得分: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中写访问规则

相关问题