1. 概要

このチュートリアルでは、2要素認証機能をソフトトークンとSpringセキュリティで実装します。

新しい機能を既存のシンプルなログインフローに追加し、Google認証システムアプリを使用してトークンを生成します。

簡単に言えば、2要素認証は、「ユーザーが知っていることとユーザーが持っていること」というよく知られた原則に従う検証プロセスです。

そのため、ユーザーは認証中に追加の「検証トークン」を提供します。これは、時間ベースのワンタイムパスワードTOTPアルゴリズムに基づくワンタイムパスワード検証コードです。

2. Maven構成

まず、アプリでGoogle認証システムを使用するには、次のことを行う必要があります。

  • 秘密鍵を生成する
  • QRコードを介してユーザーに秘密鍵を提供する
  • この秘密鍵を使用してユーザーが入力したトークンを確認します。

単純なサーバー側のライブラリを使用して、 pom.xml に次の依存関係を追加することにより、ワンタイムパスワードを生成/検証します。

<dependency>
    <groupId>org.jboss.aerogear</groupId>
    <artifactId>aerogear-otp-java</artifactId>
    <version>1.0.0</version>
</dependency>

3. ユーザーエンティティ

次に、次のように、追加情報を保持するようにユーザーエンティティを変更します。

@Entity
public class User {
    ...
    private boolean isUsing2FA;
    private String secret;

    public User() {
        super();
        this.secret = Base32.random();
        ...
    }
}

ご了承ください:

  • 後で検証コードを生成する際に使用するために、ユーザーごとにランダムなシークレットコードを保存します
  • 2段階認証プロセスはオプションです

4. 追加のログインパラメータ

まず、追加のパラメーターである検証トークンを受け入れるようにセキュリティ構成を調整する必要があります。 カスタムAuthenticationDetailsSourceを使用することで、これを実現できます。

CustomWebAuthenticationDetailsSourceは次のとおりです。

@Component
public class CustomWebAuthenticationDetailsSource implements 
  AuthenticationDetailsSource<HttpServletRequest, WebAuthenticationDetails> {
    
    @Override
    public WebAuthenticationDetails buildDetails(HttpServletRequest context) {
        return new CustomWebAuthenticationDetails(context);
    }
}

CustomWebAuthenticationDetailsは次のとおりです。

public class CustomWebAuthenticationDetails extends WebAuthenticationDetails {

    private String verificationCode;

    public CustomWebAuthenticationDetails(HttpServletRequest request) {
        super(request);
        verificationCode = request.getParameter("code");
    }

    public String getVerificationCode() {
        return verificationCode;
    }
}

そして私たちのセキュリティ構成:

@Configuration
@EnableWebSecurity
public class LssSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private CustomWebAuthenticationDetailsSource authenticationDetailsSource;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()
            .authenticationDetailsSource(authenticationDetailsSource)
            ...
    } 
}

そして最後に、ログインフォームに追加のパラメータを追加します。

<labelth:text="#{label.form.login2fa}">
    Google Authenticator Verification Code
</label>
<input type='text' name='code'/>

注:セキュリティ構成でカスタムAuthenticationDetailsSourceを設定する必要があります。

5. カスタム認証プロバイダー

次に、追加のパラメーター検証を処理するためのカスタムAuthenticationProviderが必要です。

public class CustomAuthenticationProvider extends DaoAuthenticationProvider {

    @Autowired
    private UserRepository userRepository;

    @Override
    public Authentication authenticate(Authentication auth)
      throws AuthenticationException {
        String verificationCode 
          = ((CustomWebAuthenticationDetails) auth.getDetails())
            .getVerificationCode();
        User user = userRepository.findByEmail(auth.getName());
        if ((user == null)) {
            throw new BadCredentialsException("Invalid username or password");
        }
        if (user.isUsing2FA()) {
            Totp totp = new Totp(user.getSecret());
            if (!isValidLong(verificationCode) || !totp.verify(verificationCode)) {
                throw new BadCredentialsException("Invalid verfication code");
            }
        }
        
        Authentication result = super.authenticate(auth);
        return new UsernamePasswordAuthenticationToken(
          user, result.getCredentials(), result.getAuthorities());
    }

    private boolean isValidLong(String code) {
        try {
            Long.parseLong(code);
        } catch (NumberFormatException e) {
            return false;
        }
        return true;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }
}

注–ワンタイムパスワード検証コードを検証した後、認証をダウンストリームに委任しただけです。

これが認証プロバイダーBeanです

@Bean
public DaoAuthenticationProvider authProvider() {
    CustomAuthenticationProvider authProvider = new CustomAuthenticationProvider();
    authProvider.setUserDetailsService(userDetailsService);
    authProvider.setPasswordEncoder(encoder());
    return authProvider;
}

6. 登録手続き

これで、ユーザーがアプリケーションを使用してトークンを生成できるようにするには、登録時に適切に設定する必要があります。

そのため、登録プロセスにいくつかの簡単な変更を加える必要があります。2段階認証プロセスを使用することを選択したユーザーが、後でログインする必要があるQRコードをスキャンできるようにするためです

まず、この簡単な入力を登録フォームに追加します。

Use Two step verification <input type="checkbox" name="using2FA" value="true"/>

次に、 RegistrationController –登録を確認した後、選択に基づいてユーザーをリダイレクトします。

@GetMapping("/registrationConfirm")
public String confirmRegistration(@RequestParam("token") String token, ...) {
    String result = userService.validateVerificationToken(token);
    if(result.equals("valid")) {
        User user = userService.getUser(token);
        if (user.isUsing2FA()) {
            model.addAttribute("qr", userService.generateQRUrl(user));
            return "redirect:/qrcode.html?lang=" + locale.getLanguage();
        }
        
        model.addAttribute(
          "message", messages.getMessage("message.accountVerified", null, locale));
        return "redirect:/login?lang=" + locale.getLanguage();
    }
    ...
}

そして、これが私たちのメソッド generateQRUrl()です。

public static String QR_PREFIX = 
  "https://chart.googleapis.com/chart?chs=200x200&chld=M%%7C0&cht=qr&chl=";

@Override
public String generateQRUrl(User user) {
    return QR_PREFIX + URLEncoder.encode(String.format(
      "otpauth://totp/%s:%s?secret=%s&issuer=%s", 
      APP_NAME, user.getEmail(), user.getSecret(), APP_NAME),
      "UTF-8");
}

そして、これが私たちのqrcode.htmlです。

<html>
<body>
<div id="qr">
    <p>
        Scan this Barcode using Google Authenticator app on your phone 
        to use it later in login
    </p>
    <img th:src="${param.qr[0]}"/>
</div>
<a href="/login" class="btn btn-primary">Go to login page</a>
</body>
</html>

ご了承ください:

  • generateQRUrl()メソッドを使用してQRコードURLを生成します
  • このQRコードは、Google認証システムアプリを使用してユーザーの携帯電話によってスキャンされます
  • アプリは、30秒間のみ有効な6桁のコードを生成します。これは、目的の確認コードです。
  • この確認コードは、カスタムAuthenticationProviderを使用してログインするときに確認されます

7. 2段階認証を有効にする

次に、ユーザーがいつでもログイン設定を変更できるようにします–次のように。

@PostMapping("/user/update/2fa")
public GenericResponse modifyUser2FA(@RequestParam("use2FA") boolean use2FA) 
  throws UnsupportedEncodingException {
    User user = userService.updateUser2FA(use2FA);
    if (use2FA) {
        return new GenericResponse(userService.generateQRUrl(user));
    }
    return null;
}

そしてここにupdateUser2FA()があります:

@Override
public User updateUser2FA(boolean use2FA) {
    Authentication curAuth = SecurityContextHolder.getContext().getAuthentication();
    User currentUser = (User) curAuth.getPrincipal();
    currentUser.setUsing2FA(use2FA);
    currentUser = repository.save(currentUser);
    
    Authentication auth = new UsernamePasswordAuthenticationToken(
      currentUser, currentUser.getPassword(), curAuth.getAuthorities());
    SecurityContextHolder.getContext().setAuthentication(auth);
    return currentUser;
}

そして、これがフロントエンドです。

<div th:if="${#authentication.principal.using2FA}">
    You are using Two-step authentication 
    <a href="#" onclick="disable2FA()">Disable 2FA</a> 
</div>
<div th:if="${! #authentication.principal.using2FA}">
    You are not using Two-step authentication 
    <a href="#" onclick="enable2FA()">Enable 2FA</a> 
</div>
<br/>
<div id="qr" style="display:none;">
    <p>Scan this Barcode using Google Authenticator app on your phone </p>
</div>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
function enable2FA(){
    set2FA(true);
}
function disable2FA(){
    set2FA(false);
}
function set2FA(use2FA){
    $.post( "/user/update/2fa", { use2FA: use2FA } , function( data ) {
        if(use2FA){
        	$("#qr").append('<img src="'+data.message+'" />').show();
        }else{
            window.location.reload();
        }
    });
}
</script>

8. 結論

このクイックチュートリアルでは、SpringSecurityでソフトトークンを使用して2要素認証を実装する方法を説明しました。

完全なソースコードは、いつものように、GitHubにあります。