<-- home

Writing a custom Facelet EL function makes authorization check using Spring Security

It’s common that you may want to show some part of your pages to the user with certain roles. Writing a custom Facelet EL function makes doing authorization checks for viewing parts of pages really easy. If you are using Spring Security in the background, you can use its SecurityContext object to get authorities of the user and use them in your EL function implementation.

Here, there is a simple EL function implementation that users Spring Security to get roles of user and controls if the user has a certain role or not.

package com.basrikahveci.samples;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

public class CustomELFunctions {
	public static Boolean hasRole(String roleName) {
		SecurityContext securityContext = SecurityContextHolder.getContext();
		Collection<GrantedAuthority> grantedAuthorities = securityContext
			.getAuthentication().getAuthorities();

		for (GrantedAuthority authority : grantedAuthorities) {
			if (authority.getAuthority().equals(roleName)) {
				return true;
			}
		}

		return false;
	}
}

To use this custom EL function in your facelets, define the EL function in an xml file and put that file in your WEB-INF directory. (customtags.taglib.xml is the name I used)

<?xml version="1.0" encoding="UTF-8"?>
<facelet-taglib xmlns="http://java.sun.com/xml/ns/javaee"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facelettaglibrary_2_0.xsd"
            version="2.0">

	<namespace>http://www.basrikahveci.com/custom</namespace>

	<function>
		<function-name>hasRole</function-name>
		<function-class>com.basrikahveci.samples.CustomELFunctions</function-class>
		<function-signature>boolean hasRole(java.lang.String)</function-signature>
	</function>
</facelet-taglib>

And give your tag definition file as a context parameter in your web.xml

<context-param>
	<param-name>javax.faces.FACELETS_LIBRARIES</param-name>
	<param-value>/WEB-INF/customtags.taglib.xml</param-value>
</context-param>

Now you can use your custom EL function in your facelet like this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html"	xmlns:custom="http://www.basrikahveci.com/custom">
	<h:outputText value="Only admins can see this text." rendered="#{custom:hasRole('ROLE_ADMIN')}" />
</html>

That’s all. Viva la resistance.