Hello World

Authentication against a RESTful Service with Spring Security 본문

Spring/Boot(4.x)

Authentication against a RESTful Service with Spring Security

EnterKey 2016. 1. 10. 12:56
반응형

1. Overview

This article is focused on how to authenticate against a secure REST API that provides security services – mainly, a RESTful User Account and Authentication Service.

2. The Goal

First, let’s go over the actors – the typical Spring Security enabled application needs to authenticate against something – that something can be a database, LDAP or it can be a REST service. The database is the most common scenario; however, a RESTful UAA (User Account and Authentication) Service can work just as well.

For the purpose of this article, the REST UAA Service will expose a single GET operation on /authentication, which will return the Principal information required by Spring Security to perform the full authentication process.

3. The Client

Typically, a simple Spring Security enabled application would use a simple user service as the authentication source:

1<authentication-manager alias="authenticationManager">
2    <authentication-provider user-service-ref="customUserDetailsService" />
3</authentication-manager>

This would implement the org.springframework.security.core.userdetails.UserDetailsService and would return the Principal based on a provided username:

1@Component
2public class CustomUserDetailsService implements UserDetailsService {
3    @Override
4    public UserDetails loadUserByUsername(String username) {
5      ...
6    }
7}

When a Client authenticates against the RESTful UAA Service, working only with the username will no longer be enough– the client now needs the full credentials – both username and password – when it’s sending the authentication request to the service. This makes perfect sense, as the service itself is secured, so the request itself needs to contain the authentication credentials in order to be handled properly.

From the point of view or Spring Security, this cannot be done from within loadUserByUsername because the password is no longer available at that point – we need to take control of the authentication process sooner.

We can do this by providing the full authentication provider to Spring Security:

1<authentication-manager alias="authenticationManager">
2    <authentication-provider ref="restAuthenticationProvider" />
3</authentication-manager>

Overriding the entire authentication provider gives us a lot more freedom to perform custom retrieval of the Principal from the Service, but it does come with a fair bit of complexity. The standard authentication provider –DaoAuthenticationProvider – has most of what we need, so a good approach would be to simply extend it and modify only what is necessary.

Unfortunately this is not possible, as retrieveUser – the method we would be interested in extending – is final. This is somewhat unintuitive (there is a JIRA discussing the issue) – it looks like the design intention here is simply to provide an alternative implementation which is not ideal, but not a major problem either – our RestAuthenticationProvider copy-pastes most of the implementation of DaoAuthenticationProvider and rewrites what it needs to – the retrieval of the principal from the service:

01@Override
02protected UserDetails retrieveUser(String name, UsernamePasswordAuthenticationToken auth){
03    String password = auth.getCredentials().toString();
04    UserDetails loadedUser = null;
05    try {
06        ResponseEntity<Principal> authenticationResponse =
07            authenticationApi.authenticate(name, password);
08        if (authenticationResponse.getStatusCode().value() == 401) {
09            return new User("wrongUsername""wrongPass",
10                Lists.<GrantedAuthority> newArrayList());
11        }
12        Principal principalFromRest = authenticationResponse.getBody();
13        Set<String> privilegesFromRest = Sets.newHashSet();
14        // fill in the privilegesFromRest from the Principal
15        String[] authoritiesAsArray =
16            privilegesFromRest.toArray(new String[privilegesFromRest.size()]);
17        List<GrantedAuthority> authorities =
18            AuthorityUtils.createAuthorityList(authoritiesAsArray);
19        loadedUser = new User(name, password, true, authorities);
20    catch (Exception ex) {
21        throw new AuthenticationServiceException(repositoryProblem.getMessage(), ex);
22    }
23    return loadedUser;
24}

Let’s start from the beginning – the HTTP communication with the REST Service – this is handled by theauthenticationApi – a simple API providing the authenticate operation for the actual service. The operation itself can be implemented with any library capable of HTTP – in this case, the implementation is using RestTemplate:

01public ResponseEntity<Principal> authenticate(String username, String pass) {
02   HttpEntity<Principal> entity = new HttpEntity<Principal>(createHeaders(username, pass))
03   return restTemplate.exchange(authenticationUri, HttpMethod.GET, entity, Principal.class);
04}
05 
06HttpHeaders createHeaders(String email, String password) {
07    HttpHeaders acceptHeaders = new HttpHeaders() {
08        {
09            set(com.google.common.net.HttpHeaders.ACCEPT,
10                MediaType.APPLICATION_JSON.toString());
11        }
12    };
13    String authorization = username + ":" + password;
14    String basic = new String(Base64.encodeBase64
15        (authorization.getBytes(Charset.forName("US-ASCII"))));
16    acceptHeaders.set("Authorization""Basic " + basic);
17 
18    return acceptHeaders;
19}

FactoryBean can be used to set up the RestTemplate in the context.

Next, if the authentication request resulted in a HTTP 401 Unauthorized, most likely because of incorrect credentials from the client, a principal with wrong credentials is returned so that the Spring Security authentication process can refuse them:

1return new User("wrongUsername""wrongPass", Lists.<GrantedAuthority> newArrayList());

Finally, the Spring Security Principal needs some authorities – the privileges which that particular principal will have and use locally after the authentication process. The /authenticate operation had retrieved a full principal, including privileges, so these need to be extracted from the result of the request and transformed into GrantedAuthority objects, as required by Spring Security.

The details of how these privileges are stored is irrelevant here – they could be stored as simple Strings or as a complex Role-Privilege structure – but regardless of the details, we only need to use their names to construct the GrantedAuthoritiyobjects. After the final Spring Security principal is created, it is returned back to the standard authentication process:

1List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList(authoritiesAsArray);
2loadedUser = new User(name, password, true, authorities);

4. Testing the Authentication Service

Writing an integration test that consumes the authentiction REST service on the happy-path is straightforward enough:

1@Test
2public void whenAuthenticating_then200IsReceived() {
3    // When
4    ResponseEntity<Principal> response =
5        authenticationRestTemplate.authenticate("admin""adminPass");
6 
7    // Then
8    assertThat(response.getStatusCode().value(), is(200));
9}

Following this simple test, more complex integration tests can be implemented as well – however this is outside of the scope of this post.

5. Conclusion

This article explained how to authenticate against a REST Service instead of doing so against a local system such as a database. For a full implementation of a secure RESTful service which can be used as an authentication provider, check out the github project.
 

Reference: Authentication against a REST Service with Spring Security from our JCG partner Eugen Paraschiv at thebaeldung blog.


출처: http://www.javacodegeeks.com/2012/12/authentication-against-a-restful-service-with-spring-security.html?utm_content=bufferd05e2&utm_medium=social&utm_source=facebook.com&utm_campaign=buffer

반응형
Comments