我有一个身份验证过滤器,在这里处理身份验证请求时,我应该发送一个post请求/登录,主体为{“username”:“asdd”,“password”:“asada”}
@RequiredArgsConstructor
public class JsonAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
private final ObjectMapper objectMapper;
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) {
if (isJsonContent(request)) {
return authenticate(request);
}
return super.attemptAuthentication(request, response);
}
private boolean isJsonContent(HttpServletRequest request) {
try {
String contentType = request.getContentType();
return !isEmpty(contentType) && APPLICATION_JSON.isCompatibleWith(parseMediaType(contentType));
} catch (InvalidMediaTypeException e) {
return false;
}
}
private Authentication authenticate(HttpServletRequest request) {
val login = readRequest(request);
UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(login.username,
login.password);
setDetails(request, authToken);
return this.getAuthenticationManager().authenticate(authToken);
}
private LoginRequest readRequest(HttpServletRequest request) {
...
return new LoginRequest(username, password)
}
@Value
private static class LoginRequest {
String username;
String password;
}
}
在这里,我捕获auth失败并返回带有自定义消息的json
@Component
@AllArgsConstructor
@FieldDefaults(level = PRIVATE, makeFinal = true)
public class CustomAuthenticationFailureHandler
implements AuthenticationFailureHandler {
@NonNull
ObjectMapper objectMapper;
@NonNull
AccountRepository userRepository;
@Override
@ResponseBody
public void onAuthenticationFailure(
HttpServletRequest request,
HttpServletResponse response,
AuthenticationException exception) throws IOException {
String username = request.getParameter("username"); <-- and here its returns null!!
request.getUserPrincipal();
Account account = userRepository.findByLogin(username);
String errorCode = checkAccount(account);
response.setStatus(HttpStatus.UNAUTHORIZED.value());
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
objectMapper.writeValue(response.getWriter(), new ValidationErrors(exception, errorCode));
}
private String checkAccount(Account account) {
....
return errorCode;
}
}
问题是我无法从请求中获取用户名。也许我把它过滤掉了?如何从请求中获取用户名?也许我忘了用用户名和密码设置一些参数?
1条答案
按热度按时间vd8tlhqk1#
尝试使用Map器(如com.fasterxml.jackson.databind.objectmapper)并定义一个类:
然后获取body登录: