Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Security 3.2 Token Authentication

I know this has been asked already, but I am not able to get it to work. Here is what I would like to get accomplished:

I am using Spring Security 3.2 to secure a REST-like service. No server side sessions. I am not using basic auth, because that would mean that I need to store the user's password in a cookie on client side. Otherwise the user would need to login with each page refresh/ change. Storing a token is I guess the lesser evil.

  1. A web client (browser, mobile app) calls a REST-like URL to login "/login" with username and password
  2. The server authenticates the user and sends a token back to the client
  3. The client stores the token and adds it to the http request header with each api call
  4. The server checks the validity of the token and sends a response accordingly

I did not even look at the token generation part yet. I know it is backwards, but I wanted to get the token validation part implemented first.

I am trying to get this accomplished by using a custom filer (implementation of AbstractAuthenticationProcessingFilter), however I seem to have the wrong idea about it.

Defining it like this:

public TokenAuthenticationFilter() {
    super("/");
}

will only trigger the filter for this exact URL. I am sticking to some sample implementation, where it calls AbstractAuthenticationProcessingFilter#requiresAuthentication which does not accept wildcards. I can of course alter that behavior, but this somehow makes me think that I am on the wrong path.

I also started implementing a custom AuthenticationProvider. Maybe that is the right thing? Can someone give me a push into the right direction?

like image 262
atlan Avatar asked Aug 08 '13 16:08

atlan


1 Answers

I think pre-auth filter is a better fit for your scenario. Override AbstractPreAuthenticatedProcessingFilter's getPrincipal and getCredentials methods. In case the token is not present in the header, return null from getPrincipal.

Flow:

  • User logs in for the first time, no header passed, so no authentication object set in securityContext, normal authentication process follows i.e. ExceptionTranslation filter redirtects the user to /login page based on form-logon filter or your custom authenticationEntryPoint
  • After successful authentication, user requests secured url, pre-auth filter gets token from header authentication object set in securityContext, if user have access he is allowed to access secured url
like image 156
coder Avatar answered Sep 20 '22 06:09

coder