简体   繁体   English

通过 Javascript 发送 Authorization Token Bearer

[英]Sending Authorization Token Bearer through Javascript

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 并尝试获取授权 Header 但始终为 null:

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

Edit 1 This 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 2 To 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 3 I 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);
    }

You can use headers key to add headers 您可以使用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) {

   }
});

You need to enable CORS on backend 您需要在后端启用CORS

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

Sending the request with Fetch API使用Fetch 发送请求 API

fetch('http://localhost:8080/resourceserver/protected-no-scope', { 
    method: 'GET', 
    headers: new Headers({
        'Authorization': 'Bearer <token>',
        'Content-Type': 'application/x-www-form-urlencoded'
    })
});

// before htttps.get use authorization in header. // 在 header 中的 https.get 使用授权之前。

const options = { headers: { 'Authorization': 'Bearer token' } https.get(url,options,function(res){ const options = { headers: { 'Authorization': 'Bearer token' } https.get(url,options,function(res){

console.log(res.statusCode); console.log(res.statusCode); } }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Javascript 中的授权承载令牌头 - Authorization Bearer Token Header in Javascript 通过 JQuery Ajax 发送 Authorization Token Bearer - 后端是 .NET Core Web Api - Sending Authorization Token Bearer through JQuery Ajax - Back end is .NET Core Web Api 如何在 javascript 中使用 POST 方法和授权承载令牌获取 API? - How to fetch API with POST method and Authorization Bearer token in javascript? 如何在 websocket javascript 客户端中传递授权承载访问令牌 - how to pass Authorization Bearer access token in websocket javascript client 如何从 JavaScript (Angular 2/4) 中的授权标头中检索承载令牌? - How to retrieve a Bearer Token from an Authorization Header in JavaScript (Angular 2/4)? Firebase 授权不记名令牌未注册 - Firebase authorization bearer token not registering 如何在 axios 中配置 Authorization bearer token? - How to configure Authorization bearer token in axios? 带有令牌承载javascript的onload函数 - onload function with token bearer javascript 使用Bearer令牌在JavaScript中加载图像 - Loading Image in JavaScript with Bearer token 如何设置使用Javascript通过Gmail Api发送邮件的授权? - How to set authorization for sending mail through Gmail Api in Javascript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM