Pablo
Pablo

Reputation: 1081

How to authorize users on JSP and REST services using request.isUserInRole() in Struts 2?

I'm developing a small Java EE application using Struts 2 and REST services over an JBoss AS7 server.

I'm using FORM auth for REST and Web Content, and I don't have any problem with REST, but on the web, I have to distinguish between manager and admin roles, in order to show some extra options to admin users.

I'd like to do something like:

<s:if test="#request.isUserInRole("admin")>

but it doesn't work.

Do you know any way, so I can achieve something like this?

How should I do to distinguish between roles in my JSP pages?

Upvotes: 3

Views: 1631

Answers (2)

Roman C
Roman C

Reputation: 1

You could use PrincipalAware to implement it by the action used to render the JSP. When you implement it in the action Struts2 injects PrincipalProxy object to your action. Ensure servlet-config interceptor is applied to the action.

public class MyAction extends ActionSupport implements PrincipalAware {

  protected PrincipalProxy principal;

  public void setPrincipalProxy(PrincipalProxy principalProxy) {
    this.principal = principalProxy;
  }

  public PrincipalProxy getPrincipal() {
    return principal;
  }
}

This object then you could find in the valueStack on the JSP page and do something like

<s:if test="principal.isUserInRole('admin')">

You could also access this information from How do I obtain security details (JAAS).

Upvotes: 1

Pablo
Pablo

Reputation: 1081

I solved it on this way:

importing:

<jsp:directive.page import="com.opensymphony.xwork2.util.ValueStack"/>
<jsp:directive.page import="com.opensymphony.xwork2.ActionContext"/>
<jsp:directive.page import="org.apache.struts2.ServletActionContext"/>

then stacking request with:

<jsp:scriptlet><![CDATA[
ValueStack stack = ActionContext.getContext().getValueStack();
 stack.set("httpServletRequest", ServletActionContext.getRequest());
]]></jsp:scriptlet>

and to check roles:

<s:if test="httpServletRequest.isUserInRole('admin')">

Upvotes: 0

Related Questions