OAuth2を使ったSSOに苦戦したので、備忘録として残しておきます。
-
GitHubで「OAuth Apps」のクライアントIDとクライアントシークレットを生成する。
- GitHubを開く
- 右上のプロフィール画像を押下し、「Settings」を押下
- サイドバーの「Developer Settings」を押下
- サイドバーの「OAuth Apps」を押下
- [New Auth App]ボタンを押下
- 「Application name」に任意でアプリケーションの名前を入力
- 「Homepage URL」に作成中のアプリのトップページのURLを入力、ローカル環境で作成中なら「http://localhost:8080」
- 「Authorization callback URL」に「http://localhost:8080/login/oauth2/code/github」を入力
- 上記の手順で作成が完了したらクライアントIDとクライアントシークレットを控えておく
-
application.ymlに以下のように入力
spring
security:
oauth2:
client:
registration:
github:
client-id: 控えておいたクライアントID
client-secret: 控えておいたクライアントシークレット
scope:
- read:user
- pom.xmlに以下のdependencyを追加
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
- 「configuration」パッケージを作成し、その中にconfigurationファイルを作成
@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フォルダ以下の静的ファイルはconfigure(WebSecurity web)でオーバーライド
}
}
```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(); // githubのアカウント情報からユーザ名を取得
model.addAttribute("userName", userName);
return "index";
}
}
<p th:text="${userName}"></p>
<!-- 出力: githubのユーザ名 -->