登録-メールで新しいアカウントを有効にする
1. 概要
この記事では、登録プロセスの欠落している部分の1つであるverifying the user’s email to confirm their accountを使用してongoing Registration with Spring Security seriesを続けます。
登録確認メカニズムにより、ユーザーは、登録が成功した後に送信された「Confirm Registration」電子メールに応答して、電子メールアドレスを確認し、アカウントをアクティブ化する必要があります。 ユーザーは、電子メールで送信された一意のアクティベーションリンクをクリックしてこれを行います。
このロジックに従って、新しく登録されたユーザーは、このプロセスが完了するまでシステムにログインできません。
2. 検証トークン
ユーザーを検証するための主要な成果物として、単純な検証トークンを使用します。
2.1. VerificationTokenエンティティ
VerificationTokenエンティティは、次の基準を満たしている必要があります。
-
(一方向の関係を介して)Userにリンクし直す必要があります。
-
登録直後に作成されます
-
作成後、expire within 24 hoursになります
-
unique, randomly generatedの値があります
要件2および3は、登録ロジックの一部です。 他の2つは、例2.1のような単純なVerificationTokenエンティティに実装されています。
例2.1
@Entity
public class VerificationToken {
private static final int EXPIRATION = 60 * 24;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String token;
@OneToOne(targetEntity = User.class, fetch = FetchType.EAGER)
@JoinColumn(nullable = false, name = "user_id")
private User user;
private Date expiryDate;
private Date calculateExpiryDate(int expiryTimeInMinutes) {
Calendar cal = Calendar.getInstance();
cal.setTime(new Timestamp(cal.getTime().getTime()));
cal.add(Calendar.MINUTE, expiryTimeInMinutes);
return new Date(cal.getTime().getTime());
}
// standard constructors, getters and setters
}
VerificationToken<→_User_アソシエーションでデータの整合性と一貫性を確保するために、ユーザーのnullable = falseに注意してください。
2.2. enabledフィールドをUserに追加します
最初に、Userが登録されると、このenabledフィールドはfalseに設定されます。 アカウント検証プロセス中(成功した場合)、trueになります。
Userエンティティにフィールドを追加することから始めましょう。
public class User {
...
@Column(name = "enabled")
private boolean enabled;
public User() {
super();
this.enabled=false;
}
...
}
このフィールドのデフォルト値をfalseに設定する方法にも注意してください。
3. アカウント登録中
ユーザー登録のユースケースに2つのビジネスロジックを追加しましょう。
-
ユーザーのVerificationTokenを生成し、それを永続化します
-
アカウント確認用の電子メールメッセージを送信します–これにはVerificationToken’s値の確認リンクが含まれています
3.1. Springイベントを使用してトークンを作成し、確認メールを送信する
これらの2つの追加ロジックは、「付随的な」バックエンドタスクであるため、コントローラーで直接実行しないでください。
コントローラは、これらのタスクの実行をトリガーするためにSpringApplicationEventを公開します。 これは、ApplicationEventPublisherを挿入し、それを使用して登録完了を公開するのと同じくらい簡単です。
例3.1。 この単純なロジックを示します。
例3.1。
@Autowired
ApplicationEventPublisher eventPublisher
@RequestMapping(value = "/user/registration", method = RequestMethod.POST)
public ModelAndView registerUserAccount(
@ModelAttribute("user") @Valid UserDto accountDto,
BindingResult result,
WebRequest request,
Errors errors) {
if (result.hasErrors()) {
return new ModelAndView("registration", "user", accountDto);
}
User registered = createUserAccount(accountDto);
if (registered == null) {
result.rejectValue("email", "message.regError");
}
try {
String appUrl = request.getContextPath();
eventPublisher.publishEvent(new OnRegistrationCompleteEvent
(registered, request.getLocale(), appUrl));
} catch (Exception me) {
return new ModelAndView("emailError", "user", accountDto);
}
return new ModelAndView("successRegister", "user", accountDto);
}
注意すべきもう1つのことは、イベントの公開を囲むtry catchブロックです。 このコードは、イベントの発行後に実行されるロジックに例外がある場合は常にエラーページを表示します。この場合は、電子メールの送信です。
3.2. イベントとリスナー
ここで、コントローラーが送信するこの新しいOnRegistrationCompleteEventの実際の実装と、それを処理するリスナーを見てみましょう。
Example 3.2.1. –OnRegistrationCompleteEvent
public class OnRegistrationCompleteEvent extends ApplicationEvent {
private String appUrl;
private Locale locale;
private User user;
public OnRegistrationCompleteEvent(
User user, Locale locale, String appUrl) {
super(user);
this.user = user;
this.locale = locale;
this.appUrl = appUrl;
}
// standard getters and setters
}
Example 3.2.2. –The RegistrationListenerOnRegistrationCompleteEventを処理します
@Component
public class RegistrationListener implements
ApplicationListener {
@Autowired
private IUserService service;
@Autowired
private MessageSource messages;
@Autowired
private JavaMailSender mailSender;
@Override
public void onApplicationEvent(OnRegistrationCompleteEvent event) {
this.confirmRegistration(event);
}
private void confirmRegistration(OnRegistrationCompleteEvent event) {
User user = event.getUser();
String token = UUID.randomUUID().toString();
service.createVerificationToken(user, token);
String recipientAddress = user.getEmail();
String subject = "Registration Confirmation";
String confirmationUrl
= event.getAppUrl() + "/regitrationConfirm.html?token=" + token;
String message = messages.getMessage("message.regSucc", null, event.getLocale());
SimpleMailMessage email = new SimpleMailMessage();
email.setTo(recipientAddress);
email.setSubject(subject);
email.setText(message + " rn" + "http://localhost:8080" + confirmationUrl);
mailSender.send(email);
}
}
ここで、confirmRegistrationメソッドはOnRegistrationCompleteEventを受け取り、そこから必要なすべてのUser情報を抽出し、検証トークンを作成して永続化し、「%」のパラメーターとして送信します。 (t3)s」リンク。
上で述べたように、JavaMailSenderによってスローされたjavax.mail.AuthenticationFailedExceptionは、コントローラーによって処理されます。
3.3. 検証トークンパラメータの処理
ユーザーが「Confirm Registration」リンクを受け取ったら、それをクリックする必要があります。
実行すると、コントローラーは結果のGET要求でトークンパラメーターの値を抽出し、それを使用してUserを有効にします。
例3.3.1でこのプロセスを見てみましょう。
例3.3.1。 –RegistrationController登録確認の処理
@Autowired
private IUserService service;
@RequestMapping(value = "/regitrationConfirm", method = RequestMethod.GET)
public String confirmRegistration
(WebRequest request, Model model, @RequestParam("token") String token) {
Locale locale = request.getLocale();
VerificationToken verificationToken = service.getVerificationToken(token);
if (verificationToken == null) {
String message = messages.getMessage("auth.message.invalidToken", null, locale);
model.addAttribute("message", message);
return "redirect:/badUser.html?lang=" + locale.getLanguage();
}
User user = verificationToken.getUser();
Calendar cal = Calendar.getInstance();
if ((verificationToken.getExpiryDate().getTime() - cal.getTime().getTime()) <= 0) {
String messageValue = messages.getMessage("auth.message.expired", null, locale)
model.addAttribute("message", messageValue);
return "redirect:/badUser.html?lang=" + locale.getLanguage();
}
user.setEnabled(true);
service.saveRegisteredUser(user);
return "redirect:/login.html?lang=" + request.getLocale().getLanguage();
}
次の場合、ユーザーは対応するメッセージを含むエラーページにリダイレクトされます。
-
何らかの理由でVerificationTokenが存在しない、または
-
VerificationTokenの有効期限が切れています
See Example 3.3.2.でエラーページを表示します。
例3.3.2。 –badUser.html
signup
エラーが見つからない場合、ユーザーは有効になっています。
VerificationTokenのチェックと有効期限のシナリオの処理を改善する2つの機会があります。
-
We can use a Cron Jobは、バックグラウンドでトークンの有効期限をチェックします
-
有効期限が切れるとgive the user the opportunity to get a new tokenできます
今後の記事のために新しいトークンの生成を延期し、ユーザーがここでトークンを実際に正常に検証したと想定します。
4. ログインプロセスへのアカウントアクティベーションチェックの追加
ユーザーが有効になっているかどうかを確認するコードを追加する必要があります。
これを例4.1で見てみましょう。 これは、MyUserDetailsServiceのloadUserByUsernameメソッドを示しています。
例4.1。
@Autowired
UserRepository userRepository;
public UserDetails loadUserByUsername(String email)
throws UsernameNotFoundException {
boolean enabled = true;
boolean accountNonExpired = true;
boolean credentialsNonExpired = true;
boolean accountNonLocked = true;
try {
User user = userRepository.findByEmail(email);
if (user == null) {
throw new UsernameNotFoundException(
"No user found with username: " + email);
}
return new org.springframework.security.core.userdetails.User(
user.getEmail(),
user.getPassword().toLowerCase(),
user.isEnabled(),
accountNonExpired,
credentialsNonExpired,
accountNonLocked,
getAuthorities(user.getRole()));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
ご覧のとおり、MyUserDetailsServiceはユーザーのenabledフラグを使用しないため、ユーザーの認証のみが許可されます。
ここで、AuthenticationFailureHandlerを追加して、MyUserDetailsServiceからの例外メッセージをカスタマイズします。 CustomAuthenticationFailureHandlerを例4.2に示します。:
例4.2。 –CustomAuthenticationFailureHandler:
@Component
public class CustomAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {
@Autowired
private MessageSource messages;
@Autowired
private LocaleResolver localeResolver;
@Override
public void onAuthenticationFailure(HttpServletRequest request,
HttpServletResponse response, AuthenticationException exception)
throws IOException, ServletException {
setDefaultFailureUrl("/login.html?error=true");
super.onAuthenticationFailure(request, response, exception);
Locale locale = localeResolver.resolveLocale(request);
String errorMessage = messages.getMessage("message.badCredentials", null, locale);
if (exception.getMessage().equalsIgnoreCase("User is disabled")) {
errorMessage = messages.getMessage("auth.message.disabled", null, locale);
} else if (exception.getMessage().equalsIgnoreCase("User account has expired")) {
errorMessage = messages.getMessage("auth.message.expired", null, locale);
}
request.getSession().setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, errorMessage);
}
}
エラーメッセージを表示するには、login.htmlを変更する必要があります。
例4.3。 –login.htmlにエラーメッセージを表示します。
error
5. 永続層の適応
ここで、検証トークンとユーザーを含むこれらの操作のいくつかの実際の実装を提供しましょう。
以下について説明します。
-
新しいVerificationTokenRepository
-
IUserInterfaceの新しいメソッドと、必要な新しいCRUD操作の実装
例5.1 – 5.3。 新しいインターフェースと実装を示します。
Example 5.1. –VerificationTokenRepository
public interface VerificationTokenRepository
extends JpaRepository {
VerificationToken findByToken(String token);
VerificationToken findByUser(User user);
}
Example 5.2. –IUserServiceインターフェース
public interface IUserService {
User registerNewUserAccount(UserDto accountDto)
throws EmailExistsException;
User getUser(String verificationToken);
void saveRegisteredUser(User user);
void createVerificationToken(User user, String token);
VerificationToken getVerificationToken(String VerificationToken);
}
Example 5.3.UserService
@Service
@Transactional
public class UserService implements IUserService {
@Autowired
private UserRepository repository;
@Autowired
private VerificationTokenRepository tokenRepository;
@Override
public User registerNewUserAccount(UserDto accountDto)
throws EmailExistsException {
if (emailExist(accountDto.getEmail())) {
throw new EmailExistsException(
"There is an account with that email adress: "
+ accountDto.getEmail());
}
User user = new User();
user.setFirstName(accountDto.getFirstName());
user.setLastName(accountDto.getLastName());
user.setPassword(accountDto.getPassword());
user.setEmail(accountDto.getEmail());
user.setRole(new Role(Integer.valueOf(1), user));
return repository.save(user);
}
private boolean emailExist(String email) {
User user = repository.findByEmail(email);
if (user != null) {
return true;
}
return false;
}
@Override
public User getUser(String verificationToken) {
User user = tokenRepository.findByToken(verificationToken).getUser();
return user;
}
@Override
public VerificationToken getVerificationToken(String VerificationToken) {
return tokenRepository.findByToken(VerificationToken);
}
@Override
public void saveRegisteredUser(User user) {
repository.save(user);
}
@Override
public void createVerificationToken(User user, String token) {
VerificationToken myToken = new VerificationToken(token, user);
tokenRepository.save(myToken);
}
}
6. 結論
この記事では、登録プロセスを拡張してan email based account activation procedureを含めました。
アカウントアクティベーションロジックでは、ユーザーがIDを確認するためにコントローラーに送り返すことができるように、ユーザーに確認トークンを電子メールで送信する必要があります。
このSpringSecurityでの登録チュートリアルの実装は、the GitHub projectにあります。これはEclipseベースのプロジェクトであるため、そのままインポートして実行するのは簡単です。