0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Spring Boot + Java + GitHub認証ログイン

Posted at

OAuth2を使ったSSOに苦戦したので、備忘録として残しておきます。

  1. GitHubで「OAuth Apps」のクライアントIDとクライアントシークレットを生成する。

    1. GitHubを開く
    2. 右上のプロフィール画像を押下し、「Settings」を押下
    3. サイドバーの「Developer Settings」を押下
    4. サイドバーの「OAuth Apps」を押下
    5. [New Auth App]ボタンを押下
    6. 「Application name」に任意でアプリケーションの名前を入力
    7. 「Homepage URL」に作成中のアプリのトップページのURLを入力、ローカル環境で作成中なら「http://localhost:8080」
    8. 「Authorization callback URL」に「http://localhost:8080/login/oauth2/code/github」を入力
    9. 上記の手順で作成が完了したらクライアントIDとクライアントシークレットを控えておく
  2. application.ymlに以下のように入力

spring
  security:
    oauth2:
      client:
        registration:
          github:
            client-id: 控えておいたクライアントID
            client-secret: 控えておいたクライアントシークレット
            scope:
              - read:user
  1. pom.xmlに以下のdependencyを追加
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
  1. 「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のユーザ名 -->
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?