I use Spring Boot 2.2.4 and I would like to login into my application via OAuth2 protocol and GitHub.
Here is my source code of most important configuration files and classes:
The application.properties file
spring.security.oauth2.client.registration.github.client-id=[my client id]
spring.security.oauth2.client.registration.github.client-secret=[my client secret]
spring.security.oauth2.client.registration.github.redirect-uri=http://[host ip]:8080/login_success
Spring Security config class
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/test")
.authenticated()
.anyRequest().permitAll()
.and()
.oauth2Login();
}
}
Sample controller class
@RestController
public class SampleController {
@GetMapping("/")
public String home() {
return "Home";
}
@GetMapping("/login_success")
public String loginSuccessMethod() {
return "Login success";
}
@GetMapping("/user")
public OAuth2User user(@AuthenticationPrincipal OAuth2User principal) {
return principal;
}
@GetMapping("/test")
public String testMethod() {
return "Test method";
}
}
Problem description:
When I had tried to visit the /test page then I was redirected to the /login page. It is expected behavior.
When I had clicked the GitHub link then I was redirected to login form on github.com. It is expected behavior.
When I had typed my user name and password and clicked "sign in" button then I was redirected to /login_success page. It is expected behavior.
When I had tried to visit the /test page again then I was redirected to the /login page. So the session was not created. Why?
When I had tried to visit the /user page then the user method of my controller returned null. Why?
Problem solved. I have typed wrong redirect uri value on GitHub and application.properties file. The correct value is http://[host ip]:8080/login/oauth2/code/github