How do you password protect a page with Wicket?

余生颓废 提交于 2019-12-10 17:18:27

问题


I want to password protect a webpage in Wicket so the user may only access it if he/she has logged in.

I'd also like the page to show the login page, and then after logging in the original page the user was trying to get to.

How is this done with wicket? I've already created a login page and extended the session class.


回答1:


The framework-supplied way is to provide an IAuthorizationStrategy instance for your application, e.g., by adding to your Application init() method:

init() {
    ...
    getSecuritySettings().setAuthorizationStrategy(...)
}

A working example of Wickets authorization functionality is on Wicket Stuff here, which demonstrates some reasonably complex stuff. For really simple cases, have a look at the SimplePageAuthorizationStrategy. At a very basic level, this could be used like so (taken from the linked Javadoc):

SimplePageAuthorizationStrategy authorizationStrategy = new SimplePageAuthorizationStrategy(
    MySecureWebPage.class, MySignInPage.class)
 {
        protected boolean isAuthorized()
        {
            // Authorize access based on user authentication in the session
            return (((MySession)Session.get()).isSignedIn());
        }
 };
 getSecuritySettings().setAuthorizationStrategy(authorizationStrategy);

Edit in response to comment

I think the best way forward, if you're just going to use something like SimplePageAuthorizationStrategy rather than that class itself. I did something like this to capture pages that are annotated with a custom annotation:

IAuthorizationStrategy authorizationStrategy = new AbstractPageAuthorizationStrategy()
 {
        protected boolean isPageAuthorized(java.lang.Class<Page.class> pageClass)
        {
            if (pageClass.getAnnotation(Protected.class) != null) {
                return (((MySession)Session.get()).isSignedIn());
            } else {
                return true;
            }
        }
 };

Then you'd need to register an IUnauthorizedComponentInstantiationListener similar to what is done in SimplePageAuthorizationStrategy (link is to the source code), which should be something like:

new IUnauthorizedComponentInstantiationListener()
{
    public void onUnauthorizedInstantiation(final Component component)
    {
    if (component instanceof Page)
    {
        throw new RestartResponseAtInterceptPageException(MySignInPage.class);
    }
    else
    {
        throw new UnauthorizedInstantiationException(component.getClass());
    }
    }
});


来源:https://stackoverflow.com/questions/2901285/how-do-you-password-protect-a-page-with-wicket

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