Solon v3.0.3

对 RouterInterceptor 进行路径限制

</> markdown

方案1:

RouterInterceptor 想要对路径进行限制,默认是需要自己写代码控制的。理论上,性能会更好:

@Component
public class AdminInterceptorImpl implements RouterInterceptor {
    @Inject
    private AuthService authService;

    @Override
    public void doIntercept(Context ctx, Handler mainHandler, RouterInterceptorChain chain) throws Throwable {
        //注意用 pathAsLower(小写模式)
        if (ctx.pathAsLower().startsWith("/admin/") &&
                ctx.pathAsLower().startsWith("/admin/login") == false) {
            //满足条件后,进行业务处理    
            if(authService.isLogined(ctx)){
                chain.doIntercept(ctx, mainHandler);
            }else{
               ctx.render(Result.failure(401,"账号未登录"));
            }
        } else {
            chain.doIntercept(ctx, mainHandler);
        }
    }
}

方案2:

也可以使用 pathPatterns 接口对路径进行限制。看上去清爽些。例:v2.4.2 后支持

@Component
public class AdminInterceptorImpl implements RouterInterceptor {
    @Inject
    private AuthService authService;
    
    @Override
    public PathRule pathPatterns() {
        return new PathRule().include("/admin/**").exclude("/admin/login");
    }

    @Override
    public void doIntercept(Context ctx, Handler mainHandler, RouterInterceptorChain chain) throws Throwable {
        if(authService.isLogined(ctx)){
            chain.doIntercept(ctx, mainHandler);
        }else{
           ctx.render(Result.failure(401,"账号未登录"));
        }
    }
}