Intercept request and check authorization in playframework

纵饮孤独 提交于 2019-12-03 08:36:57

Even if I would re-consider using action composition, you can fix Option 1.

Create a custom annotation to mark the actions that don't need validation.

@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface NoAuthRequired {}

Then change your HttpRequestHandler implementation.

public class RequestHandler extends DefaultHttpRequestHandler {
    @Override
    public Action createAction(Http.Request request, Method actionMethod) {
        return new Action.Simple() {
            @Override
            public F.Promise<Result> call(Http.Context ctx) throws Throwable {
                // if the action is annotated with @NoAuthRequired or user is logged in delegate to it
                if (actionMethod.isAnnotationPresent(NoAuthRequired.class) || ctx.session().containsKey("loggedIn")) {
                    return delegate.call(ctx);
                }
                // otherwise, block access
                else {
                    return F.Promise.pure(forbidden("You're not allowed"));
                }
            }
        };
    }
}

In this way, every route requires validation unless explicitly annotated.

As you can see from the code, the session is available through the Context.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!