Authorization comes into play after the user is authenticated and it usually means Who can access what?. Mentawai comes with a simple yet powerful approach to user authorization. In Mentawai you can tell the framework to which groups an authenticated user belongs so that later it can grant or deny access to parts of the web application based on that information. For example, you may have actions that must only be accessed by the ADMIN group. The same thing for some JSP pages. More interestingly, a JSP page may hide certain blocks or parts from certain user groups.
Telling the framework to which groups an user belongs:
public class LoginAction extends BaseLoginAction { @Override public String execute() { // (...) setSessionObj(u); setSessionGroups(u.getGroup()); setSessionLocale(u.getLocale()); return SUCCESS; } }
You can pass one or more Strings ("admin", "editor", "guest", etc.) to the setSessionGroups method. Its parameter is a varargs. Additionally you can also pass one or more Enumerations (Group.ADMIN, Group.EDITOR, Group.GUEST, etc.).
Authorizing an action for only certain groups:
action("/User", UserAction.class, "edit") .authorize(Group.ADMIN, Group.MASTER) .on(ACCESSDENIED, exception("Only admin and master can modify a user!")) .on(ERROR, fwd("/jsp/user/edit.jsp")) .on(SHOW, fwd("/jsp/user/edit.jsp")) .on(UPDATED, fwd("/jsp/index.jsp"));
NOTE: Line 2 above is equivalent to .authorize("ADMIN", "MASTER")
The authorization is actually implemented as a filter that will return the result ACCESSDENIED in case the authorization fails. For that result we configure and ExceptionConsequence, which as the name implies will throw an ActionException with the message given.
TIP: Instead of throwing an exception, you can also configure the ACCESSDENIED result to redirect to a nice page explaining to the user that he is not authorized to access that action.
Authorizing a JSP page for only certain groups:
<%@ page contentType="text/html; charset=UTF-8"%> <%@taglib prefix="mtw" uri="http://www.mentaframework.org/tags-mtw/"%> <mtw:requiresAuthorization groups="ADMIN, MASTER" />
NOTE: Whatever consequence you configured for the ACCESSDENIED result in the application manager will happen here.
Authorizing only parts of a JSP page for only certain groups:
<%@ page contentType="text/html; charset=UTF-8"%> <%@taglib prefix="mtw" uri="http://www.mentaframework.org/tags-mtw/"%> <mtw:hasAuthorization groups="ADMIN, MASTER"> Only authorized people can see this. </mtw:hasAuthorization>
TIP: You can also use the attribute negate="true" in the above tag to invert the condition. All Mentawai conditional tags support this feature so you can easily implement something similar to an else statement.