I\'m looking to use Spring Security for a Spring MVC application which will strictly be a JSON web service. I\'ve done some research and read a few articles but haven\'t really
This will be a good place to start with Spring-Rest-Boilerplate.
You have to come up with a token format and encryption for same. You ideally need to keep an expiry for the token too, expiry along with username could be a part of the token.Use an encryption algorithm a cryptographic hash function like MD5 and get hash of the whole Token.
Edit : As pointed out by Maciej Stępyra MD5 seems to be broken and its advised to use a Stronger hash functions like SHA-256.
Spring security by default will redirect you to a login page, but this does not make sense in case of REST so use a custom AuthenticationEntryPoint
in config(Ref sample github code).
I was using this format for my Token:
token:username:hash:expiry
hash=MD5(username+magickey)
expiry=current_timestamp+mins_to_expiry
<security:http realm="Protected API" use-expressions="true" auto-config="false" create-session="always" entry-point-ref="**CustomAuthenticationEntryPoint**">
<security:custom-filter ref="**authenticationTokenProcessingFilter**" position="PRE_AUTH_FILTER" />
<security:intercept-url pattern="/**" access="isAuthenticated()" />
</security:http>
NB:Thanks dhavaln for the code. I have used this as a reference and developed similar thing.
"I want the application to be completely stateless"
I'd reconsider what you're trying to do. There's a reason why you can't find good examples of your solution: You simply can't have an application that's both stateless and secure. Also if you're storing the tokens somewhere, you're not being stateless. Even if you aren't storing the tokens (like using JWT to encode them), you have to protect against CSRF attacks if users will be accessing this in a web browser. If you do go your route, expect to be writing a lot of customized security code (which is a bad thing). See a discussion of this here: https://spring.io/blog/2015/01/12/the-login-page-angular-js-and-spring-security-part-ii
In my case I found it easier to replace the org.springframework.security.web.context.SecurityContextRepository
in org.springframework.security.web.context.SecurityContextPersistenceFilter
with an implementation that shares the SecurityContext among several tomcat nodes. The client keeps sending a token jsessionid-like but I can do a simple round-robin load balancing and don't have to worry about session replication.