我正在尝试通过Javascript将授权令牌承载发送到REST端点,所以我这样做:
$.ajax( {
url: 'http://localhost:8080/resourceserver/protected-no-scope',
type: 'GET',
beforeSend : function( xhr ) {
xhr.setRequestHeader( "Authorization", "Bearer " + token );
},
success: function( response ) {
console.log(response);
}
我的端点在SpringBoot容器下运行,因此我正在获取HttpServletRequest并尝试获取AUthorization标头,但始终为null:
static Authentication getAuthentication(HttpServletRequest request) {
String token = request.getHeader(HEADER_STRING);
//token is always null
...
编辑1 这是客户端(浏览器
OPTIONS http://localhost:8080/resourceserver/protected-no-scope 403 ()
Failed to load http://localhost:8080/resourceserver/protected-no-scope: Response for preflight has invalid HTTP status code 403.
编辑2 为了在后端启用CORS,我在spring中使用了以下注释:
@RestController
@CrossOrigin(origins = "*", maxAge = 3600, allowCredentials = "true", allowedHeaders = "Authorization", methods =
{RequestMethod.GET, RequestMethod.OPTIONS, RequestMethod.POST})
public class MyResource {
编辑3 我尝试将CORS添加到我的过滤器中,但没有成功:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
httpServletResponse.setHeader("Access-Control-Allow-Origin", httpServletRequest.getHeader("Origin"));
httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
httpServletResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
httpServletResponse.setHeader("Access-Control-Max-Age", "3600");
httpServletResponse.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With, remember-me");
Authentication authentication = TokenAuthenticationService
.getAuthentication(httpServletRequest);
SecurityContextHolder.getContext().setAuthentication(authentication);
filterChain.doFilter(request, response);
}
答案 0 :(得分:2)
您可以使用headers
键添加标题
$.ajax({
url: 'http://localhost:8080/resourceserver/protected-no-scope',
type: 'GET',
contentType: 'application/json'
headers: {
'Authorization': 'Bearer <token>'
},
success: function (result) {
// CallBack(result);
},
error: function (error) {
}
});
您需要在后端启用CORS