Ronaldo Lanhellas
Ronaldo Lanhellas

Reputation: 3336

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:

$.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);
    }

Upvotes: 18

Views: 111154

Answers (3)

Ali
Ali

Reputation: 11

Before https.get use authorization in header.

const options = {
  headers: {
    'Authorization': 'Bearer token'
  }
}

https.get(url, options, function(res) {
  console.log(res.statusCode);
})

Upvotes: 1

ORHAN ERDAY
ORHAN ERDAY

Reputation: 1076

Sending the request with 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'
    })
});

Upvotes: 3

Zohaib Ijaz
Zohaib Ijaz

Reputation: 22885

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

Upvotes: 34

Related Questions