NoUniqueBeanDefinitionException with multiple http sections in Spring Security - java

I'm writing a RESTful web service that requires multiple authentication mechanisms (basic, x509, and anonymous). I therefore have three <http> elements in three separate spring context files.
When I start my service, I'm getting the following exception:
org.springframework.beans.factory.NoUniqueBeanDefinitionException:
No qualifying bean of type [org.springframework.security.web.SecurityFilterChain]
is defined: expected single matching bean but found 3:
org.springframework.security.web.DefaultSecurityFilterChain#0,
org.springframework.security.web.DefaultSecurityFilterChain#1,
org.springframework.security.web.DefaultSecurityFilterChain#2
I think this makes sense, right? I've defined three <http> elements, so spring is probably creating three instances of org.springframework.security.web.DefaultSecurityFilterChain. And now someone is asking for a bean of type org.springframework.security.web.SecurityFilterChain, and is finding three.
But, according to Spring Security documentation, this is supposed to be possible, so my question is: How do I get this scenario to work?
Here are my three <http> configurations:
x509Auth.xml:
<sec:http pattern="/service/x509/**" use-expressions="true">
<sec:x509 subject-principal-regex="(.*)" user-service-ref="ldapUserDetailsService" />
<sec:intercept-url pattern="/service/x509/identity/**" access="hasRole('Domain Users')" />
</sec:http>
basicAuth.xml:
<sec:http pattern="/anubis/basic/**" use-expressions="true" create-session="stateless">
<sec:intercept-url pattern="/service/basic/identity/**" access="isAuthenticated()" />
<sec:http-basic />
</sec:http>
noAuth.xml:
<sec:http pattern="/service/anonymous/**" security="none" />

Thanks to this InfoQ post, I learned that with new flexibility comes new responsibility. Since you can have multiple <http> elements now, you can also have multiple authentication managers. This requires us to tell spring which authentication manager goes with each<http> element.
Here is my now-working spring configuration:
<!-- This section configures X509 Certificate Authentication -->
<sec:http
pattern="/service/x509/**"
use-expressions="true"
authentication-manager-ref="ldapAuthenticationManager">
<sec:x509 subject-principal-regex="(.*)" user-service-ref="ldapUserDetailsService" />
<sec:intercept-url pattern="/service/x509/identity/**" access="hasRole('Domain Users')" />
</sec:http>
<sec:authentication-manager alias="ldapAuthenticationManager">
<sec:authentication-provider user-service-ref="ldapUserDetailsService" />
</sec:authentication-manager>
<!-- This section configures BASIC Authentication -->
<sec:http
pattern="/service/basic/**"
use-expressions="true"
create-session="stateless"
authentication-manager-ref="mongoAuthenticationManager">
<sec:http-basic />
<sec:intercept-url pattern="/service/basic/identity/**" access="isAuthenticated()" />
</sec:http>
<sec:authentication-manager alias="mongoAuthenticationManager">
<sec:authentication-provider user-service-ref="mongoUserDetailsService" />
</sec:authentication-manager>
<!-- This section configures NO Authentication -->
<sec:http pattern="/service/anonymous/**" security="none" />

Related

Accessing user name in the socket controller method while Integrating spring security with spring websocket and

I am implementing spring web socket into our web application and I want to access the user name in the socket controller method but I am getting it as null.
Here is the code
#MessageMapping("/user/sockettest" )
#SendTo("/topic/sockettestresult")
public String sockAdd(ListId[] listIds) {
..
SecurityContextHolder.getContext().getAuthentication().getPrincipal();
return stringRet;
}
The spring-security xml looks like this
<sec:intercept-url pattern="/topic/**" access="permitAll" />
<sec:intercept-url pattern="/" access="permitAll" />
<sec:intercept-url pattern="/login*" access="permitAll" />
<sec:intercept-url pattern="/resources/**" access="permitAll" />
<sec:form-login login-page="/login" default-target-url="/user/home" always-use-default-target="true" authentication-failure-url="/login?error"/>
<sec:logout logout-success-url="/login?logout" delete-cookies="JSESSIONID" />
<sec:access-denied-handler error-page="/denied"/>
<sec:intercept-url pattern="denied/*" access="permitAll" />
<sec:csrf disabled="true" />
</sec:http>
The socket configuration looks like this
<websocket:stomp-endpoint path="/user/sockettest">
<websocket:sockjs/>
</websocket:stomp-endpoint>
<websocket:simple-broker prefix="/topic"/>
<websocket:message-converters register-defaults="false">
<bean id="mappingJackson2MessageConverter" class="org.springframework.messaging.converter.MappingJackson2MessageConverter">
<property name="objectMapper" ref="objectMapper"></property>
</bean>
</websocket:message-converters>
</websocket:message-broker>
I have looked at some examples and most of them are in java config, however the problem that I have with that is that when I use java config, it is adding an extra /info to the destination url and it is not even connecting to the socket so I am taking the xml route.
I am pretty new to spring web sockets and I am thinking that I am missing something while integrating it with spring security but that's just me. Let me know what I am doing wrong here?
You can access current user by adding java.security.Principal parameter to socket controller method.
#MessageMapping("/user/sockettest" )
#SendTo("/topic/sockettestresult")
public String sockAdd(ListId[] listIds, Principal principal) {
//do whatever you want
return stringRet;
}
docs

Where does Spring Security get its default http configuration from?

I'm using Spring Security 3.2.4 and trying to determine where it gets its default configuration from. For example, when using the following configuration:
<http use-expressions="true">
<intercept-url pattern="/secure/login" access="permitAll" />
<intercept-url pattern="/secure/logout" access="permitAll" />
<intercept-url pattern="/secure/denied" access="permitAll" />
<session-management session-fixation-protection="migrateSession" session-authentication-error-url="/login.jsp?authFailed=true">
<concurrency-control max-sessions="10" error-if-maximum-exceeded="true" expired-url="/login.html" session-registry-alias="sessionRegistry"/>
</session-management>
<intercept-url pattern="/**" access="isAuthenticated()" />
<form-login login-page="/secure/login" default-target-url="/" authentication-failure-url="/secure/denied" />
<logout logout-url="/secure/logout" logout-success-url="/" />
<expression-handler ref="defaultWebSecurityExpressionHandler" />
</http>
Something in a Spring configuration somewhere, is telling Spring to instantiate the LoginUrlAuthenticationEntryPoint and set the login-page to "/secure/login", etc. I realize that it is the form-login tag that is doing this magic for me, but where within Spring is the form-login tag translated to mean the LoginUrlAuthenticationEntryPoint, etc?
Similarly, by default, Spring will instantiate a filter chain of name org.springframework.security.filterChains, but can't find where that bean is defined. I presume it is in an xml configuration file within one of the Spring Security jars, but I can't find it anywhere.
Where are all these defaults configured?
Check out SecurityNamespaceHandler and work your way down from there. As you can see, it is in the spring-security-config artifact, in package org.springframework.security.config.

Using Spring Security 3.1 to secure the same RESTful resources with both form-login and http-basic security

I have a java web application running on Tomcat 7.
I am using Spring 3.2 with Spring Security 3.1 on the backend, and am exposing an API via RESTful URLs following the /api/** pattern.
The UI for the web application is built using BackboneJS. I am using Backbone models mapped directly to the RESTful URLS.
The UI is locked down using form-login authentication, so the user is always redirected to the login screen if they have are not currently authenticated.
I am now attempting to expose the same RESTful URLs to another external service using http-basic authentication. Unfortunately, when securing the same URL pattern, it seems Spring will not allow me to use more than one filter chain. Whichever is defined first in the configuration file seems to take precedence.
I would hate to have to map to separate URL patterns for the same RESTful resources, but it seems like I may not have a choice.
Here is the important sample of my (currently broken) spring security configuration:
<!-- configure basic http authentication -->
<http pattern="/api/**" create-session="stateless">
<intercept-url pattern="/**" access="ROLE_USER"/>
<http-basic/>
</http>
<!-- configure form-login authentication -->
<http auto-config="true" use-expressions="true">
<intercept-url pattern="/ui/login" access="permitAll" />
<intercept-url pattern="/ui/logout" access="permitAll" />
<intercept-url pattern="/ui/loginfailed" access="permitAll" />
<intercept-url pattern="/**" access="ROLE_USER" />
<custom-filter ref="ajaxTimeoutRedirectFilter" after="EXCEPTION_TRANSLATION_FILTER" />
<form-login login-page="/ui/login" default-target-url="/" authentication-failure-url="/ui/loginfailed" />
<logout logout-success-url="/ui/logout" />
<session-management invalid-session-url="/ui/login"/>
</http>
My question is:
Is it possible to configure two different types of security (http-basic and form-login) for the same URL patterns using Spring Security? Is there a best practice for this type of scenario?
Thank you.
Why don't you just merge the two <http> elements like this:
<http pattern="/api/**" use-expressions="true">
<intercept-url pattern="/ui/login" access="permitAll" />
<intercept-url pattern="/ui/logout" access="permitAll" />
<intercept-url pattern="/ui/loginfailed" access="permitAll" />
<intercept-url pattern="/**" access="ROLE_USER" />
<http-basic/>
<custom-filter ref="ajaxTimeoutRedirectFilter" after="EXCEPTION_TRANSLATION_FILTER" />
<form-login login-page="/ui/login" default-target-url="/" authentication-failure-url="/ui/loginfailed" />
<logout logout-success-url="/ui/logout" />
<session-management invalid-session-url="/ui/login"/>
</http>
This would set up both a UsernamePasswordAuthenticationFilter and a BasicAuthenticationFilter in the same filter chain which could serve the ui client, and the external service as well.
Not possible out of the box to apply 2 different filter chain for a single URL pattern.
But it is a advisable to have unique URL patterns as UI and API, as you would have to apply a completely different filter chain in future.
For example the SecurityContextRepository hold the session information and is retrieved for each request. You don't want to apply the same for UI and API access through basic auth
Try to replace pattern="/" by pattern="/api/" in API config:
<http pattern="/api/**" create-session="stateless">
<intercept-url pattern="/api/**" access="ROLE_USER"/>
<http-basic/>
</http>

How to access resource bundle in login page of spring application using spring security

I want to use resource bundle in login page
using tag <spring:message code="login.name" /> but i am getting error as
No message found under code 'login.name' for locale 'en_US'.
I have referred this answer below ,but it is not working for me.
Can I use in Spring the Message Resource Bundle when calling a JSP directly
This is a sample snipped from my spring security.xml
<sec:global-method-security pre-post-annotations="enabled" />
<sec:http pattern="/css/**" security="none"/>
<sec:http pattern="/images/**" security="none"/>
<sec:http pattern="/js/**" security="none"/>
<sec:http pattern="/index.jsp" security="none"/>
<!-- <sec:http pattern="/app/addNewUser.json" security="none"/> -->
<sec:http pattern="/login.jsp" security="none"/>
<sec:http use-expressions="true">
<!--
Allow all other requests. In a real application you should
adopt a whitelisting approach where access is not allowed by default
-->
<sec:intercept-url pattern="/**" access="isAuthenticated()" />
<sec:form-login login-page='/login.jsp'
authentication-failure-url="/login.jsp?login_error=1"
default-target-url="/index.jsp" />
<sec:logout logout-success-url="/login.jsp" delete-cookies="JSESSIONID"/>
<sec:remember-me />
Any suggestion ?
Its my perception that login request should be routed via controller then I will be able to access the resource bundle but how to do that?
Put your login.jsp under WEB-INF directory.

Spring Security 3.1.0.RC1: With multiple <http.../> elements why can I only register one authentication manager?

I have the following configuration with multiple <http.../> elements (in order to separately support REST authetication via basic auth, and user form login):
<security:http auto-config="false" pattern="/service/**" create-session="never"
entry-point-ref="basicAuthenticationEntryPoint" >
<security:intercept-url pattern="/service/**" requires-channel="any" access="ROLE_REST_SERVICE" />
<security:custom-filter position="BASIC_AUTH_FILTER" ref="basicAuthenticationFilter" />
</security:http>
<security:http auto-config="false" pattern="/**"
entry-point-ref="loginUrlAuthenticationEntryPoint" >
<security:logout logout-url="/logout" />
<security:anonymous enabled="false"/>
<security:custom-filter position="FORM_LOGIN_FILTER" ref="usernamePasswordAuthenticationFilter" />
<security:custom-filter position="ANONYMOUS_FILTER" ref="anonymousAuthFilter" />
</security:http>
In each of my two filters requiring authentication (FORM_LOGIN_FILTER, and BASIC_AUTH_FILTER) I reference two different authentication managers.
But I get an error that I've already registered an authentication manager.
Why would I use one authentication manager when I know before hand which Authentication provider is going to be needed for each filter?
Should I not use the authentication manager and just start my AuthenticationProvider as a bean and pass it into the filter directly as the AuthenticationManager?
In spring security 3.1 you can have multiple http elements, each with their own authentication manager.
The only thing you need to do is add the following attribute authentication-manager-ref="your ref" to the http element.

Categories

Resources