我认为这应该相对简单,但是我必须缺少一些简单的东西。我有一个用户登录到一个单页应用程序,即一个在localhost:3000上运行的React应用程序(使用yarn start)。
我有一个运行在localhost:8080上的后端API,内置在go中。我想使用auth0将我的API设为 private 。我有前端登录部分正在工作。我似乎无法正确验证API请求。在我的React代码中,我有以下内容:
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);
}
我收到上面的401响应。怎么会这样?我已通过身份验证,并将 token 与我的请求一起发送。显然我缺少了一些东西。
编辑
这是执行代码:
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)))
最佳答案
我认为您在调用 / authorize 端点时未包括受众参数。结果,您收到了不透明 token 而不是JWT token 。
https://auth0.com/docs/tokens/access-tokens#access-token-structure
请尝试以下方法:
auth0 = await createAuth0Client({
domain: config.domain,
client_id: config.clientId,
audience: config.audience // API identifier (https://api.mydomain.com)
});
因此,您将收到带有API授权信息的有效JWT token 。尝试解码https://jwt.io中的 token 以查看 token 结构。确保 token 具有和aud 声明。
https://auth0.com/docs/tokens/jwt-claims#reserved-claims
我想您现在可以调用API端点了。
https://auth0.com/docs/quickstart/spa/vanillajs/02-calling-an-api#calling-the-api
关于reactjs - 如何使用auth0正确验证来自React SPA的API调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59638284/