通过 Javascript 发送 Authorization Token Bearer

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51506579/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 09:34:39  来源:igfitidea点击:

Sending Authorization Token Bearer through Javascript

javascriptjqueryjwt

提问by Ronaldo Lanhellas

I'm trying to send a Authorization Token Bearer through Javascript to a REST Endpoint, so i doing in this way:

我正在尝试通过 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);
    }

My endpoint is running under a SpringBoot container, so i'm getting the HttpServletRequest and trying to get AUthorization Header but is always null:

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

static Authentication getAuthentication(HttpServletRequest request) {
        String token = request.getHeader(HEADER_STRING);
        //token is always null
...

Edit 1This is the error in Client-Side (Browser

编辑 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.

Edit 2To enable CORS in backend i'm using the following annotation with spring:

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

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

Edit 3I tried added the CORS in my Filter but no success:

编辑 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);
    }

回答by Zohaib Ijaz

You can use headerskey to add headers

您可以使用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) {

   }
});

You need to enable CORS on backend

您需要在后端启用 CORS

https://stackoverflow.com/a/32320294/5567387

https://stackoverflow.com/a/32320294/5567387