Spring Boot OAuth2 Tutorial with Google

Firstly you need to open Google Developer Console from below link:

Google Developer Console

After open you need to login with gmail account and get your Google Developer Console Dashboard like below:

Create a new project like below:

After creating project you need to select your project and select credentials like below:

After this select create credential then select oauth client id like below:

After this you need to select configure consent screen like below:

Then you need to select external then click on create button like below:

The you need to fill details and save it like below:

After save all things you need to select credentials again and fill some details like below:

After save this you get your client id and secret like below:

Now after doing above thing you need to create a project in Spring Tool Suite like below:

Then add following dependency then click on finish. like below:

After this create project structure like below:

OuthTutorialGoogleApplication.java


package com.deepsingh44.blogspot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class OuthTutorialGoogleApplication {

	public static void main(String[] args) {
	SpringApplication.run(OuthTutorialGoogleApplication.class, args);
	}

}
  

SecurityConfig.java


package com.deepsingh44.blogspot.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.
builders.HttpSecurity;
import org.springframework.security.config.annotation.web.
configuration.WebSecurityConfigurerAdapter;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.antMatcher("/**").
		authorizeRequests().
		anyRequest().
		authenticated().
		and().
		oauth2Login().
		and().
		logout();
	}

}
  

MainController.java


package com.deepsingh44.blogspot.controller;
import java.security.Principal;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MainController {

	@GetMapping("/")
	public String home(Principal principal) {
		return "Welcome, " + principal.getName();
	}

}
  

application.properties


server.port=9988
spring.security.oauth2.client.registration.google.client-id=xxxxxxxxxxxxxxx
spring.security.oauth2.client.registration.google.client-secret=xxxxxxxxxxx
  

Run your project and you can get error so you can solve this error by pasting url in Google Developer Console and save it like below:

After this now you can run your project then below page:

Then login with your email and password so you can access main page like below:

No comments: