Unable to Configure Spring Security With X.509 Certificate and Anonymous User - spring-security

I am attempting to authenticate via X.509 smart card to my application. For the moment, my application doesn't have any users defined, so I'm trying to use anonymous authentication. I'll switch it to hasRole() once I create users.
<security:authentication-manager alias="authenticationManager">
<security:authentication-provider user-service-ref="myUserService" />
</security:authentication-manager>
<!-- TODO: Enable this once I am ready to start annotating the service interfaces -->
<security:global-method-security pre-post-annotations="enabled" />
<security:http use-expressions="true" authentication-manager-ref="authenticationManager" access-denied-page="/index2.xhtml" >
<security:anonymous enabled="true" />
<security:x509 subject-principal-regex="CN=(.*?)," user-service-ref="myUserService" />
<security:intercept-url pattern="/**" access="isAnonymous()" requires-channel="https" />
<!-- TODO: configure invalid-session-url, delete sessionid -->
<security:session-management>
<security:concurrency-control max-sessions="2" error-if-maximum-exceeded="true"/>
</security:session-management>
</security:http>
<bean id="roleVoter"
class="org.springframework.security.access.vote.RoleHierarchyVoter">
<constructor-arg ref="roleHierarchy" />
</bean>
<bean id="roleHierarchy"
class="org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl">
<property name="hierarchy">
<value>
ROLE_USER > ROLE_AUTHENTICATED
ROLE_AUTHENTICATED > ROLE_UNAUTHENTICATED
ROLE_UNAUTHENTICATED > ROLE_ANONYMOUS
</value>
</property>
</bean>
It seems to be caught in the infinite loop issue, which I thought I was avoiding using isAnonymous().
I'm probably making a dumb error, so if someone can point out said stupidity, I'd be grateful.

The issue was a problem with configuring FacesServlet in web.xml. The FacesServlet was mapped to one path, which seemed to be incompatible with the intercept-url defined for Spring Security.
We've since jettisoned JSF (and good riddance).

Related

Spring security authentication using ldap based on memberOf attribute

I'm using spring authentication against ldap. If the provided user id and password exists in ldap, then I was able to get the user login. I would like to restrict this based on the user's memberOf attribute in the LDAP. If the user has memberOf attribute with a specific CN value (CN=adminaccess or CN=superadminaccess), then authentication/authorization should pass.Else authentication/authorization should fail.
<security:http auto-config="true" use-expressions="true" access-denied-page="/admin/auth/denied">
<security:intercept-url pattern="/admin/auth/login" access="permitAll" />
<security:intercept-url pattern="/admin/dashboard/*" access="hasAnyRole('ROLE_ADMINACCESS','ROLE_SUPERADMINACCESS')"/>
</security:http>
<security:authentication-manager>
<security:ldap-authentication-provider user-dn-pattern="CN={0},CN=Users" group-search-base="CN=adminaccess,CN=Users" />
</security:authentication-manager>
<bean id="ldapContext"
class="org.springframework.security.ldap.DefaultSpringSecurityContextSource">
<constructor-arg value="ldap://xxx.ds.yyy.com:389/DC=xxx,DC=ds,DC=yyy,DC=com"/>
<property name="userDn" value="CN=aaa,CN=Users,DC=xxx,DC=ds,DC=yyy,DC=com"/>
<property name="password" value="thepassword"/>
</bean>
I always go to the Access Denied page with my above configuration. If I remove the access="hasAnyRole('ROLE_ADMINACCESS','ROLE_SUPERADMINACCESS')" from the security:intercept-url, I'm able to always access with valid user/password, even if the user is not part of adminaccess (which I was hoping would be restricted because my group -search-base had specified CN=adminaccess).
Wondering what the configuration should be:
To restrict access to just users who are memberOf CN=adminaccess and/or CN=superadminaccess
Specify correct group-search-base. If I specify only CN=Users, I'm getting a timeout as this is going against our corporate ldap. When I looked up users on LDAP browser, I couldnt find a "ou" that couldhelp. With my above configuration group-search-base="CN=adminaccess,CN=Users", I dont get a timeout, but I dont think it is correct either
Not sure if there is a better way, but I was able to successfully get this working using DefaultLdapAuthoritiesPopulator and updating to the below configuration:
<security:http auto-config="true" use-expressions="true" access-denied-page="/admin/auth/denied">
<security:intercept-url pattern="/admin/auth/login" access="permitAll" />
<security:intercept-url pattern="/admin/dashboard/*" access="hasAnyRole('ROLE_ADMINACCESS','ROLE_SUPERADMINACCESS')"/>
</security:http>
<security:authentication-manager>
<security:authentication-provider
ref="ldapAuthProvider"></security:authentication-provider>
</security:authentication-manager>
<bean id="ldapContext"
class="org.springframework.security.ldap.DefaultSpringSecurityContextSource">
<constructor-arg value="ldap://xxx.ds.yyy.com:389/DC=xxx,DC=ds,DC=yyy,DC=com"/>
<property name="userDn" value="CN=aaa,CN=Users,DC=xxx,DC=ds,DC=yyy,DC=com"/>
<property name="password" value="thepassword"/>
</bean>
<bean id="ldapAuthProvider"
class="org.springframework.security.ldap.authentication.LdapAuthenticationProvider">
<constructor-arg>
<bean
class="org.springframework.security.ldap.authentication.BindAuthenticator">
<constructor-arg ref="ldapContext" />
<property name="userDnPatterns">
<list>
<value>CN={0},CN=Users</value>
</list>
</property>
</bean>
</constructor-arg>
<constructor-arg>
<bean
class="org.springframework.security.ldap.userdetails.DefaultLdapAuthoritiesPopulator">
<constructor-arg ref="ldapContext" />
<constructor-arg value="CN=Users" />
<property name="groupRoleAttribute" value="CN" />
</bean>
</constructor-arg>
</bean>
With this configuration, if the login username/password provided is correct, all the groups that the user is "memberOf" (pattern CN=Users,DC=xxx,DC=ds,DC=yyy,DC=com), get loaded as his "roles" (prefixed with ROLE_) and I'm able to manage access to these roles using security:intercept-url

Customizing authentication exceptions spring oauth

I'm using jersey as a RESTFul webserver. (jersey-server 1.8) with spring (3.2.0.RELEASE) and hibernate.
My endpoints are protected using spring-security (3.1.3.RELEASE) with 2 legged oAuth 1.0a (spring-security-oauth 1.0.0.M4 )
Everything works as expected and the securing works.
Inside my ConsumerDetailsServiceImpl (implements ConsumerDetailsService, UserDetailsService, AuthenticationProvider) i throw different exceptions (all are of form OAuthException now, but i want to add my own custom exceptions)
However no matter what i tried i cannot get to customize the different authentication and access denied exceptions the way i want, i always get the default 401 page
My API is agreed to always return a json responseobject so i need to catch these exceptions and show 401 pages with json inside it
My securty.xml
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:security="http://www.springframework.org/schema/security" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:oauth="http://www.springframework.org/schema/security/oauth"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.1.xsd
http://www.springframework.org/schema/security/oauth
http://www.springframework.org/schema/security/spring-security-oauth.xsd">
<!-- Authentication beans -->
<bean name="consumerDetailsService" class="com.securitytest.core.services.impl.ConsumerDetailsServiceImpl" />
<bean name="oauthProcessingFilterEntryPoint" class="org.springframework.security.oauth.provider.OAuthProcessingFilterEntryPoint" />
<bean id="oAuthAuthenticationHandler" class="com.securitytest.core.security.CustomOAuthAuthenticationHandler" />
<security:http auto-config="true" use-expressions="true" entry-point-ref="oauthProcessingFilterEntryPoint" >
<security:intercept-url pattern="/rest/secured/**" access="isAuthenticated()" />
<security:intercept-url pattern="/rest/unsecured/**" access="permitAll" />
<security:intercept-url pattern="/rest/**" access="isAuthenticated()" />
<security:form-login login-page='/login' default-target-url="/home" authentication-failure-handler-ref="authenticationFailureHandler"/>
<security:access-denied-handler ref="accessDeniedHandler" />
</security:http>
<bean id="accessDeniedHandler" class="com.securitytest.core.security.CustomoauthAccessDeniedHandler" />
<!-- this was just a test, it didn't work obviously -->
<bean id="authenticationFailureHandler" class="org.springframework.security.web.authentication.ExceptionMappingAuthenticationFailureHandler">
<property name="exceptionMappings">
<props>
<prop key="org.springframework.security.authentication.BadCredentialsException">/login/badCredentials</prop>
<prop key="org.springframework.security.authentication.CredentialsExpiredException">/login/credentialsExpired</prop>
<prop key="org.springframework.security.authentication.LockedException">/login/accountLocked</prop>
<prop key="org.springframework.security.authentication.DisabledException">/login/accountDisabled</prop>
</props>
</property>
</bean>
<security:authentication-manager alias="authenticationManager">
<security:authentication-provider ref="consumerDetailsService" />
</security:authentication-manager>
<bean id="nonceServices" class="org.springframework.security.oauth.provider.nonce.InMemoryNonceServices" />
<oauth:provider
auth-handler-ref="oAuthAuthenticationHandler"
consumer-details-service-ref="consumerDetailsService"
nonce-services-ref="nonceServices"
token-services-ref="tokenServices"
require10a="true"
/>
<oauth:token-services id="tokenServices" />
Stuff i tried
Change the exceptionTranslationFilter -> is not allowed by the docs
Add a custom access-denied-handler and a authentication-failure-handler-ref
<security:http auto-config="true" use-expressions="true" entry-point-ref="oauthProcessingFilterEntryPoint" >
<security:intercept-url pattern="/rest/secured/**" access="isAuthenticated()" />
<security:intercept-url pattern="/rest/unsecured/**" access="permitAll" />
<security:intercept-url pattern="/rest/**" access="isAuthenticated()" />
<security:form-login login-page='/login' default-target-url="/home" authentication-failure-handler-ref="authenticationFailureHandler"/>
<security:access-denied-handler ref="accessDeniedHandler" />
</security:http>
-> this gets blatantly ignored by spring-security/oauth
Add a custom filter after the EXCEPTION_TRANSLATION_FILTER
<security:custom-filter after="EXCEPTION_TRANSLATION_FILTER" ref="myFilter" />
MyFilter just implements "javax.servlet.Filter".
-> It goes into the doFilter but i have no idea what do with it (i can't see which exception is thrown, if any).
Any help is appreciated!!
I am quite late answering this question and you might have resolved or moved to some other alternative. However I recently dived into the Oauth and faced similar problem and managed to resolve it. Sharing it as reference for others.
I have used Oauth's MediaTypeAwareAccessDeniedHandler and MediaTypeAwareAuthenticationEntryPoint for error handling. As per documentation, it defaults to 401 error page. However, from source code, error response content type is dependent upon request Accept-Type. But requesting clients to always sent Accept-Type as application/json is like asking fox to safeguard hen.
Good news is that response type support setter injection. So simple solution was to override defaults and inject response property to always sent JSON response irrespective of Accept-Type
<bean id="accessDeniedHandler" class="org.springframework.security.oauth2.provider.error.MediaTypeAwareAccessDeniedHandle"/>
<property name="responses">
<map>
<entry key="*/*" value="{error:"%s"}"></entry>
</map>
</property>
</bean>

Spring security oauth 2 simple example

I try to implement my own example based on official tutorial Sparklr2/Tonr2. Everything looks good but when I remove from web.xml in my Tonr2 implementation, spring security filter I have exception:
No redirect URI has been established for the current request
I can't understand what URL should I use. Here is my code, for client implementation:
<!--apply the oauth client context -->
<oauth:client id="oauth2ClientFilter" />
<!--define an oauth 2 resource for sparklr -->
<oauth:resource id="provider" type="authorization_code" client-id="client" client-secret="secret"
access-token-uri="http://localhost:8080/provider/oauth/token" user-authorization-uri="http://localhost:8080/provider/oauth/authorize" scope="read,write" />
<beans:bean id="clientController" class="com.aouth.client.ClientController">
<beans:property name="trustedClientRestTemplate">
<oauth:rest-template resource="provider" />
</beans:property>
</beans:bean>
And for provider:
<http pattern="/oauth/token" create-session="stateless" authentication-manager-ref="clientAuthenticationManager" xmlns="http://www.springframework.org/schema/security">
<intercept-url pattern="/oauth/token" access="IS_AUTHENTICATED_FULLY" />
<anonymous enabled="false" />
<http-basic />
</http>
<authentication-manager id="clientAuthenticationManager" xmlns="http://www.springframework.org/schema/security">
<authentication-provider user-service-ref="clientDetailsUserService" />
</authentication-manager>
<bean id="clientDetailsUserService" class="org.springframework.security.oauth2.provider.client.ClientDetailsUserDetailsService">
<constructor-arg ref="clientDetails" />
</bean>
<!-- The OAuth2 protected resources are separated out into their own block so we can deal with authorization and error handling
separately. This isn't mandatory, but it makes it easier to control the behaviour. -->
<http pattern="/secured" create-session="never" access-decision-manager-ref="accessDecisionManager" xmlns="http://www.springframework.org/schema/security">
<anonymous enabled="false" />
<intercept-url pattern="/secured" access="ROLE_USER,SCOPE_READ" />
<custom-filter ref="resourceServerFilter" before="PRE_AUTH_FILTER" />
<http-basic />
</http>
<bean id="accessDecisionManager" class="org.springframework.security.access.vote.UnanimousBased" xmlns="http://www.springframework.org/schema/beans">
<constructor-arg>
<list>
<bean class="org.springframework.security.oauth2.provider.vote.ScopeVoter" />
<bean class="org.springframework.security.access.vote.RoleVoter" />
<bean class="org.springframework.security.access.vote.AuthenticatedVoter" />
</list>
</constructor-arg>
</bean>
<oauth:resource-server id="resourceServerFilter" resource-id="resource" token-services-ref="tokenServices" />
<bean id="tokenServices" class="org.springframework.security.oauth2.provider.token.DefaultTokenServices">
<property name="tokenStore" ref="tokenStore" />
<property name="supportRefreshToken" value="true" />
<property name="clientDetailsService" ref="clientDetails"/>
</bean>
<bean id="tokenStore" class="org.springframework.security.oauth2.provider.token.InMemoryTokenStore" />
<http auto-config="true" xmlns="http://www.springframework.org/schema/security">
<intercept-url pattern="/test" access="ROLE_USER" />
<intercept-url pattern="/" access="IS_AUTHENTICATED_ANONYMOUSLY" />
</http>
<authentication-manager alias="authenticationManager" xmlns="http://www.springframework.org/schema/security">
<authentication-provider>
<user-service>
<user name="pr" password="pr" authorities="ROLE_USER" />
</user-service>
</authentication-provider>
</authentication-manager>
<oauth:authorization-server client-details-service-ref="clientDetails" token-services-ref="tokenServices" >
<oauth:authorization-code />
<oauth:implicit />
<oauth:refresh-token />
<oauth:client-credentials />
<oauth:password />
</oauth:authorization-server>
<oauth:client-details-service id="clientDetails">
<oauth:client client-id="client" resource-ids="resource" authorized-grant-types="authorization_code, implicit"
authorities="ROLE_CLIENT" scope="read,write" secret="secret" />
</oauth:client-details-service>
I just want my client to work without spring security. And when I need my protected resource I want to login only on provider side.
You 2nd XML that you pasted here is the spring's XML for the oauth-provider and the protected-resource, which in your case run in the same webapp. (you can separate them, of course, if you wish).
The client (the 1st pasted-XML) is a different story. If I understand you correctly, you want your client to run without Spring's help (to be a regular webapp, and not spring-security-oauth-client webapp).
You have to understand how oAuth works: the client tries to get to a protected resource; if it does not have the access-token, it is being redirected to the oAuth-provider (that shows the login page and supplies the token). By the standard, the request for the access-token MUST contain a "redirect-uri" param, so after a successful login, the oAuth-provider knows where to redirect the client to. The oAuth client does it for you, and if you delete the "oauth client" from your web.xml, you now have to implement this by yourself.
Thanks for your answer. But I still don't understand how spring
security influences my oAuth client. And can I use for client side
spring-oauth (spring-mvc) without spring-security?
When you write this line in your XML:
< oauth:client id="oauth2ClientFilter" />
it means that you use spring-security-oauth, which is a package dedicated for oauth, built on spring-security. If you dig in, it puts a special filter (OAuth2ClientContextFilter) in the chain that handles the oAuth stuff, that are relevant for the client. One of them is sending the request with all the params ("redirect-uri" is one of them).
If you decide NOT to use spring-security-oauth, well - you will have to implement this logic by yourself...
Hope that helps!

Spring Security 3 SavedRequestAwareAuthenticationSuccessHandler not saving original request

I am trying to configure spring security 3 so that when a users is forced to login again (eg. when the session has timed out) the user will be taken back the the page they where on before the authorisation process began.
I am using a SavedRequestAwareAuthenticationSuccessHandler but the original request does not seem to be saved in the cache.
Below is my security configuration.
<security:http auto-config="false"
use-expressions="true"
access-denied-page="/views/auth/login?error=true"
entry-point-ref="authenticationEntryPoint" >
<security:intercept-url pattern="/*" access="hasRole('ROLE_USER')" />
<security:intercept-url pattern="/views/*" access="hasRole('ROLE_USER')" />
<security:intercept-url pattern="/data/*" access="hasRole('ROLE_USER')" />
<security:intercept-url pattern="/auth/*" access="permitAll" />
<security:logout invalidate-session="true" logout-success-url="/views/auth/login" logout-url="/views/auth/logout" />
<security:session-management invalid-session-url="/views/auth/login" >
<security:concurrency-control max-sessions="1" error-if-maximum-exceeded="true" />
</security:session-management>
<security:custom-filter ref="authenticationFilter" position="FORM_LOGIN_FILTER"/>
</security:http>
<security:authentication-manager />
<bean id="authenticationFilter" class="com.security.web.filter.UsernamePasswordAuthenticationFilter">
<property name="allowSessionCreation" value="true" />
<property name="authenticationManager" ref="authenticationManager"/>
<property name="authenticationFailureHandler" ref="aAuthenticationFailureHandler" />
<property name="authenticationSuccessHandler" ref="authenticationSuccessHandler" />
</bean>
<bean id="authenticationManager" class="com.security.web.manager.AuthenticationManager" />
<bean id="authenticationEntryPoint" class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint" >
<property name="loginFormUrl" value="/views/auth/login"/>
</bean>
<bean id="authenticationFailureHandler" class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler">
<property name="defaultFailureUrl" value="/views/auth/login?error=true"/>
</bean>
<bean id="authenticationSuccessHandler" class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler">
<property name="defaultTargetUrl" value="/views"/>
</bean>
Any help would be appreciated.
I know this question is old, but I wanted to document what I found for others.
Short Answer
The problem is that if you use the invalid-session-url on the <session-management> tag, then the original request will not be saved in the cache.
Explanation
This is discussed at the spring source forum:
http://forum.springsource.org/showthread.php?89352-requestCache-null-when-using-session-management-gt-invalid-session-url
In the above forum, Luke Taylor, a senior member of the security team says:
The invalid-session-url implies that the previous session has expired and the user should start again. There's no connection with the RequestCache which is used for restoring a request after a user has logged in.
and
When a session expires you can't know that it is safe to continue with the requested URL as some required state may have been lost along with the session. It may be OK in your particular case, but it's not a safe assumption in general.
You may be missing this :
<bean id="requestCacheAwareFilter"
class="org.springframework.security.web.savedrequest.RequestCacheAwareFilter">
<constructor-arg ref="requestCache"/>
</bean>
<bean id="requestCache" class="org.springframework.security.web.savedrequest.HttpSessionRequestCache"/>
also you need to add requestCache been to authenticationSuccessHandler
<property name="requestCache" ref="requestCache"/>

Mapping each http block to a specific Authentication Provider

I would like to base my Spring Security configuration depending on the user's context path. If the user goes against a url with http://path1/resource1 I would like to direct them to a specific authentication provider. If they come in on http://path2/resource2 I would like to direct them to a different authentication provider. These url paths are REST based web services calls so that's why they're stateless and not coming from a form. Currently, all authentication providers get executed. What is the best approach for this situation? I'm using spring-security 3.1.0.M1.
<http pattern="/path1/**" create-session="stateless">
<intercept-url pattern="/**" access="ROLE_USER,ROLE_VAR,ROLE_ADMIN" />
<http-basic />
</http>
<http pattern="/path2/**" create-session="stateless">
<intercept-url pattern="/**" access="ROLE_USER,ROLE_VAR,ROLE_ADMIN" />
<http-basic />
</http>
You can define an authentication-manager reference in each http block:
<http pattern="/api/**" authentication-manager-ref="apiAccess">
...
</http>
<http auto-config = "true" authentication-manager-ref="webAccess">
...
</http>
<!-- Web authentication manager -->
<authentication-manager id="webAccess">
<authentication-provider
user-service-ref="userService">
</authentication-provider>
</authentication-manager>
<!-- API authentication manager -->
<authentication-manager id="apiAccess">
<authentication-provider
user-service-ref="developerService">
</authentication-provider>
</authentication-manager>
This feature has been added in Spring Security 3.1.
This works for me:
<security:authentication-manager alias="basicAuthenticationManager">
<security:authentication-provider user-service-ref="accountService">
<security:password-encoder hash="sha"/>
</security:authentication-provider>
<security:authentication-provider user-service-ref="accountService"/>
</security:authentication-manager>
<bean id="basicProcessingFilter" class="org.springframework.security.web.authentication.www.BasicAuthenticationFilter">
<property name="authenticationManager">
<ref bean="basicAuthenticationManager" />
</property>
<property name="authenticationEntryPoint">
<ref bean="basicProcessingEntryPoint" />
</property>
</bean>
<bean id="basicProcessingEntryPoint"
class="com.yourpackage.web.util.CustomBasicAuthenticationEntryPoint">
<property name="realmName" value="yourRealm" />
</bean>
<!-- Stateless RESTful service using Basic authentication -->
<security:http pattern="/rest/**" create-session="stateless" entry-point-ref="basicProcessingEntryPoint">
<security:custom-filter ref="basicProcessingFilter" position="BASIC_AUTH_FILTER" />
<security:intercept-url pattern="/rest/new" access="IS_AUTHENTICATED_ANONYMOUSLY" />
<security:intercept-url pattern="/rest/**" access="ROLE_USER" />
</security:http>
<!-- Additional filter chain for normal users, matching all other requests -->
<security:http use-expressions="true">
<security:intercept-url pattern="/index.jsp" access="permitAll" />
<security:intercept-url pattern="/**" access="hasRole('ROLE_USER')" />
<security:form-login login-page="/signin"
authentication-failure-url="/signin?signin_error=1"
default-target-url="/"
always-use-default-target="true"/>
<security:logout />
</security:http>
I implemented the authentication entry point because I needed to send some special error codes in certain situations but you don't need to do so.

Resources