Sending Authorization Token Bearer through Javascript

56,883

You can use headers key to add 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

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

Share:
56,883
Ronaldo Lanhellas
Author by

Ronaldo Lanhellas

Updated on July 09, 2022

Comments

  • Ronaldo Lanhellas
    Ronaldo Lanhellas almost 2 years

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

    $.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:

    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

    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:

    @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:

    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);
        }
    
  • Ronaldo Lanhellas
    Ronaldo Lanhellas almost 6 years
    I tried but continue returning null in my java endpoint. I know that problem is not in java server because if i use postman and send a request with Authorization Bearer Token everything works.
  • Zohaib Ijaz
    Zohaib Ijaz almost 6 years
    You can also copy code generated by POSTMAN and try that getpostman.com/docs/v6/postman/sending_api_requests/…
  • Ronaldo Lanhellas
    Ronaldo Lanhellas almost 6 years
    I edited my post with error in client-side (browser)
  • Zohaib Ijaz
    Zohaib Ijaz almost 6 years
    which means there is CORS issue. Fix on server side
  • Ronaldo Lanhellas
    Ronaldo Lanhellas almost 6 years
    debugging my server-side i need this token to validate the request but as i said, this token is always null.
  • Zohaib Ijaz
    Zohaib Ijaz almost 6 years
    Because browsers don't allow cross origin ajaz calls, copy code generated by POSTMAN and if you still face same issue then it's sure it's CORS issue. Allow your host and required headers on backend.
  • Zohaib Ijaz
    Zohaib Ijaz almost 6 years
    @RonaldoLanhellas Have a look at this, stackoverflow.com/a/32320294/5567387 also you have not shared your backend code, how are you handling CORS issue
  • Ronaldo Lanhellas
    Ronaldo Lanhellas almost 6 years
    I tried with code generated by POSTMAN and i have same issue. So i can understand thaet is a CORS issue, do you have any tip how can i allow this i spring-boot ?
  • Zohaib Ijaz
    Zohaib Ijaz almost 6 years
    I added a link in my answer but google is your friend.
  • Ronaldo Lanhellas
    Ronaldo Lanhellas almost 6 years
    I already added a CORS Config in backend, saw my editied post please
  • Zohaib Ijaz
    Zohaib Ijaz almost 6 years
  • Ronaldo Lanhellas
    Ronaldo Lanhellas almost 6 years
  • Ronaldo Lanhellas
    Ronaldo Lanhellas almost 6 years
  • Cyril
    Cyril about 4 years
    For the comment 'You can also copy code generated by POSTMAN and try that', the resource has moved to another location: learning.postman.com/docs/postman/sending-api-requests/…