Intercept request and check authorization in playframework

后端 未结 1 2031
渐次进展
渐次进展 2021-02-10 15:34

I\'m using play framework 2.4.2 with Java and I want to validate that a user is logged in by intercepting all requests and checking if a session value is set. So I

相关标签:
1条回答
  • 2021-02-10 16:22

    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.

    0 讨论(0)
提交回复
热议问题