My linux world » Java Spring Security – OAuth2

Java Spring Security - OAuth2


I will give two quick examples about OAuth2.
The first example will use server + resource + client implicit (i.e. redirect to server to make authentication).
The second one will use server + resource + client password (will have its own form to authenticate, but ask server if user is allowed to connect).

Contents

Server

The server must extends AuthorizationServerConfigurerAdapter :

@Configuration
@EnableAuthorizationServer
public class OAuth2AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
  (...)
 
@Override
    public void configure(final ClientDetailsServiceConfigurer clients) throws Exception {
         .jdbc(dataSource)         
           .withClient("clientImplicit")
               .authorizedGrantTypes("implicit")
               .scopes("read","write","foo","bar")
               .autoApprove(false)
               .accessTokenValiditySeconds(3600)
 
               .and()
               .withClient("clientPassword")
               .secret("secret")
               .authorizedGrantTypes("password","authorization_code", "refresh_token")
               .scopes("foo","read","write")
               .accessTokenValiditySeconds(3600) // 1 hour
               .refreshTokenValiditySeconds(2592000) // 30 days
    }
 
  (...)
}

Resource server

The resource server will extends ResourceServerConfigurerAdapter :

@Configuration
@EnableResourceServer
public class OAuth2ResourceServerConfig extends ResourceServerConfigurerAdapter {
  (...)
 
    @Override
    public void configure(final HttpSecurity http) throws Exception {
        http
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
            .and().authorizeRequests().anyRequest().authenticated();
    }
 
  (...)
}

When a user will request the spring servlets, the authorization can be checked like this :

@PreAuthorize("#oauth2.hasScope('foo') and #oauth2.hasScope('read')")
@RequestMapping(method = RequestMethod.GET, value = "/foos/get")
public Foo get() {
  return new Foo();
}

Or simply like this :

@PreAuthorize("isFullyAuthenticated()")
@RequestMapping(method = RequestMethod.GET, value = "/foos/get")
public Foo get() {
  return new Foo();
}

Implicit client

To get the access token, the client will request :

http://oauth-server/oauth-authorize?response_type=token
                                   &scope=read write foo bar
                                   &client_id=clientImplicit
                                   &redirect_uri=http://oauth-client-implicit
  

The server will authenticate user.
If succeed, redirect to http://oauth-client-implicit?access_token=YOUR_ACCESS_TOKEN.

You can get the access token like this :

var match = document.location.hash.match(/access_token=([\w-\.]+)/);
var access_token=!!match && match[1];

Password client

To get the access_token, the client must request zuul server :

jQuery.ajax({
		url: "http://oauth-client-password/oauth/token",
		beforeSend: function (xhr) {
			xhr.setRequestHeader('Accept',        "application/json");
		},		
		data : {grant_type : "password",
			username : "user1",
			password : "user1Password",
			client_id : "clientPassword"
                       },
		success: function(response) {
                    access_token = response.access_token;
                },		
		error : function( jqXHR, textStatus, errorThrown) {
			console.error(jqXHR);
		}
	});

To refresh access token :

jQuery.ajax({
		url: "http://oauth-client-password/oauth/token",
		beforeSend: function (xhr) {
			xhr.setRequestHeader('Accept',        "application/json");
                        xhr.setRequestHeader('Authorization', "Bearer YOUR_ACCESS_TOKEN");
		},		
		data : {grant_type : "refresh_token"},
		success: function(response) {
                    access_token = response.access_token;
                },		
		error : function( jqXHR, textStatus, errorThrown) {
			console.error(jqXHR);
		}
	});

Copyright © 2023 My linux world - by Marc RABAHI
Design by Marc RABAHI and encelades.

Fork me on GitHub