Search code examples
flutterjwtcorskeycloakwebsecurity

Problem with keycloak cors. No 'Access-Control-Allow-Origin'


I use keycloak and hasura. I have a flutter web app. I retrive the JWT token from keycloak using flutter http. But I get this error:

XMLHttpRequest error.

Access to XMLHttpRequest at 'http://xxx.xx.xxx.xxx:8080/auth/realms
/hasura-app/protocol/openid-connect/token' from origin 
'http://localhost:5050' has been blocked by CORS policy: Request header
field access-control-allow-origin is not allowed by Access-Control-Allow-Headers 
in preflight response.

But when I use reqbin/curl and this curl command:

curl --request POST \
  --url http://xxx.xx.xxx.xxx:8080/auth/realms/hasura-app/protocol/openid-connect/token \
  --header 'Content-Type: application/x-www-form-urlencoded' \
  --data username=user \
  --data password=password \
  --data grant_type=password \
  --data client_id=hasura

it works. This is my flutter code:

String url = 'http://xxx.xx.xxx.xxx:8080/auth/realms/hasura-app/protocol/openid-connect/token';

      Map<String, String> headers = {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Access-Control-Allow-Origin': '*',
      };
    
      String body = 'username=user&password=password&grant_type=password&client_id=hasura';
    
      final response = await http.post(Uri.parse(url), headers: headers, body: body);
      print(response.body);

When I use --web-browser-flag "--disable-web-security" it works fine. But I cannot use this I need this for production. My app will be in the closed local network.


Solution

  • I fix it. I set Web Origins: * and Valid Redirect URIs: *. Like in the image: image

    But the real problem is in flutter code - headers. I set headers in flutter to this:

    Map<String, String> headers = {
        'Content-Type': 'application/x-www-form-urlencoded',
         'Access-Control-Allow-Origin': '*',
      };
    

    This 'Access-Control-Allow-Origin': '*' should not be here. I remove him and all work.

    Map<String, String> headers = {
        'Content-Type': 'application/x-www-form-urlencoded',
      };
    

    So final flutter code is this:

    String url = 'http://xxx.xx.xxx.xxx:8080/auth/realms/hasura-app/protocol/openid-connect/token';
    
      Map<String, String> headers = {
        'Content-Type': 'application/x-www-form-urlencoded',
      };
    
      String body = 'username=user&password=password&grant_type=password&client_id=hasura';
    
      final response = await http.post(Uri.parse(url), headers: headers, body: body);
      print(response.body);