<dependency>
<groupId>org.springframework.social</groupId>
<artifactId>spring-social-facebook</artifactId>
</dependency>
このチュートリアルでは、既存のフォームログインアプリケーションに新しいFacebookログインを追加することに焦点を当てます。
私たちは、Spring Socialサポートを使ってFacebookと対話し、物事をきれいでシンプルにしていきます。
まず、pom.xmlにspring-social-facebook依存関係を追加する必要があります。
<dependency>
<groupId>org.springframework.social</groupId>
<artifactId>spring-social-facebook</artifactId>
</dependency>
まずフォームベースの認証がある単純なセキュリティ設定から始めましょう。
@Configuration
@EnableWebSecurity
@ComponentScan(basePackages = { "org.baeldung.security" })
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Override
protected void configure(AuthenticationManagerBuilder auth)
throws Exception {
auth.userDetailsService(userDetailsService);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/login** ").permitAll()
.anyRequest().authenticated()
.and()
.formLogin().loginPage("/login").permitAll();
}
}
この設定にはあまり時間をかけません - もっと理解したいのなら、リンクを見てください:/spring-security-login[フォームのログイン記事]。
それでは、Facebookを利用して、システムに認証するための新しい方法を追加しましょう。
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private ConnectionFactoryLocator connectionFactoryLocator;
@Autowired
private UsersConnectionRepository usersConnectionRepository;
@Autowired
private FacebookConnectionSignup facebookConnectionSignup;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/login** ","/signin/** ** ","/signup/** ** ").permitAll()
...
}
@Bean
public ProviderSignInController providerSignInController() {
((InMemoryUsersConnectionRepository) usersConnectionRepository)
.setConnectionSignUp(facebookConnectionSignup);
return new ProviderSignInController(
connectionFactoryLocator,
usersConnectionRepository,
new FacebookSignInAdapter());
}
}
新しい設定をよく見てみましょう。
Facebookを有効にするために ProviderSignInController を使用しています
認証 ** POST を“ /signin/facebook ”に送ることによって
Facebookサービスプロバイダを使用してユーザーサインインを開始する ** ログインロジックを処理するために SignInAdapter を設定しています。
応用 ** そしてユーザーのサインアップを処理するために ConnectionSignUp も設定します。
彼らが最初にFacebookで認証を受けたとき
端的に言うと、このアダプタは、上記のコントローラ(Facebookユーザのサインインフローを促進する)と当社の特定のローカルアプリケーションとの間のブリッジです。
public class FacebookSignInAdapter implements SignInAdapter {
@Override
public String signIn(
String localUserId,
Connection<?> connection,
NativeWebRequest request) {
SecurityContextHolder.getContext().setAuthentication(
new UsernamePasswordAuthenticationToken(
connection.getDisplayName(), null,
Arrays.asList(new SimpleGrantedAuthority("FACEBOOK__USER"))));
return null;
}
}
Facebookを使用してログインしたユーザーは FACEBOOK USER ロールを持ち、formを使用してログインしたユーザーは USERロールを持ちます。 + __
ユーザーが初めてFacebookで認証されたときは、アプリケーションに既存のアカウントはありません。
これが、そのアカウントを自動的に作成する必要があるポイントです。そのユーザー作成ロジックを推進するために ConnectionSignUp を使用します。
@Service
public class FacebookConnectionSignup implements ConnectionSignUp {
@Autowired
private UserRepository userRepository;
@Override
public String execute(Connection<?> connection) {
User user = new User();
user.setUsername(connection.getDisplayName());
user.setPassword(randomAlphabetic(8));
userRepository.save(user);
return user.getUsername();
}
}
ご覧のとおり、 DisplayName をユーザー名として使用して、新しいユーザーのアカウントを作成しました。
次に、application.propertiesでFacebookのプロパティを設定しましょう。
spring.social.facebook.appId=YOUR__APP__ID
spring.social.facebook.appSecret=YOUR__APP__SECRET
ご了承ください:
私たちは appId を取得するためにFacebookアプリケーションを作成する必要があります。
appSecret ** Facebookアプリケーションの設定から、必ずプラットフォームを追加してください
“ Website”と http://localhost:8080/ は“サイトURL”です。
最後に、私たちのフロントエンドを見てみましょう。
ログインページで、フォームログインとFacebookの2つの認証フローをサポートします。
<html>
<body>
<div th:if="${param.logout}">You have been logged out</div>
<div th:if="${param.error}">There was an error, please try again</div>
<form th:action="@{/login}" method="POST" >
<input type="text" name="username"/>
<input type="password" name="password"/>
<input type="submit" value="Login"/>
</form>
<form action="/signin/facebook" method="POST">
<input type="hidden" name="scope" value="public__profile"/>
<input type="submit" value="Login using Facebook"/>
</form>
</body>
</html>
最後に、これが__index.htmlです。
<html>
<body>
<nav>
<p sec:authentication="name">Username</p>
<a th:href="@{/logout}">Logout</a>
</nav>
<h1>Welcome, <span sec:authentication="name">Username</span></h1>
<p sec:authentication="authorities">User authorities</p>
</body>
</html>
このインデックスページがユーザー名と権限をどのように表示しているかに注意してください。
これで、アプリケーションへの認証には2つの方法があります。
この簡単な記事では、 spring-social-facebook を使用してアプリケーションの2次認証フローを実装する方法を学びました。
そしてもちろん、いつものように、ソースコードは完全に入手可能です。