spring boot security oauth2 implementation | spring boot security oauth2 example | spring boot security oauth2 practical approach

Spring Security Oauth 2

This tech blog explains how to setup spring boot security using oauth2, To understand oauth2 integration you must have basic knowledge about how oauth2 works? 

I must say with spring boot security it's very easy to integrate the oauth2. In this example I have taken google server for oauth authentication.

By following the below steps, you can easily understand and integrate oauth2 client in your application

let’s discuss step by step oauth2 authentication using oauth2client

1. Maven dependencies

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-oauth2-client</artifactId>
        </dependency> 

2. application.properties

a. You must create your client-id and client-secret at google cloud, https://console.cloud.google.com/apis/credentials

b. The syntax to register your oauth2 provider should be like

     spring.security.oauth2.client.registration.<oauth2_provider>.<key>=<value>

c. Provider properties should have syntax like

    spring.security.oauth2.client.registration.< oauth2_provider>.provider.<key>=<value>

d. Multiple scopes can be listed separated by comma operator.

spring.security.oauth2.client.registration.google.client-id=
spring.security.oauth2.client.registration.google.client-secret=
spring.security.oauth2.client.registration.google.scope=email
spring.security.oauth2.client.registration.google.redirect-uri=http://localhost:8080/login/oauth2/code/google
spring.security.oauth2.client.registration.google.provider=google
spring.security.oauth2.client.registration.google.client-authentication-method=basic
spring.security.oauth2.client.registration.google.authorization-grant-type=authorization_code
spring.security.oauth2.client.provider.google.authorization-uri=https://accounts.google.com/o/oauth2/auth
spring.security.oauth2.client.provider.google.token-uri=https://www.googleapis.com/oauth2/v3/token

3. Create SecurityConfig class where you must write security configuration for your

    application. http://link.to.security.condig.class

    Here I am going discuss important security configuration in the configure method

a.     You need to extends WebSecurityConfigurerAdapter and override configure method.

b.     Since you are implementing this security to secure rest end points you need to add this prop sessionCreationPolicy(SessionCreationPolicy.STATELESS)

c.     .antMatchers("/", followed by .permitAll() ensures there will not be any security checks done for the request metioned in antMatchers

d.     .anyRequest() followed by .authenticated() indicates any other request apart from the point c will have to go for security check

e.     .oauth2Login() indicates this security configuration following oauth2 flow.

f.      .baseUri("/oauth2/authorize") this is the uri which triggers the oauth flow, so when you trigger the oauth flow our url pattern should be like /oauth2/authorize/<oauthprovider> in our case it is google so complete your URL can be /oauth2/authorize/google

g.     .userInfoEndpoint() followed by .userService(customOAuth2UserService) customOAuth2UserService is the instance of CustomOAuth2UserService class will discuss this later it’s an important aspect so I am mentioning here

h.     .successHandler(oAuth2AuthenticationSuccessHandler) and .failureHandler(oAuth2AuthenticationFailureHandler) as name suggested these are the callback handler classes which gets invoked in case of successful or failed authentication.

i.      .authorizationRequestResolver(new CustomAuthorizationRequestResolver(this.clientRegistrationRepository, oAuthExtraUrlParameters)) in detail I’ll cover this later but here important to note that CustomAuthorizationRequestResolver used to modify oauth request just before it hits to oauth2 server.

j.      .tokenEndpoint() followed by .accessTokenResponseClient(accessTokenResponseClient()) accessTokenResponseClient is Bean returns the object of OAuth2AccessTokenResponseClient which is needed for intercepting token response sent by the oauthserver. This bean is responsible to configure token response interceptor.

 

k.     http.addFilterBefore(tokenAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class) tokenAuthenticationFilter() is a Bean responsible for token authentication will cover this later.

 

Now let’s understand the request flow of execution using diagram

 

 


 

1.     The URL http://localhost:8080/oauth2/authorize/google triggers the standard spring security oauth2 flow automatically since it’s already been configured as base url /oauth2/authorize/ in SpringConfig class

2.     CustomAuthorizationRequestResolver is the class which extends OAuth2AuthorizationRequestResolver to intercept this outgoing request we need to override method public OAuth2AuthorizationRequest resolve(HttpServletRequest request) here you can add custom parameters to your request. Since other oauth provider may require extra parameters for the user authentication.

3.     Once request escaped from CustomAuthorizationRequestResolver then you can see the login screen in our case it’s a google login page. On successful authentication google oauth server redirect us to our spring.security.oauth2.client.registration.google.redirect-uri which is already configured in application.properties file note that we also need to configure this URL at google oauth configuration otherwise it will throw Invalid_redirect_url error.

4.     Once authentication from google is successful method convert from  CustomTokenResponseConverter gets called here you can get access token/ refresh token etc. and modify the token response as per your need.

5.     If anything goes wrong with authentication and oauth sever decides redirect the client by assigning oauth standard failure response then in that case method onAuthenticationFailure  from OAuth2AuthenticationFailureHandler class will be invoked  here you can redirect user to the error page.

6.     If you put valid credentials to the google login screen you will be again redirected to the client application and in this case method loadUser from CustomOAuth2UserService will be invoked this method takes argument (OAuth2UserRequest oAuth2UserRequest) from which you can get the details of the user. E.g you can retrieve the user email, photo, name it depends on what are scope you have requested to the oauth server. So that you can save these details to your database.

7.     After that method onAuthenticationSuccess from OAuth2AuthenticationSuccessHandler will be invoked this method takes an arguments like (HttpServletRequest request, HttpServletResponse response, Authentication authentication) authentication object will give you access token and refresh token although you cannot retrieve refresh token directly but I’ll add this code in the git repo. Now you can create your custom jwt authentication token for your application.

 

Github: https://github.com/kulbhushanchaskar/spring_security

Comments

Popular posts from this blog

ResultSet as Stream in Java

Teiid - Simplifies Data Virtualization

What is jquery Deferred and Promise?