Spring Security Authentication Provider Sample Explanation
- 2021-07-26 07:45:20
- OfStack
1. Introduction
This tutorial describes how to set up an authentication provider in Spring Security, providing additional flexibility compared to standard scenarios using simple UserDetailsService.
2. The Authentication Provider
Spring Security provides a variety of options for performing authentication-all following simple specifications-authentication requests are processed by Authentication Provider and return fully authenticated objects with full credentials.
The standard and most common implementation is DaoAuthenticationProvider-which retrieves user details from a simple read-only user DAO-UserDetailsService. This UserDetailsService can only access the user name, which is used to retrieve the complete user entity-in many cases, this is enough.
More common scenarios still require access to the full authentication request to perform the authentication process. For example, when authenticating against some external third-party service, such as Crowd, you will need the username and password from the authentication request.
For these more advanced scenarios, we need to define custom authentication providers:
@Component
public class CustomAuthenticationProvider
implements AuthenticationProvider {
@Override
public Authentication authenticate(Authentication authentication)
throws AuthenticationException {
String name = authentication.getName();
String password = authentication.getCredentials().toString();
if (shouldAuthenticateAgainstThirdPartySystem()) {
// use the credentials
// and authenticate against the third-party system
return new UsernamePasswordAuthenticationToken(
name, password, new ArrayList<>());
} else {
return null;
}
}
@Override
public boolean supports(Class<?> authentication) {
return authentication.equals(
UsernamePasswordAuthenticationToken.class);
}
}
Note that the grant permissions set on the returned Authentication object are empty-this is because the permissions are of course application-specific.
3. Register Authentication Provider
Now that the authentication provider is defined, we need to specify it in the XML security configuration using the available namespace support:
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans
xmlns="http://www.springframework.org/schema/security"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xsi:schemaLocation="
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-4.0.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd">
<http use-expressions="true">
<intercept-url pattern="/**" access="isAuthenticated()"/>
<http-basic/>
</http>
<authentication-manager>
<authentication-provider
ref="customAuthenticationProvider" />
</authentication-manager>
</beans:beans>
4. Java Configuration
Next, let's look at the corresponding Java configuration:
@Configuration
@EnableWebSecurity
@ComponentScan("org.baeldung.security")
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private CustomAuthenticationProvider authProvider;
@Override
protected void configure(
AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authProvider);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().authenticated()
.and()
.httpBasic();
}
}
STEP 5 Test certification
Whether you use this custom authentication provider at the back end or not, requesting authentication from the client is basically the same-we can send an authenticated request using a simple curl command:
curl --header "Accept:application/json" -i --user user1:user1Pass
http://localhost:8080/spring-security-custom/api/foo/1
Note-for the purposes of this example-that we have secured REST API with Basic authentication.
We return the expected 200 OK from the server
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Set-Cookie: JSESSIONID=B8F0EFA81B78DE968088EBB9AFD85A60; Path=/spring-security-custom/; HttpOnly
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Sun, 02 Jun 2013 17:50:40 GMT
6. Summary
In this article, we discussed an example of a custom authentication provider for Spring Security.
The full implementation of this tutorial can be found in the GitHub project-this is an Maven-based project, so it should be easy to import and run.