我有一个简单的基于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服务的访问。我不知道怎样才能使访问失败。
在这件事上有人能帮上忙吗?谢谢。
发布于 2018-09-04 14:14:10
当您无法像往常一样访问资源或处理请求时,需要在筛选器中更改请求。您的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的安全模块,你可以在配置文件more examples in the doc中使用@Secured注释或编写访问规则
https://stackoverflow.com/questions/52124394
复制相似问题