Spring Security 3 RestTemplate POST to j_spring_security_check - spring

I am using Spring Security 3 with REST endpoints. I managed to get a basic Spring Security working.
Part of the security-context.xml
<security:http auto-config="true" use-expressions="true" access-denied-page="/rest/denied" >
<security:intercept-url pattern="/rest/*" access="ROLE_USER"/>
and basic config as found on the web
<security:authentication-manager>
<security:authentication-provider user-service-ref="userDetailsService">
<security:password-encoder ref="passwordEncoder"/>
</security:authentication-provider>
<!-- Use a Md5 encoder since the user's passwords are stored as Md5 in the database -->
<bean class="org.springframework.security.authentication.encoding.Md5PasswordEncoder" id="passwordEncoder"/>
<!-- An in-memory list of users. No need to access an external database layer.
See Spring Security 3.1 Reference 5.2.1 In-Memory Authentication -->
<!-- john's password is admin, while jane;s password is user -->
<security:user-service id="userDetailsService">
<security:user name="john" password="21232f297a57a5a743894a0e4a801fc3" authorities="ROLE_USER, ROLE_ADMIN" />
<security:user name="jane" password="ee11cbb19052e40b07aac0ca060c23ee" authorities="ROLE_USER" />
</security:user-service>
I want to login to j_spring_security_check using a RestTemplate POST.
HttpEntity<String> entity = new HttpEntity<String>(request, headers);
HashMap<String, String> map = new HashMap<String, String>();
map.put("j_username", "john");
map.put("j_password","21232f297a57a5a743894a0e4a801fc3");
String response = restTemplate.postForObject("http://localhost:8080/rest/j_spring_security_check", map, String.class);
but in the log, it seems the username parameter is not being read
DEBUG o.s.s.authentication.ProviderManager - Authentication attempt using org.springframework.security.authentication.dao.DaoAuthenticationProvider
DEBUG o.s.s.a.d.DaoAuthenticationProvider - User '' not found
DEBUG o.s.s.w.a.UsernamePasswordAuthenticationFilter - Authentication request failed: org.springframework.security.authentication.BadCredentialsException: Bad credentials
What is the correct way to get the REST Template to post auth credentials? Is there a better way to login in/ get authorized other than j_spring_security_check? Does the information go in the header?
Thanks in advance.

This seems like a duplicate of another SO question. You are probably approaching this the wrong way, though. Typically if you are issuing a REST request you wouldn't be authenticating at the same time - this doesn't make any sense - certainly not using form POST style logic.
For authentication of REST requests you should be using another form of authentication (assuming these requests are generated programmatically):
* HTTP Basic auth
* X.509 certificates
OR if this is happening through an XHR / Javascript origin, you should be prepared to have the request fail and redirect the user to the login mechanism. Typically handling REST style requests with Spring Security is not at all the same as handling regular secured pages. You should be prepared for some amount of complexity.
Good luck!

Related

Share Spring Security Context across multiple http sections

I have a situation where I have the basic application being served on the main endpoint (/**). I use spring security to authenticate the user before serving any further resources. The authentication is done with a login form.
But specifically the endpoint (/lti/**) is being used in a different Http Section. There, Spring security handles the authentication using OAuth.
After authentication on the /lti/** endpoint, the user is expected to load my entire application in an iFrame. This means access to all resources protected by the 1st Http-section.
Now the problem here is even though the user authenticated using OAuth creds for loading the app from /lti/**, and I set all appropriate user roles, when the application loads in the iFrame and tries to access any resources, it redirects to the login screen as directed by the 1st Http-section (The succeeding calls are through AJAX if that helps, but you can see the response in the dev tools).
Based on my research so far, the Security Context is not shared among different entry points. Different firewalls are instantiated so the Security context itself is re-initiated.
Here's a bit of my Security context:
<security:http pattern="/lti/**" use-expressions="true" entry-point-ref="oAuthProcessingFilterEntryPoint">
<security:headers>
<security:frame-options disabled="true"/>
</security:headers>
<security:intercept-url pattern="/**" access="hasRole('ROLE_OAUTH')"/>
<!-- Filter -->
<security:custom-filter ref="oAuthProcessingFilter" before="ANONYMOUS_FILTER"/>
<!-- Disable CSRF -->
<security:csrf disabled="true"/>
</security:http>
<security:http>
<security:intercept-url ... />
....
<security:form-login
authentication-success-handler-ref="authenticationSuccessHandler"
login-page=............"/>
<security:logout ................./>
<security:session-management invalid-session-url="............." session-authentication-error-url="................">
</security:session-management>
<!-- Enable csrf protection -->
<security:csrf/>
</security:http>
Any approach that will work or have any ideas how I ccan tackle the situation?
SecurityContext is populated in every request, the FilterChain set it up at the beginning of the request by using the SecurityContextPersistenceFilter. By deafult, this filter store the authentication data in the HttpSession.
The users are authenticated in a page an then you load an Iframe which starts a different HttpSession (you could check this if you watch the sessionids).
Then you have several options:
Do not use an Iframe. The best option, if it is not a must.
Configure a default RememberMe filter. the problem is that the users will be remembered in each session, until the cookie expires.
Store the SecurityContext in a more persistent way than the session.
Summarizing, I think that your problem is not about different entry points, its about different sessions.

Session fixation in Spring Security

We are trying to prevent session fixation attack in our application. This means we are expected to generate new JSESSIONID every time a user logs into application.
Current scenario doesn't generate new JSESSIONID post authentication with ADFS (Active directory). Thus we would like to achieve the same. Can you let us know, how to achieve solution for this kind of attack?
We have Spring, Primefaces and Spring Security used in our application. We tried implementing below tags in our Spring security.xml file. However, it doesnt seem to generate new JSESSIONID post authentication is successful with ADFS. This spring-security.xml has been added in web.xml. Can you let us know what is wrong with below use? We are using Spring Security 3.2.10 in project.
<sec:http create-session="always" use-expressions="true">
<sec:intercept-url pattern="/*" />
<sec:http-basic />
<sec:session-management invalid-session-url="/"
session-fixation-protection="newSession">
<sec:concurrency-control max-sessions="150"
expired-url="/" />
</sec:session-management>
<sec:csrf/>
</sec:http>
<sec:authentication-manager alias="authenticationManager">
<sec:authentication-provider>
<sec:user-service>
<sec:user name="abc" password="abc" authorities="ROLE_USER" />
</sec:user-service>
</sec:authentication-provider>
</sec:authentication-manager>
If you are using the Basic authentication for API, you'd better not create new session
<sec:http create-session="stateless" ....
If you want to create new session post authentication, the default Basic Filter is not supported, but you can implement your own filter and just like AbstractAuthenticationProcessingFilter, there is SessionAuthenticationStrategy in it, and SessionFixationProtectionStrategy will create a new session with exist attributes in old session post authentication.
I suposse you are using form-login because talking about users login in. Spring includes out-of-the-box session fixation protection. In SessionManagementFilter, in doFilter method, you can see that if the user has been authenticated in the current request, the session authentication strategy is called. This strategy by default is SessionFixationProtectionStrategy.
Apparently your configuration is correct, debug that method and check what is happening. Besides, login forms are recommended to be light and sessionless if possible, so default create-session value "IfRequired" should be preferred instead of "always". Anyway newSession strategy should invalidate current session, ceate a new one and return a new JSESSIONID cookie.

Spring REST Basic Authentication Design Approach

Environment :
Spring 4
Spring Security 4
Spring MVC 4
Hibernate 4
MySQL
Issue :
Below is the requirement :
1)We are developing a Spring REST service for inventory management.
2)This web service will be consumed by .NET client. (or may be mobile device in future)
3)The users of REST service need to be authenticated. The user will use login form displayed by .NET client and if authentication is successfull , he will be
allowed to consume REST API.
4)If authentication fails , user won't be allowed entry into REST service.
Now we have decided to use Basic Authentication for this.
My question is : How do we achieve this using Spring MVC REST and Spring security ?
Below is my first attempt :
application-security.xml
<http auto-config="true" use-expressions="true">
<intercept-url pattern="/usermanagement/authenticate" access="permitAll"/>
<intercept-url pattern="/abhishek/*" access="hasRole('ROLE_ADMIN')"/>
<http-basic/>
<csrf disabled="true"/>
</http>
<authentication-manager>
<authentication-provider>
<user-service>
<user name="Atul" password="12345" authorities="ROLE_ADMIN" />
</user-service>
</authentication-provider>
</authentication-manager>
Following is the flow happening right now :
1)The /authentication API looks up user in Db and returns Http Status code 201(success ) or 401 (failure) accordingly. (this url is unsecured)
2)If success , client puts username/password as Authorization header (which is used in login) and sends this header for future Http requests.
3)Now once next request comes (this is secured), spring security comes into picture and again authentication happens here.
But this time it will be Spring provided.
4)So there are two authentication mechanism are being used .
5)I know I am messing up here , but not able to decide on what is the correct approach to design this.
6)How can client be provided the authentication capability by hooking into Spring security ? He needs to know authentication success/failure
immediately after he logs in.
Please help since I am struggling a lot on this.

Spring Security custom filter registration with Java config

I am trying to setup pre-authentication authorisation using Spring Security, similar to site minder where an external system does the authentication and saves login information in a cookie. However for that to happen I need to redirect to the external URL.
I tried doing it from an implementation of AbstractPreAuthenticatedProcessingFilter but that doesn't work because the HttpServletResponse object is not available.
A more appropriate way seems to be to just add a custom filter that checks for cookie and does the redirection and once the cookies are available then passes the control forward to Spring Security filter. How can I register this custom filter in a Java configuration based Spring Security application? Any help would be appreciated.
The common way is to redirect user to the external authentication interface using an AuthenticationEntryPoint, for example LoginUrlAuthenticationEntryPoint. The entry point is automatically invoked by Spring Security whenever it determines that user needs to get authenticated.
Once user returns back to your application, it should hit a custom filter which extends the AbstractPreAuthenticatedProcessingFilter and extracts the username from your cookie/header/token (after perhaps some validity and integrity checks) in method getPreAuthenticatedPrincipal.
The Spring configuration could be similar to:
<security:http entry-point-ref="externalAuthentication">
<security:custom-filter after="BASIC_AUTH_FILTER" ref="cookieAuthentication"/>
<security:intercept-url pattern="/**" access="IS_AUTHENTICATED_FULLY"/>
</security:http>
<bean id="externalAuthentication" class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint">
<constructor-arg value="http://server.local/authenticationService"/>
</bean>
<bean id="cookieAuthentication" class="custom class extending org.springframework.security.web.authentication.preauth.AbstractPreAuthenticatedProcessingFilter">
...
</bean>

Support SAML SSO and normal login

I have an application which is accessed by two types of users, internal and external.
I need to authenticate external users using SAML.
I need to authenticate internal users with the normal form-based login. My application need to support both types of users. I use spring security frame work.
Is it possible to support both types of users? if so can you suggest the approach at high level? Thanks.
You can easily enable support for both form and SAML authentication with configuration similar to this:
<http entry-point-ref="authenticationEntryPoint" authentication-manager-ref="authenticationManager">
<intercept-url pattern="/**" access="IS_AUTHENTICATED_FULLY"/>
<form-login login-page="/login" />
<custom-filter before="FIRST" ref="metadataGeneratorFilter"/>
<custom-filter after="BASIC_AUTH_FILTER" ref="samlFilter"/>
</http>
Make sure that your AuthenticationManager contains the samlAuthenticationProvider. And of course include other configuration parts from the Spring SAML sample application.
You can then create your custom login page which presents user with username+password fields for form-based authentication and a link/picture (or multiple of them) which initialize authentication with the IDP (by redirecting user to scheme://host:port/saml/login?idp=selectedIdpEntityId).
Your users then decide which one to use - depending on whether they's internal or external.
The part of Spring SAML documentation touching on this subject is in chapter Spring Security integration.

Resources