Spring Securityとの二要素認証

Spring Securityによる2要素認証

1. 概要

このチュートリアルでは、ソフトトークンとSpring Securityを使用してTwo Factor Authentication functionalityを実装します。

新しい機能をan existing, simple login flowに追加し、Google Authenticator appを使用してトークンを生成します。

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

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

2. Mavenの構成

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

  • 秘密鍵を生成する

  • QRコードを介してユーザーに秘密鍵を提供します

  • この秘密鍵を使用してユーザーが入力したトークンを確認します。

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


    org.jboss.aerogear
    aerogear-otp-java
    1.0.0

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 {

    @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)
            ...
    }
}

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


    Google Authenticator Verification 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. 登録手続き

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

そのため、登録プロセスにいくつかの簡単な変更を加える必要があります。これにより、scan the QR-code they need to login laterに対して2段階認証プロセスを使用することを選択したユーザーが使用できるようになります。

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

Use Two step verification 

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

@RequestMapping(value = "/registrationConfirm", method = RequestMethod.GET)
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があります:



Scan this Barcode using Google Authenticator app on your phone to use it later in login

Go to login page

ご了承ください:

  • generateQRUrl()メソッドを使用してQRコードURLを生成します

  • このQRコードは、Google認証システムアプリを使用してユーザーの携帯電話によってスキャンされます

  • アプリは、検証コードである30秒間のみ有効な6桁のコードを生成します

  • この確認コードは、カスタムAuthenticationProviderを使用してログインするときに確認されます

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

次に、ユーザーがログイン設定をいつでも変更できることを確認します-次のように:

@RequestMapping(value = "/user/update/2fa", method = RequestMethod.POST)
@ResponseBody
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;
}

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

You are using Two-step authentication Disable 2FA
You are not using Two-step authentication Enable 2FA

8. 結論

このクイックチュートリアルでは、Spring Securityでソフトトークンを使用して2要素認証の実装を行う方法を示しました。

完全なソースコードは、いつものようにover on GitHubで見つけることができます。