Kris Swat
Kris Swat

Reputation: 1024

Axios - React SWA - Azure function app - message: "Request failed with status code 400", name: "AxiosError", code: "ERR_BAD_REQUEST"

I am looking for a way to secure my Azure function app API.

The Static WebApp is react based and has google oauth.

I have simple functions that work from Code + Test , before linking Static WebApp and Function App.

After linking the expectation is to deny unauthorized access. But getting error {"code":400,"message":"Login not supported for provider azureStaticWebApps }

Config in azure portal Confiuration

Error: (firefox console)

​ message: "Request failed with status code 400", name: "AxiosError", code: "ERR_BAD_REQUEST", config: {…}, request: XMLHttpRequest, response: {…}, status: 400 } code: "ERR_BAD_REQUEST"

Network tab of developer tools (firefox)

{"code":400,"message":"Login not supported for provider azureStaticWebApps"}

Dev and Integration:

Created a react app, implemented google oauth , axios api.

   async function getItems( formattedDate, category,  personal, token) {
  try {
      const response = await instance
    .get("/api/register/find", {
          headers: { 'Authorization': bearer(token) },
          params: {        
            incidentDate: formattedDate,
            category: category,
            personal: personal
          },
        });
          return response;
        }
        catch (error) {
          console.log(error);
        };
    }

function bearer(token) { return Bearer ${token}; }

Function code :

@FunctionName("findRegister")
public HttpResponseMessage find(
        @HttpTrigger(name = "req", methods = {HttpMethod.GET}, route = "register/find") HttpRequestMessage<Optional<String>> request,
        final ExecutionContext context) {
    context.getLogger().info("Processing /register/find endpoint");
    final String query = request.getQueryParameters().get("incidentDate");
    final String incidentDate = request.getBody().orElse(query);
    var itemDto = new ItemDto(…);//dummy output
    var response = new ArrayList<ItemDto>();
    response.add(itemDto);
    try {
        String jsonResponse = mapper.writeValueAsString(response);
        return request.createResponseBuilder(HttpStatus.OK)
                .header("Content-Type", "application/json")
                .body(jsonResponse)
                .build();
    } catch (JsonProcessingException e) {
        context.getLogger().severe("Error creating Items : " + e.getMessage());
        return request.createResponseBuilder(HttpStatus.INTERNAL_SERVER_ERROR)
                .body("Error Fetching response")
                .build();
    }

}

Function app is not logging - context.getLogger().info("Processing /register/find endpoint"); Not sure why ?

There is some info about a file staticwebapp.config.json from link - info link but not sure where this exists. (could not find)

Should SWA be created differently? configure SWA

How to troubleshoot ? Is there a way to test or remote debug ? Is there a problem in the request ? Anything react app config to check

As mentioned before I dont have staticwebapp.config.json...not sure if azure-static-web-apps-icy-dune-09764cf03.yml is alternate

How to test function app in Code + Test after linking ? enter image description here

Upvotes: 0

Views: 142

Answers (1)

Sampath
Sampath

Reputation: 3669

After deploying the sample Azure Function, I enabled Google authentication but encountered the same 401 error, as shown below:

StaticWebapp Azurefunction

You need to use the URL https://<app-name>.azurewebsites.net/.auth/login/google/callback for login purposes:

Afterlogin

I referred to this guide for adding Google login to a React app. In the React app, I used the callback URL code as shown in this documentation.

Below code is Google login with the React app using callbackurl:

const handleClick = () => {
    const callbackUrl = `${window.location.origin}`;
    const googleClientId = "YOUR_CLIENT_ID_FROM_GOOGLE";
    const targetUrl = `https://accounts.google.com/o/oauth2/auth?redirect_uri=${encodeURIComponent(
      callbackUrl
    )}&response_type=token&client_id=${googleClientId}&scope=openid%20email%20profile`;
    window.location.href = targetUrl;
  };

  useEffect(() => {
    const accessTokenRegex = /access_token=([^&]+)/;
    const isMatch = window.location.href.match(accessTokenRegex);

To fetch the data, I used the following code:

   if (!res.ok) {
        throw new Error(`Error: ${res.status} - ${res.statusText}`);
      }
      const data = await res.text(); // Assuming response is plain text.
      setResponse(data);
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

I followed this doc for Google Authentication with my Azure Function app. Additionally, I referred to this Microsoft documentation for enabling Google authentication in Azure Static Web Apps.

Here’s the staticwebapp.config.json file configuration: staticwebapp.config.json:

{
  "routes": [
    {
      "route": "/",
      "allowedRoles": ["anonymous"]
    }
  ],
  "navigationFallback": {
    "rewrite": "/index.html"
  },
  "globalHeaders": {
    "cache-control": "no-store, must-revalidate"
  },
  "trailingSlash": "auto",
  "auth": {
    "identityProviders": {
      "google": {
        "registration": {
          "clientIdSettingName": "GOOGLE_CLIENT_ID",
          "clientSecretSettingName": "GOOGLE_CLIENT_SECRET"
        }
      }
    }
  }
}

Make sure to add CORS settings in the Azure function configuration. Azure Static Output

Upvotes: 1

Related Questions