简体   繁体   中英

Authentication errors in HTTP requisitions with AngularJs and Keycloak

I'm trying to create an app for study purposes with AngularJS and Keycloak.

And I'm experiencing some errors in my HTML requisitions:

Failed to load resource: the server responded with a status of 401 ()

XMLHttpRequest cannot load http://127.0.0.1:8081/customers . Response for preflight has invalid HTTP status code 401

My problem is in the requests made by the app. The requests made by Postman works fine.

My HTTP Requisition:

$http({
  method: 'GET',
  url: 'http://127.0.0.1:8081/customers'
}).then(function success(response) {
  console.log('success');
}, function error() {
  console.log('error');
});

My angular configs:

app.config(['$httpProvider', function ($httpProvider) {
   $httpProvider.interceptors.push('BearerAuthInterceptor');
}]);

app.factory('BearerAuthInterceptor', function () {
  var token = window._keycloak.token;

  return {
    request: function (config) {
      config.headers = config.headers || {};
      if (token) {
        config.headers.Authorization = 'Bearer ' + token;
      }
      return config;
    }
  };
});

From what I saw, the token is being sent in the header correctly.

I would be grateful if anyone could help me.

Make sure you have CORS enabled on your server to allow the client to make cross domain/cross port requests. The error

XMLHttpRequest cannot load http://127.0.0.1:8081/customers . Response for preflight has invalid HTTP status code 401

401 is unauthorized, preflight is the OPTIONS request the browser sends ahead of another HTTP request automatically when the request is using AJAX and is going to another domain/port from the client code that is making the call. The server just needs to respond with the appropriate headers to allow the client to get the response (it has to respond with the appropriate headers to the OPTION request)

https://enable-cors.org/

add "enable-cors":true on backend application keycloak.json file.

And add this class also.

@Component
public class CORSFilter implements Filter {
    static Logger logger = LoggerFactory.getLogger(CORSFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse res,
            FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "*");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "*");
        chain.doFilter(request, response);
    }

    public void destroy() {
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM