I am using Spring Security with SpringMVC to create a web application (I will refer to this as the WebApp for clarity) that speaks to an existing application (I will refer to this as BackendApp).
I want to delegate authentication responsibilities to the BackendApp (so that I don't need to synchronise the two applications).
To implement this, I would like the WebApp (running spring security) to communicate to the BackendApp via REST with the username and password provided by the user in a form and authenticate based on whether the BackendApp's response is 200 OK or 401 Unauthorised.
I understand I will need to write a custom Authentication Manager to do this however I am very new to spring and can't find any information on how to implement it.
I believe I will need to do something like this:
public class CustomAuthenticationManager implements AuthenticationManager{
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String username = authentication.getName();
String pw = authentication.getCredentials().toString();
// Code to make rest call here and check for OK or Unauthorised.
// What do I return?
}
}
Do I set authentication.setAuthenticated(true) if successful and false if otherwise and thats it?
Once this is written, how do I configure spring security to use this authentication manager using a java configuration file?
Thanks in advance for any assistance.
Take a look at my sample below. You have to return an UsernamePasswordAuthenticationToken. It contains the principal and the GrantedAuthorities. Hope I could help :)
PS: userRepo and rightRepo are Spring-Data-JPA Repositories which access my custom User-DB
SpringSecurity JavaConfig:
My solution is almost the same as the first answer:
1) You need a class which implements the Authentication Provider
2) Opposite to the first answer you don't need to have following code in your WebSecurityConfiguration if you have only this custom provider.
The issue is that Spring looks for available providers and use the default if nothing else is found. But as you have the implementation of the AuthenticationProvider - your implementation will be used.
In its most simplest:
First you must configure Spring security to use your custom AuthenticationProvider. So, in your spring-security.xml (or equivalent config file) you must define wich class is implementing this feature. For example:
Secondly you must implement AuthenticationProvider as in your example. Specially the method authenticate(Authentication authentication) in which your rest call must be. For example: