Josh
Josh

Reputation: 2587

How do I properly authenticate an API call from a React SPA using auth0?

I think this should be relatively straightforward but I must be missing something simple. I have a user logged into a single page application, a React app running on localhost:3000 (using yarn start).

I have a backend API running on localhost:8080, built in go. I want to make my API private using auth0. I have the front end login portion working. I can't seem to get the API request authenticated properly. In my React code I have the following:

    const auth0 = await createAuth0Client({
        domain: 'mydomain.auth0.com',
        client_id: 'my_client_id_for_react_spa'
    });

    //just making sure this is true. It always is. 
    const isAuthenticated = await auth0.isAuthenticated();

    console.log("Is Authenticated: ", isAuthenticated);

    const token = await auth0.getTokenSilently();

    console.log("Token: ", token);

    try {
        const result = await fetch('http://localhost:8080/api/private', {
            method: 'GET',
            mode: 'no-cors',
            headers: {
                Authorization: 'Bearer ' + token,
            }
        });

        console.log("Result: ", result);
    } catch (e) {
        console.log("Error: ", e);
    }

I get a 401 response with the above. How can this be? I am authenticated and send the token along with my request. Clearly I'm missing something.

Edit

Here is the go code:

import (
    //...other stuff i need 
    jwtmiddleware "github.com/auth0/go-jwt-middleware"
    "github.com/codegangsta/negroni"
    jwt "github.com/dgrijalva/jwt-go"
    "github.com/gorilla/handlers"
    "github.com/gorilla/mux"
)

r := mux.NewRouter()

jwtMiddleware := jwtmiddleware.New(jwtmiddleware.Options{
    ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) {

        // Verify 'aud' claim
        aud := "https://api.mydomain.com"
        checkAud := token.Claims.(jwt.MapClaims).VerifyAudience(aud, false)
        if !checkAud {
            log.Println("Invalid audience")
            return token, errors.New("Invalid audience.")
        }
        // Verify 'iss' claim
        iss := "https://mydomain.auth0.com/"
        checkIss := token.Claims.(jwt.MapClaims).VerifyIssuer(iss, false)
        if !checkIss {
            log.Println("Invalid issuer")
            return token, errors.New("Invalid issuer.")
        }

        cert, err := getPemCert(token)
        if err != nil {
            panic(err.Error())
        }

        result, _ := jwt.ParseRSAPublicKeyFromPEM([]byte(cert))
        return result, nil
    },
    SigningMethod: jwt.SigningMethodRS256,
})

t := testAPIEndpoint{}
n := negroni.New(negroni.HandlerFunc(jwtMiddleware.HandlerWithNext), negroni.Wrap(t))
r.Handle("/api/private", n)

// This route is always accessible
r.Handle("/api/public", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    message := "Hello from a public endpoint! You don't need to be authenticated to see this."
    responseJSON(message, w, http.StatusOK)
}))

allowedOrigins := handlers.AllowedOrigins([]string{"http://localhost:3000"})

log.Fatal(http.ListenAndServe(":8080", handlers.CORS(allowedOrigins)(r)))

Upvotes: 0

Views: 313

Answers (1)

Tanver Hasan
Tanver Hasan

Reputation: 1763

I think you did not include the audience parameter when calling /authorize endpoint. As a result, you received opaque token instead of JWT token.

https://auth0.com/docs/tokens/access-tokens#access-token-structure

Try below:

  auth0 = await createAuth0Client({
    domain: config.domain,
    client_id: config.clientId,
    audience: config.audience   // API identifier (https://api.mydomain.com)
  });

Therefore, you will receive a valid JWT token with API authorization info. Try to decode the token in https://jwt.io to see the token structure. Make sure token has got aud claim. https://auth0.com/docs/tokens/jwt-claims#reserved-claims

I guess you can now call the API endpoints. https://auth0.com/docs/quickstart/spa/vanillajs/02-calling-an-api#calling-the-api

Upvotes: 1

Related Questions