Chapter 8: Authentication
Target Application
In this chapter, we will demonstrate how to implement authentication and protect your pages from illegal access. We will create a login page without sidebar as follows:
After login, we redirect users to index page with user name appeared at right side of the header.
Authentication
Authentication is the process to identify a user, and requesting an account and a password is a common way. Our login page also use a template zul to keep a consistent style with index page. But it has no sidebar because users without login should not access main functions.
/chapter8/layout/template-anonymous.zul
<zk>
<!-- free to access template, without sidebar -->
<borderlayout hflex="1" vflex="1">
<north height="100px" border="none" >
<include src="/chapter8/layout/banner.zul"/>
</north>
<center id="mainContent" autoscroll="true" border="none" self="@insert(content)">
<!-- the main content will be insert to here -->
</center>
<south height="50px" border="none">
<include src="/chapter3/footer.zul"/>
</south>
</borderlayout>
</zk>
- Line 7: Define an anchor named content
Login form is built with Grid.
<?link rel="stylesheet" type="text/css" href="/style.css"?>
<!-- it is a login page, no authentication protection and use anonymous template -->
<?init class="org.zkoss.zk.ui.util.Composition" arg0="/chapter8/layout/template-anonymous.zul"?>
<zk>
<hbox self="@define(content)" vflex="1" hflex="1" align="center"
pack="center" spacing="20px">
<vlayout>
<window id="loginWin"
apply="org.zkoss.tutorial.chapter8.LoginController"
title="Login with you name" border="normal" hflex="min">
<vbox hflex="min" align="center">
<grid hflex="min">
<columns>
<column hflex="min" align="right" />
<column />
</columns>
<rows>
<row>
Account :
<textbox id="account" width="200px" />
</row>
<row>
Password :
<textbox id="password" type="password"
width="200px" />
</row>
</rows>
</grid>
<label id="message" sclass="warn" value=" " />
<button id="login" label="Login" />
</vbox>
</window>
(use account='zkoss' and password='1234' to login)
</vlayout>
</hbox>
</zk>
- Line 3: Apply a template zul with <?init ?>.
- Line 5: Define a fragment to be inserted in the anchor content.
- Line 24: Specify "password" at type, then input will be masked.
Session
Logout
Secure Your Pages
Security is an important issue that every developer must consider for a web application since users can enter any URL in a browser to access any resource. Even though you have created a login page for authentication, but a user can bypass the login page and access the index page after login if he knows the page's URL. Therefore, we should apply a mechanism to protect zul pages from illegal access. ZK allows you to initialize a zul page by implement a Initiator. When we apply an Initiator to a zul, ZK will use it to perform initialization before creating components upon a zul. We can create a initiator to check user's