Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
    }
like image 467
Ronaldo Lanhellas Avatar asked Jul 24 '18 19:07

Ronaldo Lanhellas


People also ask

How do I pass Authorization Bearer Token?

Bearer tokens enable requests to authenticate using an access key, such as a JSON Web Token (JWT). The token is a text string, included in the request header. In the request Authorization tab, select Bearer Token from the Type dropdown list. In the Token field, enter your API key value.

How do I send a POST request with Bearer Token?

To send a POST JSON request with a Bearer Token authorization header, you need to make an HTTP POST request, provide your Bearer Token with an Authorization: Bearer {token} HTTP header and give the JSON data in the body of the POST message.

Can I pass Bearer Token in URL?

Don't pass bearer tokens in page URLs: Bearer tokens SHOULD NOT be passed in page URLs (for example, as query string parameters). Instead, bearer tokens SHOULD be passed in HTTP message headers or message bodies for which confidentiality measures are taken.

How do I send the Authorization header in HTTP?

It is a simple authentication scheme built into the HTTP protocol. The client sends HTTP requests with the Authorization header that contains the word Basic, followed by a space and a base64-encoded(non-encrypted) string username: password. For example, to authorize as username / Pa$$w0rd the client would send.

How do I send a GET request with Bearer Token Authorization header?

How do I Send a GET Request with Bearer Token Authorization Header? [JavaScript/AJAX Code] To send a GET request with a Bearer Token authorization header using JavaScript/AJAX, you need to make an HTTP GET request and provide your Bearer Token with the Authorization: Bearer {token} HTTP header.

What is a Bearer Token?

A Bearer Token is a cryptic string typically generated by the server in response to a login request. The client must send this Bearer Token in the Authorization header on every request it makes to obtain a protected resource. For security reasons, Bearer Tokens are only sent over HTTPS (SSL).

What is bearer authentication scheme in JavaScript/Ajax?

After receiving a 401 response, your JavaScript/AJAX client can send another HTTP request with a valid authorization header. The Bearer Authentication Scheme was initially created as part of OAuth 2.0 in RFC6750 but is sometimes also used by itself. For security reasons, the bearer token should only be sent over HTTPS ( SSL) connections.

What is bearer authentication and how does it work?

Bearer authentication (also called token authentication) is one of the HTTP authentication schemes that grant access to the bearer of this token. Bearer token authentication is done by sending a security token with every HTTP request we make to the server. You can do bearer authentication with any programming language, including JavaScript/AJAX.


1 Answers

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

like image 51
Zohaib Ijaz Avatar answered Sep 17 '22 13:09

Zohaib Ijaz