Spring-boot-google-oauth2-sign-in

提供:Dev Guides
移動先:案内検索

Spring Boot-Google OAuth2サインイン

この章では、Spring BootアプリケーションとGradleビルドを使用して、Google OAuth2サインインを追加する方法を説明します。

最初に、Spring Boot OAuth2セキュリティ依存関係をビルド構成ファイルに追加します。ビルド構成ファイルは以下のとおりです。

buildscript {
   ext {
      springBootVersion = '1.5.8.RELEASE'
   }
   repositories {
      mavenCentral()
   }
   dependencies {
      classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
   }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'

group = 'com.finddevguides.projects'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
   mavenCentral()
}
dependencies {
   compile('org.springframework.boot:spring-boot-starter')
   testCompile('org.springframework.boot:spring-boot-starter-test')
   compile('org.springframework.security.oauth:spring-security-oauth2')
   compile('org.springframework.boot:spring-boot-starter-web')
   testCompile('org.springframework.boot:spring-boot-starter-test')
}

次に、HTTPエンドポイントを追加して、以下に示すようにメインのSpring BootアプリケーションクラスファイルでSpring Bootを介して認証した後、Googleからユーザープリンシパルを読み取ります

package com.finddevguides.projects.googleservice;

import java.security.Principal;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
public class GoogleserviceApplication {
   public static void main(String[] args) {
      SpringApplication.run(GoogleserviceApplication.class, args);
   }
   @RequestMapping(value = "/user")
   public Principal user(Principal principal) {
      return principal;
   }
}

次に、構成ファイルを作成して、Webセキュリティ用にOAuth2SSOを有効にし、次のようにindexlファイルの認証を削除します-

package com.finddevguides.projects.googleservice;

import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso;
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
@EnableOAuth2Sso
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
   @Override
   protected void configure(HttpSecurity http) throws Exception {
      http
         .csrf()
         .disable()
         .antMatcher("/**")
         .authorizeRequests()
         .antMatchers("/", "/indexl")
         .permitAll()
         .anyRequest()
         .authenticated();
   }
}

次に、静的リソースの下にindexlファイルを追加し、ユーザーHTTPエンドポイントにリダイレクトするリンクを追加して、以下に示すようにGoogleユーザープリンシパルを読み取ります-

<!DOCTYPE html>
<html>
   <head>
      <meta charset = "ISO-8859-1">
      <title>Insert title here</title>
   </head>
   <body>
      <a href = "user">Click here to Google Login</a>
   </body>
</html>

-Google Cloudコンソールで-Gmailサービス、分析サービス、およびGoogle+サービスAPIを有効にします。

次に、資格情報セクションに移動して資格情報を作成し、OAuthクライアントIDを選択します。

認証情報セクション

次に、OAuth2同意画面で製品名を入力します。

OAuth2同意画面の製品名

次に、「Webアプリケーション」としてアプリケーションタイプを選択し、承認済みのJavaScriptオリジンと承認済みリダイレクトURIを指定します。

承認済みリダイレクトURI

これで、OAuth2クライアントIDとクライアントシークレットが作成されました。

作成されたOAuth2クライアントID

次に、アプリケーションプロパティファイルにクライアントIDとクライアントシークレットを追加します。

security.oauth2.client.clientId = <CLIENT_ID>
security.oauth2.client.clientSecret = <CLIENT_SECRET>
security.oauth2.client.accessTokenUri  =  https://www.googleapis.com/oauth2/v3/token
security.oauth2.client.userAuthorizationUri  =  https://accounts.google.com/o/oauth2/auth
security.oauth2.client.tokenName = oauth_token
security.oauth2.client.authenticationScheme = query
security.oauth2.client.clientAuthenticationScheme = form
security.oauth2.client.scope = profile email

security.oauth2.resource.userInfoUri  =  https://www.googleapis.com/userinfo/v2/me
security.oauth2.resource.preferTokenInfo = false

これで、実行可能なJARファイルを作成し、次のGradleコマンドを使用してSpring Bootアプリケーションを実行できます。

Gradleの場合、次のようにコマンドを使用できます-

gradle clean build

「BUILD SUCCESSFUL」の後、build/libsディレクトリの下にJARファイルがあります。

コマンドjava –jar <JARFILE>を使用してJARファイルを実行すると、アプリケーションがTomcatポート8080で開始されます。

次に、URL http://localhost:8080/ にアクセスして、Google Loginリンクをクリックします。

Googleログインリンク

Googleログイン画面にリダイレクトされ、Gmailログインの詳細が提供されます。

Googleログイン画面

ログインに成功すると、Gmailユーザーのプリンシパルオブジェクトを受け取ります。

Gmailユーザーの主要オブジェクト