Ниже приведено то, что у меня есть до сих пор, но оно не делает то, что я хочу. Я хочу, чтобы 415, если тип содержимого не json, а 400 jackson не могут десериализоваться или если проверка неверна. В настоящее время, конечно, это все 401, и я делаю что-то неправильно с десериализацией (передавал неправильный тип json). Я думаю, что может быть какой-то способ использовать то, что Spring MVC будет делать под капотом для обычного контроллера.Каков наилучший способ создания AuthenticationFilter с функциями REST?
@Component
public class JsonAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
private final ObjectMapper objectMapper;
private final Validator validator;
protected JsonAuthenticationFilter(final ObjectMapper objectMapper, final Validator validator) {
super(new AntPathRequestMatcher("/authentication/password", "POST"));
this.objectMapper = objectMapper;
this.validator = validator;
}
@Override
public Authentication attemptAuthentication(final HttpServletRequest request, final HttpServletResponse response)
throws AuthenticationException, IOException, ServletException {
if (request.getContentType() == null
|| !MediaType.APPLICATION_JSON.isCompatibleWith(MediaType.parseMediaType(request.getContentType()))) {
response.setStatus(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
throw new AuthenticationServiceException(
"Media Type not supported: " + request.getContentType());
}
PasswordCredentials credentials = objectMapper.readValue(request.getReader(), PasswordCredentials.class);
DataBinder dataBinder = new DataBinder(credentials);
dataBinder.setValidator(validator);
dataBinder.validate();
AbstractAuthenticationToken authRequest = credentials.toAuthenticationToken();
setDetails(request, authRequest);
return this.getAuthenticationManager().authenticate(authRequest);
}
/**
* Provided so that subclasses may configure what is put into the authentication
* request's details property.
*
* @param request that an authentication request is being created for
* @param authRequest the authentication request object that should have its details
* set
*/
protected void setDetails(HttpServletRequest request, AbstractAuthenticationToken authRequest) {
authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
}
@Override
@Autowired
public void setAuthenticationManager(final AuthenticationManager authenticationManager) {
super.setAuthenticationManager(authenticationManager);
}
}
Можете ли вы предоставить объект PasswordCredentials и формат сообщения json, который вы отправляете? – jlumietu
Не пишите сами, найдите проверенные примеры. Хорошим источником будет JHipster для запуска (https://github.com/jhipster/jhipster-sample-app-token) – Vaelyr
@jlumietu http://stackoverflow.com/q/39166509/206466 Я не думаю, что структура особенно релевантно, только изменение заключается в том, что я изменил значение 'toAuthentication' на' toAuthenticaitonToken' – xenoterracide