パスワードを更新する

1概要

このクイック記事では、ユーザーが登録してログインした後に、ユーザーが利用できる簡単な「自分のパスワードを変更する」機能を実装します。

2クライアントサイド - パスワードページを変更する

非常に単純なクライアントサイドページを見てみましょう。

<html>
<body>
<div id="errormsg" style="display:none"></div>
<div>
    <input id="oldpass" name="oldpassword" type="password"/>
    <input id="pass" name="password" type="password"/>
    <input id="passConfirm" type="password"/>
    <span id="error" style="display:none">Password mismatch</span>

   <button type="submit" onclick="savePass()">Change Password</button>
</div>

<script src="jquery.min.js"></script>
<script type="text/javascript">

var serverContext =[[@{/}]];
function savePass(){
    var pass = $("#pass").val();
    var valid = pass == $("#passConfirm").val();
    if(!valid) {
      $("#error").show();
      return;
    }
    $.post(serverContext + "user/updatePassword",
      {password: pass, oldpassword: $("#oldpass").val()} ,function(data){
        window.location.href = serverContext +"/home.html?message="+data.message;
    })
    .fail(function(data) {
        $("#errormsg").show().html(data.responseJSON.message);
    });
}
</script>
</body>
</html>

3ユーザーパスワードの更新

サーバー側の操作も実装しましょう。

@RequestMapping(value = "/user/updatePassword", method = RequestMethod.POST)
@PreAuthorize("hasRole('READ__PRIVILEGE')")
@ResponseBody
public GenericResponse changeUserPassword(Locale locale,
  @RequestParam("password") String password,
  @RequestParam("oldpassword") String oldPassword) {
    User user = userService.findUserByEmail(
      SecurityContextHolder.getContext().getAuthentication().getName());

    if (!userService.checkIfValidOldPassword(user, oldPassword)) {
        throw new InvalidOldPasswordException();
    }
    userService.changeUserPassword(user, password);
    return new GenericResponse(messages.getMessage("message.updatePasswordSuc", null, locale));
}

このメソッドは @ PreAuthorize アノテーションを介してどのように保護されているかに注意してください。ログインユーザーにのみ** アクセス可能であるべきです。

4 APIテスト

最後に、すべてが正常に機能していることを確認するために、いくつかのAPIテストでAPIを使用しましょう。テストの簡単な構成とデータの初期化から始めましょう。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(
  classes = { ConfigTest.class, PersistenceJPAConfig.class },
  loader = AnnotationConfigContextLoader.class)
public class ChangePasswordApiTest {
    private final String URL__PREFIX = "http://localhost:8080/";
    private final String URL = URL__PREFIX + "/user/updatePassword";

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    FormAuthConfig formConfig = new FormAuthConfig(
      URL__PREFIX + "/login", "username", "password");

    @Before
    public void init() {
        User user = userRepository.findByEmail("[email protected]");
        if (user == null) {
            user = new User();
            user.setFirstName("Test");
            user.setLastName("Test");
            user.setPassword(passwordEncoder.encode("test"));
            user.setEmail("[email protected]");
            user.setEnabled(true);
            userRepository.save(user);
        } else {
            user.setPassword(passwordEncoder.encode("test"));
            userRepository.save(user);
        }
    }
}

それでは、ログインしたユーザーのパスワードを変更してみましょう。

@Test
public void givenLoggedInUser__whenChangingPassword__thenCorrect() {
    RequestSpecification request = RestAssured.given().auth()
      .form("[email protected]", "test", formConfig);

    Map<String, String> params = new HashMap<String, String>();
    params.put("oldpassword", "test");
    params.put("password", "newtest");

    Response response = request.with().params(params).post(URL);

    assertEquals(200, response.statusCode());
    assertTrue(response.body().asString().contains("Password updated successfully"));
}

次に、間違った古いパスワードを入力して、パスワードを変更してみましょう。

@Test
public void givenWrongOldPassword__whenChangingPassword__thenBadRequest() {
    RequestSpecification request = RestAssured.given().auth()
      .form("[email protected]", "test", formConfig);

    Map<String, String> params = new HashMap<String, String>();
    params.put("oldpassword", "abc");
    params.put("password", "newtest");

    Response response = request.with().params(params).post(URL);

    assertEquals(400, response.statusCode());
    assertTrue(response.body().asString().contains("Invalid Old Password"));
}

最後に、認証なしでパスワードを変更してみましょう。

@Test
public void givenNotAuthenticatedUser__whenChangingPassword__thenRedirect() {
    Map<String, String> params = new HashMap<String, String>();
    params.put("oldpassword", "abc");
    params.put("password", "xyz");

    Response response = RestAssured.with().params(params).post(URL);

    assertEquals(302, response.statusCode());
    assertFalse(response.body().asString().contains("Password updated successfully"));
}

各テストで認証を処理するための FormAuthConfig を提供していることに注意してください。

テストの前に正しいパスワードを使用するように、 init() を使用してパスワードをリセットします。

5結論

これがラップです - アプリケーションを登録してログインした後で、ユーザーが自分のパスワードを変更できるようにする直接的な方法です。

このチュートリアルの 完全な実装 はhttps://github.com/eugenp/spring-security-registration[the github project]にあります - これはEclipseベースのプロジェクトなので、インポートして実行するのは簡単です。そうです。

  • «** 前へ