Spring Boot:如何告诉客户帐户密码已过期?

时间:2018-07-26 23:15:23

标签: spring-boot jwt

我在控制器中有一个简单的登录表单和一个login()方法:

@PostMapping("/login")
public ResponseEntity<UserVO> login(@RequestBody UserVO userVO) {

    Authentication authentication = authenticationManager.authenticate(
            new UsernamePasswordAuthenticationToken(
                    userVO.getUsername(),
                    userVO.getPassword()
            )
    );

    SecurityContextHolder.getContext().setAuthentication( authentication );

    // ...
    return ResponseEntity.ok( loggedInUser );
}

我有一个包含列的用户表:

  `username`
  `password`
  `password_expiration`
  `account_expiration`
  `account_locked`
  `account_disabled`

当我设置password_expiration列的值以使用户密码失效时,Spring Boot的 authenticationManager.authenticate()方法在下次尝试登录时会引发 AccountExpiredException 异常:

package org.springframework.security.authentication;

public class AccountExpiredException extends AccountStatusException {
    public AccountExpiredException(String msg) {
        super(msg);
    }

    public AccountExpiredException(String msg, Throwable t) {
        super(msg, t);
    }
}

,JSON响应为:

{
"timestamp":"2018-07-26T22:53:05.392+0000",
"status":401,
"error":"Unauthorized",
"message":"Unauthorized",
"path":"/login"
}

每当密码错误或UserVO的一种方法(反过来实现UserDetails)返回false时,我都会得到相同的JSON响应(401错误代码):

boolean isAccountNonExpired();

boolean isAccountNonLocked();

boolean isCredentialsNonExpired();

boolean isEnabled();

到目前为止很好。

当用户登录并且他/她的密码过期时,我想将UI重定向到强制性的密码更改页面。但是如何?我总是得到相同的JSON响应。

1)由于返回的JSON输出始终是HTTP 401错误,如何获得更细粒度的响应? (如何告诉客户密码密码已过期?)

2)告知用户其帐户已被锁定/过期/被禁用通常被认为是好习惯还是坏习惯? (良好的用户体验,而不是向黑客泄露有关帐户状态的信息)

1 个答案:

答案 0 :(得分:0)

也许不是最好的解决方案,但是我通过设置“消息”字段来解决它:

@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint, Serializable {

    @Override
    public void commence(HttpServletRequest request,
                         HttpServletResponse response,
                         AuthenticationException authException) throws IOException {

        String message = "Unauthorized";
        if ( authException instanceof BadCredentialsException )
            message = AUTH_CREDENTIALS_BAD;
        else if ( authException instanceof CredentialsExpiredException )
            message = AUTH_CREDENTIALS_EXPIRED;
        else if ( authException instanceof LockedException )
            message = AUTH_ACCOUNT_LOCKED;
        else if ( authException instanceof DisabledException )
            message = AUTH_ACCOUNT_DISABLED;
        else if ( authException instanceof AccountExpiredException )
            message = AUTH_ACCOUNT_EXPIRED;

        response.sendError( HttpServletResponse.SC_UNAUTHORIZED, message );
    }
}

现在我得到这个答复:

{
   "timestamp":"2018-07-27T12:54:53.097+0000",
   "status":401,
   "error":"Unauthorized",
   "message":"credentials_expired",
   "path":"/login"
}