通过Javascript发送授权令牌承载

Ron*_*las 10 javascript jquery jwt

我正在尝试通过 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);
    }
Run Code Online (Sandbox Code Playgroud)

我的端点在 SpringBoot 容器下运行,所以我正在获取 HttpServletRequest 并尝试获取 AUthorization Header 但始终为空:

static Authentication getAuthentication(HttpServletRequest request) {
        String token = request.getHeader(HEADER_STRING);
        //token is always null
...
Run Code Online (Sandbox Code Playgroud)

编辑 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.
Run Code Online (Sandbox Code Playgroud)

编辑 2 要在后端启用 CORS,我在 spring 中使用以下注释:

@RestController
@CrossOrigin(origins = "*", maxAge = 3600, allowCredentials = "true", allowedHeaders = "Authorization", methods =
        {RequestMethod.GET, RequestMethod.OPTIONS, RequestMethod.POST})
public class MyResource {
Run Code Online (Sandbox Code Playgroud)

编辑 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);
    }
Run Code Online (Sandbox Code Playgroud)

Zoh*_*jaz 21

您可以使用headerskey 添加标题

$.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) {

   }
});
Run Code Online (Sandbox Code Playgroud)

您需要在后端启用 CORS

/sf/answers/2262420611/