Suppose you declared everything as usual:
<security:http auto-config="true">
<security:intercept-url pattern="/secure/**" access="ROLE_User"/>
<security:anonymous username="Guest" granted-authority="ROLE_Guest"/>
</security:http>
And everything's working just fine.
Then for some reason you decide to check for anonymous (not logged in) user:
if( request.isUserInRole("ROLE_Guest") ) ...
Always false.
You try
if( request.isUserInRole("Guest") ) ...
And
if( request.getRemoteUser().equals("Guest") )
Won't work, either.
And, guess what, it's by design. Yup. By design. Don't ask. At least don't ask me, I didn't write the thing.
Here's the culprit:
http://static.springsource.org/spring-security/site/apidocs/org/springframework/security/wrapper/SecurityContextHolderAwareRequestWrapper.html
http://acegisecurity.svn.sourceforge.net/viewvc/acegisecurity/spring-security/branches/2.0.x-branch/core/src/main/java/org/springframework/security/wrapper/SecurityContextHolderAwareRequestWrapper.java?revision=3290&view=markup
See line 77.
So, what can you do?
if( request.getRemoteUser() == null )
Just forget the anonymous user exists, has a role and a name. It works only inside Spring Security and by default does not propagate to Servlet API.
So, why give the poor anonymous user a name and a role just to deny the access to them? That is, besides confusing the issue? Where is it actually useful?
In configurations like this:
<security:http auto-config="true">
<security:intercept-url pattern="/my_application/**" access="ROLE_User"/>
<security:intercept-url pattern="/my_application/docs/**" access="ROLE_Guest,ROLE_User"/>
<security:anonymous username="Guest" granted-authority="ROLE_Guest"/>
</security:http>
Yes, that's a bad example and you shouldn't actually set up a directory structure like that.
I couldn't come up with anything better now. I just wasted a couple hours on this and I need sleep.
Yawn.
Sometimes I hate this job.
Comments: 0