Sitemap
Bushra Saifi

Bushra Saifi

Technology is best when it brings people together.

Spring boot OAuth2

4 min readApr 21, 2020

OAuth 2 is an authorization method to provide access to protected resources over the HTTP protocol and when it comes to achieving this in spring boot we have a predefined set of interfaces and classes.

Press enter or click to view image in full size

OAuth2 provides four different roles:

  1. Resource owner — The user of the application.
  2. Client — the application (user is using) which requires access to user data on the resource server.
  3. Resource Server — store user’s data and HTTP services which can return user data to authenticated clients.
  4. Authorization Server — responsible for authenticating a user’s identity and gives an authorization token. This token is accepted by the resource server and validates your identity.

Flow:

  1. The Application (Client) asks for authorization from the Resource Owner in order to access the resources.
  2. Provided that the Resource Owner authorizes this access, the Application receives an Authorization Grant. This is a credential representing the Resource Owner’s authorization.
  3. The Application requests an Access Token by authenticating with the Authorization Server and giving the Authorization Grant.
  4. Provided that the Application is successfully authenticated and the Authorization Grant is valid, the Authorization Server issues an Access Token and sends it to the Application.
  5. The Application requests access to the protected resource by the Resource Server and authenticate by presenting the Access Token.
  6. Provided that the Access Token is valid, the Resource Server serves the Application’s request.

Have you ever think about when you Login to another site using Facebook or Google how these third parties allow you to Login to a different application.

ok, Let's take an example — you want to login in a site and they have features of social login(like login with Facebook) and if you click on login with a Facebook button then many things happen in between.

In this scenario, Facebook is responsible for authenticating the user’s identity and gives an authorization token to the resource server(the application user wants to use). This token is accepted by that application and validates your identity.

You can find many of these examples on the web. But here the question is what if we want to use oauth2 in our application without any social login? Yes, you can implement OAuth 2.0 for your REST API for your own accounts (resource owners) independent of social media platforms.

When using social media platforms (e.g. Facebook, Google, etc.), you just need to implement an OAuth 2.0 client since the social medial platform is providing the OAuth 2.0 server. To implement OAuth 2.0 for your own accounts, you need to implement both OAuth 2.0 client and server.

Authorization Server —

To achieve this in Spring boot we make Authorization server by extending AuthorizationServerConfigurerAdapter class which implements AuthorizationServerConfigurer interface and use @EnableAuthorizationServer annotation.

Get Bushra Saifi’s stories in your inbox

Join Medium for free to get updates from this writer.

AuthorizationServerConfigurerAdapter class has three configure methods which we need to override in our Auth server:

//Configure the security of the Authorization Server, which means in practical terms the /oauth/token endpoint.@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
// Resource server should send credentials to validate the token
security.checkTokenAccess("isAuthenticated()");

}
//Configure the ClientDetailsService e.g. declaring individual clients and their properties.
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.jdbc(dataSource);

}
//Configure the non-security features of the Authorization Server endpoints, like the token store, token customizations, user approvals, and grant types.@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.tokenStore(tokenStore())
.authenticationManager(authenticationManager)
.userDetailsService(userDetailsService);
}

@Bean
public TokenStore tokenStore() {
return new JdbcTokenStore(dataSource);
}

Resource Server —

In the resource server, we use @EnableResourceServer annotation and extend ResourceServerConfigurerAdapter class which have two configure method that we need to override:

//Use this to configure the access rules for secure resources.@Override
public void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/api/free/**").permitAll()
.antMatchers("/**").authenticated();
}
//Add resource-server specific properties (like a resource id).@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.resourceId(resourceId);
}

we need to add these in application.yml:

security.oauth2:
client:
client-id: demo_client
client-secret: notasecret
resource:
id: resource_server
token-info-uri: http://localhost:8090/oauth/check_token

You need a WebSecurityConfigurerAdapter to secure the /authorize endpoint and to provide a way for users to authenticate. A Spring Boot application would do that for you (by adding its own WebSecurityConfigurerAdapter with HTTP basic auth). It creates a filter chain with order=0 by default and protects all resources unless you provide a request matcher. The @EnableResourceServer does something similar, but the filter chain it adds is at order=3 by default. WebSecurityConfigurerAdapter has an @Order(100) annotation. So first the ResourceServer will be checked (authentication) and then your checks in your extension of WebSecurityConfigureAdapter will be checked.

@Configuration
@EnableWebSecurity
public class AuthorizationServerWebSecurityConfig extends WebSecurityConfigurerAdapter {


@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.exceptionHandling()
.authenticationEntryPoint(AuthorizationServerWebSecurityConfig::commence)
.and()
.authorizeRequests()
.antMatchers("/db/h2/**").permitAll()
.antMatchers("/**").authenticated()
.and()
.httpBasic()
.and()
.headers().frameOptions().sameOrigin();


}

@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}

private static void commence(HttpServletRequest request,
HttpServletResponse response,
AuthenticationException authException) throws IOException {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
}
}

for a better understanding of oauth2 flow, you can enable your authorization server and resource server logging level to DEBUG as :

logging.level:
org.springframework: DEBUG
org.hibernate.SQL: DEBUG

Spring provide endpoint: localhost:8080/oauth/token (POST)

Request Json:{
“username”:”John”,
“password”:12345,
“grant_type”:”password”
}

Grant type —Application grant types (or flows) are methods through which applications can gain Access Tokens and by which you grant limited access to your resources to another entity without exposing credentials. Please refer below link for detail:

https://alexbilbie.com/guide-to-oauth-2-grants/

--

--

Bushra Saifi
Bushra Saifi

Written by Bushra Saifi

Technology is best when it brings people together.