Handling both form and HTTP basic authentication with different sources - spring-security

I already have form login and Basic auth working side by side with the help of a DelegatingAuthenticationEntryPoint.
What I'm trying to do is have users coming thru the login form to be authenticated against criteria "A", and have users coming thru the Basic auth requests to be authenticated against criteria "B".
Some of the application's resources are exposed thru a RESTful service (accessible via Basic auth). Instead of having users enter their own credentials to make a REST service call, they can enter generated key/value pairs for use exclusively with the REST service that can later be revoked by the user or by the app administrator.
I would prefer to share as much of my security-specific beans as possible between the two methods of authentication. I know I will need separate UserDetailsServices as the form login queries my users table, and Basic auth will query my service_credentials table.
What is the correct way to achieve this kind of configuration in Spring Security?

Depending on your app and whether you're using Spring Security 3.1, you might be best to split the configuration into multiple filter chains, each with a separate authentication manager defined:
<http pattern="/rest_api/**" create-session="stateless"
authentication-manager-ref="serviceCredsAuthMgr">
<http-basic />
</http>
<http authentication-manager-ref="mainAuthMgr">
<form-login />
</http>
<authentication-manager id="serviceCredsAuthMgr">
<authentication-provider user-service-ref="serviceCredsUserDetailsSvc" />
</authentication-manager>
<authentication-manager id="mainAuthMgr">
<!-- whatever -->
</authentication-manager>
Instead of the pattern attribute you can also use the request-matcher-ref attribute to specify a RequestMatcher instance which will be used to map incoming requests to a particular filter chain. This has a very simple interface, but can allow you to match based on something other than the URL path, such as the Accept header.

With SpringSecurity (3.2.3.RELEASE) work fine form as well as basic auth:
<http pattern="/resources/**" security="none"/>
<http pattern="/webjars/**" security="none"/>
<http pattern="/rest/**" create-session="stateless" use-expressions="true">
<intercept-url pattern="/**" access="isFullyAuthenticated()"/>
<http-basic />
</http>
<http auto-config="true" use-expressions="true">
<http-basic/>
<intercept-url pattern="/login" access="permitAll"/>
<intercept-url pattern="/loginfailed" access="permitAll"/>
<intercept-url pattern="/logout" access="permitAll"/>
<intercept-url pattern="/admin**" access="hasRole('ROLE_ADMIN')"/>
<intercept-url pattern="/**" access="isAuthenticated()"/>
<form-login login-page="/login" default-target-url="/" authentication-failure-url="/loginfailed"/>
<logout logout-success-url="/logout"/>
<remember-me user-service-ref="userService"/>
</http>
<authentication-manager>
<authentication-provider user-service-ref="userService">
<!--
<jdbc-user-service data-source-ref="dataSource"
users-by-username-query="SELECT email, password, enabled FROM users WHERE email = ?"
authorities-by-username-query="
SELECT u.email, r.name FROM users u, roles r WHERE u.id = r.user_id and u.email = ?"/>
-->
<!--
<user-service>
<user name="mail#yandex.ru" password="password" authorities="ROLE_USER"/>
<user name="admin#gmail.com" password="admin" authorities="ROLE_ADMIN"/>
</user-service>
-->
</authentication-provider>
</authentication-manager>

Related

How to redirect user to authentication page when he tries to enter the url of the secured page ?

I'm using spring security to authenticate users, if it's the right user :he has access to the home page ..
But when I tried to enter with the url (without entering my name or my password ) an anonymous user can see the home page !
My application is not secured !
Could someone help me please ?
This is my spring-securityConfig.xml :
<http auto-config="true">
<form-login login-page="/login" username-parameter="j_username"
password-parameter="j_password" default-target-url="/accueil"
authentication-failure-url="/403" always-use-default-target="true" />
<logout logout-success-url="/login" />
<http-basic/>
<intercept-url pattern="/**" />
</http>
<authentication-manager>
<authentication-provider ref="userService">
</authentication-provider>
</authentication-manager>
You don't have to do anything for the redirection, it comes with Spring Security by default. It's just that your home page isn't secure. Did you try
<intercept-url pattern="/login*" access="permitAll" />
<intercept-url pattern="/**" access="isAuthenticated()" />

spring securit3.x y integration with wicket 6.7.0

I am new to wicket and SpringSecurity. I configured the spring security as follows.
<http create-session="never" auto-config="true">
<remember-me />
<http-basic />
<intercept-url pattern="/**" requires-channel="https" />
<!-- <form-login login-page="/admin"/> <logout invalidate-session="true"
logout-url="/j_spring_security_logout" logout-success-url="/admin" delete-cookies="JSESSIONID"/> -->
<session-management session-fixation-protection="migrateSession">
<concurrency-control max-sessions="1"
error-if-maximum-exceeded="true" />
</session-management>
</http>
<authentication-manager alias="authenticationManager">
<authentication-provider user-service-ref="userDetailsService"></authentication-provider>
</authentication-manager>
<global-method-security secured-annotations="enabled" />
I have extended the AuthenticatedWebSession doing the authentication in my extended class.
My Questions :
How can I configure for form based Authentication.
How can I configure for Session Management.
How can I configure for Single Sign in per user (Here if the user try to login with same user I want invalidate the session of the previous logged in user. )
Need reference manual on Spring Security Integration with Wicket.
Please also let me know if I am missing anything.
you can have a look at the following working example on Wicket / Spring-Security integration on github: https://github.com/thombergs/wicket-spring-security-example.
Your questions are a little vague for a helpful answer, so I'd suggest yoiu have a look at the example on github and ask again if you have any problems.
Regards,
Tom

Removing Session in Spring Security

I want to put security for all the URL's except the login screen URL in spring security,
but I don't want to use session management.
Please help me out in this issue.
my security context file is below
<security:http pattern="/" security="none" />
<security:http auto-config="false" use-expressions="true" create-session="stateless" access-denied-page="/" entry-point-ref="authenticationEntryPoint" >
<security:intercept-url pattern="/**" access="isAuthenticated()" />
<security:intercept-url pattern="/logout" access="permitAll" />
<security:intercept-url pattern="/logout.jsp" access="permitAll" />
<security:logout logout-url="/j_spring_security_logout" />
<security:custom-filter ref="authenticationFilter" position="FORM_LOGIN_FILTER"/>
</security:http>
The ordering of your intercept-url tags is wrong. Quote from the reference docs:
You can use multiple elements to define different access requirements for different sets of URLs, but they will be evaluated in the order listed and the first match will be used. So you must put the most specific matches at the top.
Move the intercept-url with the universal match pattern to the bottom of the list.

Spring Security Preauth "filters=none" not working

strange one,
I am using spring security with siteminder and it works fine. However I want to have one url which isn't protected - our loadBalancer needs a "healthCheck" url within the app itself. This url isn't intercepted by siteminder, but spring security seems to apply the preauth to it anyhow..
if I run it locally using a simple forms-based security config the following works (excluding the filters):
<http auto-config="true" use-expressions="true">
<intercept-url pattern="/html/healthCheck.html" filters="none" />
<intercept-url pattern="/css/**" filters="none" />
<intercept-url pattern="/images/**" filters="none" />
<intercept-url pattern="/js/**" filters="none" />
<intercept-url pattern="/login" filters="none" />
<intercept-url pattern="/favicon.ico" filters="none" />
<intercept-url pattern="/*" access="hasAnyRole('ROLE_USER')" />
<form-login login-page="/login" default-target-url="/" authentication-failure-url="/loginfailed" />
<logout logout-success-url="/logout" />
</http>
In this case, I can browse to localhost/myApp/resources/html/healthCheck.html without hitting an authorization issue, but any other url will display the login form. All looking good so far!
However when I deploy to the server I am using the following config:
<http auto-config="true" use-expressions="true">
<intercept-url pattern="/html/healthCheck.html" filters="none" />
<intercept-url pattern="/css/**" filters="none" />
<intercept-url pattern="/images/**" filters="none" />
<intercept-url pattern="/js/**" filters="none" />
<intercept-url pattern="/login" filters="none" />
<intercept-url pattern="/favicon.ico" filters="none" />
<intercept-url pattern="/*" access="hasAnyRole('ROLE_USER')" />
<custom-filter position="PRE_AUTH_FILTER" ref="siteminderFilter" />
</http>
When I browse to: server/myapp/resources/html/healthCheck.html I get the following error:
java.lang.IllegalArgumentException: Cannot pass null or empty values to constructor
org.springframework.security.core.userdetails.User.<init>(User.java:94)
com.myApp.security.SecuritySBSUserDetailsService.loadUserByUsername(SecuritySBSUserDetailsService.java:119)
org.springframework.security.core.userdetails.UserDetailsByNameServiceWrapper.loadUserDetails(UserDetailsByNameServiceWrapper.java:53)
I think this is caused by the UserDetailsService getting instantiated without any SM_USER. Yet the filters=none is in place.. and works when using forms authentication..Any idea what might be causing this, or better - of a workaround?
By the way, my userdetails service is configured as follows:
<beans:bean id="siteminderFilter" class="org.springframework.security.web.authentication.preauth.RequestHeaderAuthenticationFilter">
<beans:property name="principalRequestHeader" value="SM_USER" />
<beans:property name="exceptionIfHeaderMissing" value="false" />
<beans:property name="authenticationManager" ref="authenticationManager" />
</beans:bean>
i.e. I've set exceptionIfHeaderMissing to false, if that helps..
The most obvious thing I can see is that /resources/html/healthCheck.html won't be matched by /html/healthCheck.html. If you are rewriting the URLs somewhere you should probably explain that.
If you enable debug logging, it should explain in detail what is matched against what.
I'd also leave out the auto-config. It causes more confusion than it is worth. And you should use /** rather than /* for a universal ant pattern match.
It's probably also worth mentioning here that Spring Security 3.1 has a better approach for defining empty filter chains, and also allows you to define more than one filter chain using the <http> syntax.
Okay, it seems to be a bug in spring security as far as I can see. I got around it by adding a dummy return to the start of the loadUserByName method in the UserDetailsService..
#Override
public UserDetails loadUserByUsername(String userName)
throws UsernameNotFoundException, DataAccessException {
logger.trace(">> loadUserByUsername()");
logger.info("-- loadUserByUsername(): username : {}", userName);
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
if(userName==null || userName.trim().equals("")) {
return(new User("ANONYMOUS", "", true, true, true, true, authorities));
}
// rest of auth checks
It would seem like with the config I have, the UserDetails check shouldn't be getting triggered at all (as it is with the forms..). If anyone has a configuration based workaround I'll give you a plus :-)

Spring Security 3.0 - Intercept-URL - All pages require authentication but one

I want any user to be able to submit their name to a volunteer form but only administrators to be able to view any other URL. Unfortunately I don't seem to be able to get this correct. My resources.xml are as follows;
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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.0.xsd">
<http realm = "BumBumTrain Personnel list requires you to login" auto-config="true" use-expressions="true">
<http-basic/>
<intercept-url pattern="/person/volunteer*" access=""/>
<intercept-url pattern="/**" access="isAuthenticated()" />
</http>
<authentication-manager alias="authenticationManager">
<authentication-provider>
<user-service>
<user name="admin" password="admin" authorities="ROLE_ADMIN"/>
</user-service>
</authentication-provider>
</authentication-manager>
</beans:beans>
Specifically I am trying to achieve the access settings I described via;
<intercept-url pattern="/person/volunteer*" access=""/>
<intercept-url pattern="/**" access="isAuthenticated()" />
Could someone please describe how to use intercept-url to achieve the outcome I've described?
Thanks
Gav
For whatever reason in a grails app I needed;
<intercept-url pattern="/person/volunteer/**" access="" filters="none"/>
<intercept-url pattern="/images/**" access="" filters="none"/>
<intercept-url pattern="/css/**" access="" filters="none"/>
<intercept-url pattern="/js/**" access="" filters="none"/>
<intercept-url pattern="/**" access="ROLE_ADMIN" />
To get this to work, note the difference in the first rule.
What exactly does not work as you expect? what goes wrong?
I think access="" does not what you expect... Use the format from the docs:
<intercept-url pattern="/login.jsp*" filters="none"/>
If you don't use the default authentication (which you do) you would need to add a WebExpressionVoter because you use expressions expressions doc
Hi replace access="" with access="permitAll" for the url you want to make accessile without authentication.

Resources