在rest api项目中,我在端点使用Bearer Token进行呼叫 与程序:邮递员一起使用令牌。 但是在ajax中不起作用。
我试图在ajax代码中插入令牌,但是ii不起作用
使用Ajax代码
$.ajax({
type: 'GET',
url: url ,
dataType :'application/json',
contentType: 'application/json; charset=utf-8',
data: { nome : nome },
headers: { "Authorization": "Bearer fe500f21-070a-4539-9c92-09c1153bd6de"
},
success: function (data, textStatus, jqXHR) {
setRisultatoRicerca(JSON.stringify(data));
setNomeRicerca(nome);
window.location = "/ricerca";
},
error: function (jqXHR, textStatus, errorThrown) {
alert( "Nessun Prodotto Trovato");
}
});
});//
AuthenticationFilter:
AuthenticationFilter(final RequestMatcher requiresAuth) {
super(requiresAuth);
}
@Override
public Authentication attemptAuthentication(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws AuthenticationException, IOException, ServletException {
Optional<String> tokenParam = Optional.ofNullable(httpServletRequest.getHeader(AUTHORIZATION)); //Authorization: Bearer TOKEN
String token= StringUtils.isNotEmpty(httpServletRequest.getHeader(AUTHORIZATION))? httpServletRequest.getHeader(AUTHORIZATION) : "";
token= StringUtils.removeStart(token, "Bearer").trim();
Authentication requestAuthentication = new UsernamePasswordAuthenticationToken(token, token);
return getAuthenticationManager().authenticate(requestAuthentication);
}
@Override
protected void successfulAuthentication(final HttpServletRequest request, final HttpServletResponse response, final FilterChain chain, final Authentication authResult) throws IOException, ServletException {
SecurityContextHolder.getContext().setAuthentication(authResult);
chain.doFilter(request, response);
}
作为回应,我有错误代码401-未经授权