Java Reference
In-Depth Information
• If the
@RolesAllowed
annotation is found, access is granted if the
user has at least one of the roles listed in the annotation.
• If no annotation is found, access is granted.
To determine whether the user is authenticated and whether the user
has a given role,
J2EESecurityManager
defines protected methods with
default implementations:
public class
J2EESecurityManager
implements
SecurityManager {
/
*
...
*
/
protected
Boolean isUserAuthenticated(ActionBean bean, Method handler) {
return
bean.getContext().getRequest().getUserPrincipal() !=
null
;
}
protected
Boolean hasRole(ActionBean bean, Method handler,
String role)
{
return
bean.getContext().getRequest().isUserInRole(role);
}
}
HttpRequest.getUserPrincipal()
and
HttpRequest.isUserInRole(role)
use the
servlet container's configuration. In our case, however, authentication
is performed in the Login page. Roles are stored in the database and are
associated to the
User
object. We can subclass
J2EESecurityManager
and
provide our own implementation for
isUserAuthenticated
( ) and
hasRole
( ):
package
stripesbook.nonext;
public class
MySecurityManager
extends
J2EESecurityManager {
@Override
protected
Boolean isUserAuthenticated(ActionBean bean, Method handler) {
return
getUser(bean) !=
null
;
}
@Override
protected boolean
hasRole(ActionBean actionBean, Method handler,
String role)
{
User user = getUser(bean);
if
(user !=
null
) {
Collection<Role> roles = user.getRoles();
return
roles !=
null
&& roles.contains(
new
Role(role));
}
return false
;
}
private
User getUser(ActionBean bean) {
return
((BaseActionBean) bean).getContext().getUser();
}
}
Search WWH ::
Custom Search