How to create custom web security expression to use in JSP?

Viewed 1147

How is it possible to create your own web security expression, so that I'll be able to use it in JSP file like:

<sec:authorize access="isOwner()"> some content here </sec:authorize>
2 Answers

Here is what you need. Follow below to create custom SpEL expression:

1) Create custom subclass of WebSecurityExpressionRoot class. In this subclass create a new method which you will use in expression. For example:

public class CustomWebSecurityExpressionRoot extends WebSecurityExpressionRoot {

    public CustomWebSecurityExpressionRoot(Authentication a, FilterInvocation fi) {
        super(a, fi);
    }

    public boolean yourCustomMethod() {
        boolean calculatedValue = ...;

        return calculatedValue;

    }
}

2) Create custom subclass of DefaultWebSecurityExpressionHandler class and override method createSecurityExpressionRoot(Authentication authentication, FilterInvocation fi) (not createEvaluationContext(...)) in it to return your CustomWebSecurityExpressionRoot instance. For example:

@Component(value="customExpressionHandler")
public class CustomWebSecurityExpressionHandler extends DefaultWebSecurityExpressionHandler {

    @Override
    protected SecurityExpressionRoot createSecurityExpressionRoot(
            Authentication authentication, FilterInvocation fi) {

        WebSecurityExpressionRoot expressionRoot = new CustomWebSecurityExpressionRoot(authentication, fi);

        return expressionRoot;
}}

3) Define in your spring-security.xml the reference to your expression handler bean

<security:http access-denied-page="/error403.jsp" use-expressions="true" auto-config="false">
    ...

    <security:expression-handler ref="customExpressionHandler"/>
</security:http>

After this, you can use your own custom expression instead of the standard one:

<security:authorize access="yourCustomMethod()">

I suggest you using Shiro framework.
Official Link:http://shiro.apache.org/
Implement AuthorizingRealm with extends, then add the expression of security control in the doGetAuthorizationInfo(...).
In the JSP, first add Shiro JSP tag library, official link :http://shiro.apache.org/web.html#Web-taglibrary

Using <shiro:hasPermission name="...">...</shiro:hasPermission> can control the things you need. name property is the expression which will compare with what you set in AuthorizingRealm.

Here is permission expression guide :http://shiro.apache.org/permissions.html

Here is some usage:

<%@ taglib prefix="shiro" uri=http://shiro.apache.org/tags %>
<html>
<body>
    <shiro:hasPermission name="users:manage">
        <a href="manageUsers.jsp">
            Click here to manage users
        </a>
    </shiro:hasPermission>
    <shiro:lacksPermission name="users:manage">
        No user management for you!
    </shiro:lacksPermission>
</body>
</html>
Related