为了账号安全,请及时绑定邮箱和手机立即绑定

Micronaut 安全无法“保护”

Micronaut 安全无法“保护”

红糖糍粑 2021-08-25 10:45:41
我有一个简单的基于 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 教程说明创建了一个安全服务类:@Singletonpublic 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 服务。我不知道需要什么才能使访问失败。有人可以帮忙解决这个问题吗?谢谢。
查看完整描述

1 回答

?
慕姐8265434

TA贡献1813条经验 获得超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 批注或在配置文件中写入访问规则,文档中的更多示例


查看完整回答
反对 回复 2021-08-25
  • 1 回答
  • 0 关注
  • 158 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信