Spring Securityでのみ利用可能な場所からの認証を許可

Spring Securityを使用して、受け入れられた場所からの認証のみを許可する

1. 概要

このチュートリアルでは、非常に興味深いセキュリティ機能、つまりユーザーの場所に基づいてユーザーのアカウントを保護することに焦点を当てます。

簡単に言えば、we’ll block any login from unusual or non-standard locationsを使用すると、ユーザーは安全な方法で新しい場所を有効にできます。

これはpart of the registration seriesであり、当然、既存のコードベースの上に構築されます。

2. ユーザーロケーションモデル

まず、ユーザーのログイン場所に関する情報を保持するUserLocationモデルを見てみましょう。各ユーザーには、アカウントに関連付けられた場所が少なくとも1つあります。

@Entity
public class UserLocation {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String country;

    private boolean enabled;

    @ManyToOne(targetEntity = User.class, fetch = FetchType.EAGER)
    @JoinColumn(nullable = false, name = "user_id")
    private User user;

    public UserLocation() {
        super();
        enabled = false;
    }

    public UserLocation(String country, User user) {
        super();
        this.country = country;
        this.user = user;
        enabled = false;
    }
    ...
}

そして、リポジトリに簡単な取得操作を追加します。

public interface UserLocationRepository extends JpaRepository {
    UserLocation findByCountryAndUser(String country, User user);
}

ご了承ください

  • 新しいUserLocationはデフォルトで無効になっています

  • 各ユーザーには、アカウントに関連付けられた少なくとも1つの場所があり、登録時にアプリケーションにアクセスした最初の場所です。

3. 登録

次に、登録プロセスを変更してデフォルトのユーザーの場所を追加する方法について説明します。

@RequestMapping(value = "/user/registration", method = RequestMethod.POST)
@ResponseBody
public GenericResponse registerUserAccount(@Valid UserDto accountDto,
  HttpServletRequest request) {

    User registered = userService.registerNewUserAccount(accountDto);
    userService.addUserLocation(registered, getClientIP(request));
    ...
}

サービスの実装では、ユーザーのIPアドレスで国を取得します。

public void addUserLocation(User user, String ip) {
    InetAddress ipAddress = InetAddress.getByName(ip);
    String country
      = databaseReader.country(ipAddress).getCountry().getName();
    UserLocation loc = new UserLocation(country, user);
    loc.setEnabled(true);
    loc = userLocationRepo.save(loc);
}

GeoLite2データベースを使用して、IPアドレスから国を取得していることに注意してください。 GeoLite2を使用するには、Mavenの依存関係が必要でした。


    com.maxmind.geoip2
    geoip2
    2.9.0

また、単純なBeanを定義する必要もあります。

@Bean
public DatabaseReader databaseReader() throws IOException, GeoIp2Exception {
    File resource = new File("src/main/resources/GeoLite2-Country.mmdb");
    return new DatabaseReader.Builder(resource).build();
}

ここでMaxMindからGeoLite2 Countryデータベースをロードしました。

4. 安全なログイン

ユーザーのデフォルトの国がわかったので、認証後に簡単な場所チェッカーを追加します。

@Autowired
private DifferentLocationChecker differentLocationChecker;

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

そしてここに私たちのDifferentLocationCheckerがあります:

@Component
public class DifferentLocationChecker implements UserDetailsChecker {

    @Autowired
    private IUserService userService;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private ApplicationEventPublisher eventPublisher;

    @Override
    public void check(UserDetails userDetails) {
        String ip = getClientIP();
        NewLocationToken token = userService.isNewLoginLocation(userDetails.getUsername(), ip);
        if (token != null) {
            String appUrl =
              "http://"
              + request.getServerName()
              + ":" + request.getServerPort()
              + request.getContextPath();

            eventPublisher.publishEvent(
              new OnDifferentLocationLoginEvent(
                request.getLocale(), userDetails.getUsername(), ip, token, appUrl));
            throw new UnusualLocationException("unusual location");
        }
    }

    private String getClientIP() {
        String xfHeader = request.getHeader("X-Forwarded-For");
        if (xfHeader == null) {
            return request.getRemoteAddr();
        }
        return xfHeader.split(",")[0];
    }
}

ユーザーが適切な資格情報を提供したときにthe check only run after successful authenticationになるように、setPostAuthenticationChecks()を使用したことに注意してください。

また、カスタムUnusualLocationExceptionは単純なAuthenticationExceptionです。

エラーメッセージをカスタマイズするには、AuthenticationFailureHandlerも変更する必要があります。

@Override
public void onAuthenticationFailure(...) {
    ...
    else if (exception.getMessage().equalsIgnoreCase("unusual location")) {
        errorMessage = messages.getMessage("auth.message.unusual.location", null, locale);
    }
}

それでは、isNewLoginLocation()の実装を詳しく見てみましょう。

@Override
public NewLocationToken isNewLoginLocation(String username, String ip) {
    try {
        InetAddress ipAddress = InetAddress.getByName(ip);
        String country
          = databaseReader.country(ipAddress).getCountry().getName();

        User user = repository.findByEmail(username);
        UserLocation loc = userLocationRepo.findByCountryAndUser(country, user);
        if ((loc == null) || !loc.isEnabled()) {
            return createNewLocationToken(country, user);
        }
    } catch (Exception e) {
        return null;
    }
    return null;
}

ユーザーが正しい資格情報を提供したときに、その場所を確認する方法に注意してください。 場所が既にそのユーザーアカウントに関連付けられている場合、ユーザーは正常に認証できます。

そうでない場合は、NewLocationTokenと無効なUserLocationを作成して、ユーザーがこの新しい場所を有効にできるようにします。 詳細については、次のセクションをご覧ください。

private NewLocationToken createNewLocationToken(String country, User user) {
    UserLocation loc = new UserLocation(country, user);
    loc = userLocationRepo.save(loc);
    NewLocationToken token = new NewLocationToken(UUID.randomUUID().toString(), loc);
    return newLocationTokenRepository.save(token);
}

最後に、単純なNewLocationTokenの実装を示します。これにより、ユーザーは新しい場所を自分のアカウントに関連付けることができます。

@Entity
public class NewLocationToken {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String token;

    @OneToOne(targetEntity = UserLocation.class, fetch = FetchType.EAGER)
    @JoinColumn(nullable = false, name = "user_location_id")
    private UserLocation userLocation;

    ...
}

5. 別の場所のログインイベント

ユーザーが別の場所からログインするときに、NewLocationTokenを作成し、それを使用してOnDifferentLocationLoginEventをトリガーしました。

public class OnDifferentLocationLoginEvent extends ApplicationEvent {
    private Locale locale;
    private String username;
    private String ip;
    private NewLocationToken token;
    private String appUrl;
}

DifferentLocationLoginListenerは、イベントを次のように処理します。

@Component
public class DifferentLocationLoginListener
  implements ApplicationListener {

    @Autowired
    private MessageSource messages;

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private Environment env;

    @Override
    public void onApplicationEvent(OnDifferentLocationLoginEvent event) {
        String enableLocUri = event.getAppUrl() + "/user/enableNewLoc?token="
          + event.getToken().getToken();
        String changePassUri = event.getAppUrl() + "/changePassword.html";
        String recipientAddress = event.getUsername();
        String subject = "Login attempt from different location";
        String message = messages.getMessage("message.differentLocation", new Object[] {
          new Date().toString(),
          event.getToken().getUserLocation().getCountry(),
          event.getIp(), enableLocUri, changePassUri
          }, event.getLocale());

        SimpleMailMessage email = new SimpleMailMessage();
        email.setTo(recipientAddress);
        email.setSubject(subject);
        email.setText(message);
        email.setFrom(env.getProperty("support.email"));
        mailSender.send(email);
    }
}

when the user logs in from a different location, we’ll send an email to notify themに注意してください。

他の誰かが自分のアカウントにログインしようとした場合、もちろん、その人はパスワードを変更します。 認証の試みを認識した場合、新しいログイン場所を自分のアカウントに関連付けることができます。

6. 新しいログイン場所を有効にする

最後に、疑わしいアクティビティがユーザーに通知されたので、how the application will handle enabling the new locationを見てみましょう。

@RequestMapping(value = "/user/enableNewLoc", method = RequestMethod.GET)
public String enableNewLoc(Locale locale, Model model, @RequestParam("token") String token) {
    String loc = userService.isValidNewLocationToken(token);
    if (loc != null) {
        model.addAttribute(
          "message",
          messages.getMessage("message.newLoc.enabled", new Object[] { loc }, locale)
        );
    } else {
        model.addAttribute(
          "message",
          messages.getMessage("message.error", null, locale)
        );
    }
    return "redirect:/login?lang=" + locale.getLanguage();
}

そして、isValidNewLocationToken()メソッド:

@Override
public String isValidNewLocationToken(String token) {
    NewLocationToken locToken = newLocationTokenRepository.findByToken(token);
    if (locToken == null) {
        return null;
    }
    UserLocation userLoc = locToken.getUserLocation();
    userLoc.setEnabled(true);
    userLoc = userLocationRepo.save(userLoc);
    newLocationTokenRepository.delete(locToken);
    return userLoc.getCountry();
}

簡単に言うと、トークンに関連付けられているUserLocationを有効にしてから、トークンを削除します。

7. 結論

このチュートリアルでは、アプリケーションにセキュリティを追加するための強力な新しいメカニズムに焦点を当てました–restricting unexpected user activity based on their location.

いつものように、完全な実装はover on GiHubで見つけることができます。