I struggled with SSO using OAuth2, so I will leave it as a memorandum.
Generate a client ID and client secret for "OAuth Apps" on GitHub.
Open GitHub
Press the profile image on the upper right and press "Settings"
Press "Developer Settings" in the sidebar
Press "OAuth Apps" in the sidebar
Press the [New Auth App] button
Enter the name of the application in "Application name"
Enter the URL of the top page of the application being created in "Home page URL", and if it is being created in the local environment, "http: // localhost: 8080"
Enter "http: // localhost: 8080/login/oauth2/code/github" in "Authorization callback URL"
Make a note of the client ID and client secret when the creation is completed by the above procedure.
Enter the following in application.yml
spring
security:
oauth2:
client:
registration:
github:
client-id:The client ID you wrote down
client-secret:A copy of the client secret
scope:
- read:user
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
@Configuration
public class OAuth2ClientConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/")
.permitAll()
.antMatchers("/home")
.permitAll()
.antMatchers("/home/**").permitAll()
.and()
.oauth2Login()
.loginPage("/login");
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/css/**", "/img/**", "/js/**" );
//Static files under the static folder are configured(WebSecurity web)Override with
}
}
```java
@Controller
@RequestMapping("")
public class OAuth2ClientController {
@GetMapping("")
public String index(OAuth2AuthenticationToken authentication,
@AuthenticationPrincipal OAuth2User oauth2User,
Model model) {
if(Objects.isNull(authentication)){
return "index";
}
String userName = oauth2User.getAttributes (). get ("name"). toString (); // Get username from github account information
model.addAttribute("userName", userName);
return "index";
}
}
<p th:text="${userName}"></p>
<!-Output: github username->
Recommended Posts