Checking for existing HttpSession in Spring Security - java

Is it possible to authenticate a user by checking for an existing HttpSession within Spring Security? I would like users to authenticate via CAS at one URL (http://example.com/auth), but not the other URLs. For example, if they go straight to http://example.com/content, then I'd like to check for the HttpSession and return a 401 Unauthorized code if they haven't logged into CAS yet. If they've already gone to the /auth page and logged in, then going to /content will return the content. The main reason for this is to avoid any redirects that CAS causes during authentication.
I am kind of new to Spring Security and can't figure out if I need a custom AuthenticationManager, AuthenticationEntryPoint, both, or something else. The AuthenticationManager doesn't have a way for me to access the HttpSession, and the AuthenticationEntryPoint doesn't seem to be the right place to implement this functionality.
Any ideas?

Spring Security is not using HTTP session.
Instead, you can easily call to this static method:
SecurityContextHolder.getContext().getAuthentication();
Frankly, I believe that you need to configure Spring security correct in order to avoid checking authentication and redirect manually to other page.

Related

Spring Security - UserDetailsService for oAuth2 implementation?

So, using a basic authentication, I can see the value in simply using an implementation of the UserDetailsService which basically just loads a user and confirms they are authenticated.
However, I would now like to use oAuth2 and am not sure if my thinking is completely wrong on this subject. Wouldn't using oAuth2 eliminate the need for a UserDetailsService implementation? Because essentially the authorization server is the one who is checking to make sure the user exists (using Resource owner password flow) and then sends the user a JWT.
Once the user has this access token and can send it with every request, there has got to be another way to get the user authenticated into the AuthenticationManager rather than duplicating the effort and checking to make sure the credentials are correct again within the UserDetailsService (which the Authorization Server from oAuth2 would have already one).
What is this other way? What would be a solid implementation for this?
Thanks.
Actually UserDetailsService required for getting user information with his permissions. This is normal behavior. If user passed authorization he receive access token and Spring store his authentication data into SecurityContext. When user sends requests to protected resources with token - Spring validates token and puts into SecurityContext authentication data from DB or from memory. Its depends on the type of TokenStore (jdbc, memory, etc). Spring security using UserDetailsService once for user authorization.

Using password from spring security to authenticate REST call

I have a spring boot web app with spring security integrated with LDAP authentication. This web app internally makes REST calls. These REST calls are having username-password authentication. This username-password is the same used by spring security. Is there anyway I can get the username-password authenticated by spring security, so as to use in the REST calls. If not this way, is there any other way to achieve this.
Thanks in advance.
There is a quite nice way that I think fit your case.
By default Spring Security does not store the password in memory after authentication has been made, so you need to change that. With Java config, add in configure(AuthenticationManagerBuilder) method:
auth.eraseCredentials(false);
Then you can get the username and password for the current user with:
String username = SecurityContextHolder.getContext().getAuthentication().getName();
Object rawPassword = SecurityContextHolder.getContext().getAuthentication().getCredentials();
Spring Security is performed based on the rule in the security properties.
This means that you just need to have spring-security enabled, the only problem is that if not authorised it will go to the Not Authorised Page which a Restful client will not understand. But if the Restful client has authenticated and been granted a valid session then it will be able to get past the Security_check and access the protected page.
I guess Spring security is working like AOP so each protected page has a Security_check crosscut that only allows access to the page if the authentication is there.
Anyway, I solved the problem writing a custom AuthenticationProvider, which will perform the LDAP authentication and get the username-password for the future REST calls.

Adding Spring Security to Existing Spring AngularJS Application

I am developing a web application using AngularJS and Spring (4.1.0.RELEASE) as the backend. Everything is currently working great. Now that the functionality is done, I would like to add Spring Security (3.2.5.RELEASE) to the project, to both authenticate, and then authorize all of the requests. As I am using Angular, all of my views are static, and never rendered by the server. Therefore, the typical Spring Security setup (with a login jsp), will not work. I have looked at many examples, and none fit my needs. I do not want to use any external frameworks like Jersey to help with the authentication, or any server-rendered views, e.g. jsps.
When I enable Spring Security, my GET requests still work fine, but my POST requests, such as my login requests, no longer work, and return a 404 error. The controllers are correctly mapped, and the URLs are valid, so I know it must have something to do with Spring Security intercepting the request and deeming it invalid. I am not sure why this is, but I think it may have something to do with the requests not having the proper headers and Spring's CSRF protection. I do not want to disable this protection. My question is, how can I define a custom login url with Spring Security, that will authenticate my login POST request, and then send back all headers necessary to enable future, authenticated requests?
EDIT: I have gotten the url to work. Is there any way to retrieve the CSRF token from an ajax call? My views are all static, and the server is first hit on the login request, so there are no jsps, and no way to get the csrf token from the server via the jsp tag libraries. The suggestion in the first answer assumes that we are on a jsp, which is not the case. Is there any way to allow CSRF protection, or do I need to disable it and perform my own request validation?
With Spring security enabled, you'll need to add the CSRF token to all POST, PATCH, PUT and DELETE requests. This can be sent in a request header and you should be able to use a GET request to get the token. The default header is X-CSRF-TOKEN=<tokenvalue>.
Source: http://docs.spring.io/spring-security/site/docs/3.2.0.CI-SNAPSHOT/reference/html/csrf.html
(This is an older version of the docs, but includes a very relevant section on Ajax and Json requests.)
If you want to disable CSRF protection for a specific URL, you'll need to write a custom RequestMatcher that excludes your login URL.
In XML configuration it would look like:
<csrf request-matcher-ref="myCustomRequestMatcher"/>
See: http://blogs.sourceallies.com/2014/04/customizing-csrf-protection-in-spring-security/

Spring Security example

I am learning Spring and trying to implement Springs Security. I am not able to understand how it works. I read tutorials from which I understood the following:
we have to configure web.xml for delegating proxy and pattern
we need to add intercepts to dispatcher-servlet.xml
When request is made it triggers intercepts but after that I am unable to understand how it works. It would be helpful if somebody could provide a list of steps to be followed. I am using Hibernate and Spring (both with annotations), I want to authenticate users using Hibernate.
A detailed article can be found here: Code Project Or a tutorial with MVC and Spring Security here.
I tried to illustrate the process a little bit:
The user sends a HTTP-Request to the server
The server processes the request according to the web.xml
The web.xml contains a filter (AKA interceptor) and passes the request through this filter.
Because the user is unknown/not authenticated, Spring Security does its best to get more details.Depending on the config, it
sends an HTTP header, so that a login popup pops up in the browser (client side).
redirects to a form where you can enter username and password.
does a lot of hidden interaction between server and browser to guarantee a "Single-Sign-On" (SSO)
Except for SSO the user enters her/his/its credentials and create an additional request.
Spring Security realizes the login attempt and authenticates the user against a
file with user and passwords
a built-in XML structure in a spring config file
a database
an LDAP
When the access is granted, it assignes the necessary roles...
...and redirects to hard-coded "home page". (Spring Security let's you adjust this behaviour.)
In your application you can check the authorization for certain actions
.....
The user clicks on "logout" or the session expires. With the next request the process starts again.
Annotations
I found a tutorial here (Link).
I understood/assume the following facts:
The filters still must be defined in the web.xml.
You can annotate your classes/methods with
#Controller (API)
#Secured (API)
#RequestMapping (API)
I admit that I only gave you a rough overview, because your question is not that specific.
Please let me know what you want to learn in detail (re-recognize users, authenticate against different resources, do a SSO, create a secured area on your webpage,...)
Spring uses a dispatcher servlet for delegating the request. Spring security filters the request and checks if a valid security context is established. If so the request is passed to the dispatcher and it passes the request forward to the corresponding controller. If no security context is established, Spring security intercepts the request which means he could manipulate the request before the diespatcher servlet could process it. During this interception the request dispatcher (Servlet Specification) will be assigned to forward the request to a login page.
I think you don't have to bother with xml anymore. Now you can use Spring Boot + annotation based configuration. One of the best tutorial I found is this one: A good spring security tutorial
There are some good step-by-step tutorials on how to integrate spring security. For example:
For Java config: http://jtuts.com/2016/03/03/spring-security-login-form-integration-example-with-java-configuration/
For XML config: http://jtuts.com/2016/03/02/spring-security-login-form-integration-example-with-xml-configuration/

How to introduce 'Remember me' checkbox to existing project with Spring Security?

I have a pretty standard project with Spring Security.
I have a login form and I need to add 'Remember me' checkbox there. How can I do that?
I can provide some code if necessary.
I think the below links will be very useful,
Remember-Me Authentication
Configuring Spring Security Form Login with Remember-Me Enabled
5 Minute Guide to Spring Security
So this is a complete WAG - but it's how I would do it, at least initially.
I would override the Spring SecurityContextPersistenceFilter so that it only saves the Authentication details (i.e. the SecurityContext) if that box is checked (you would know this by some attribute you included when you POST the Form for login). You could also, possibly, create a new Cookie if the box is checked and check for the existence of said Cookie before you try Authentication - if the cookie exists it contains the UserDetails and will authenticate, otherwise redirect to the login page.
Here is a tutorial from mkyong that is good.

Categories

Resources