Using the wixSecretsbackend update function requires special privileges?

I am trying to cache an access token obtained from an oauth2 flow. I would like to do this with the wix secrets api.

I try to use the update() function from the wixSecrectsBackend but I read that this function needs wix members activated. This function also only seems to work when i am logged in with an admin user on the live site.

If I am not logged in with an admin user, it gives me a 403 error.

Some side info, I am calling this function from the backend, the backend should be allowed to call such functions shouldn’t it?

1 Like

Certain functionality is only available when a site has a Members area.

See the following for information on the Wix Secrets Manager:

Yes, that is fine, I have the members area enabled, however I can’t seem to make requests to the wixSecretsBackend unless the function call originates from a web session where a wix admin is logged in.

Should it not be great if the backend could make changes to the wixSecrets without having to be logged in with an admin account?

I even tried with the job scheduler (maybe this runs within admin context) , This also does not seem to be able to call the function without a permission error.

Adjustment, I cant seem to make update requests to the secretsbackend without being logged in as an admin. getSecret runs without any trouble.

@thomas1675 Please share your code (nicely formatted in a code block please) so we can what you are trying to do.

thanks for the help Yisrael!
I have written 2 functions, the first GetAccessToken() gets the previously cached access token from the secrets backend, checks if it is expired & tries to refresh it when needed. This function uses the storeAccessToken() function to store the refreshed token into the secretsbackend. ( this is where it goes wrong and I get a 403 code back from the wixSecretsBackend.update() function)

export async function getAccessToken () {
await setClient ()
const storedSecret = await wixSecretsBackend . getSecret ( “teamleader_access_token” );
let accessToken = {};

if ( storedSecret === null || storedSecret === “” ) {
return accessToken ;
} else {
accessToken = client . createToken ( JSON . parse ( storedSecret ));

if ( accessToken . expired ()) {
console . log ( “Token expired, refreshing” )
try {
const refreshParams = {};
accessToken = await accessToken . refresh ( refreshParams )
storeAccessToken ( accessToken )
} catch ( error ) {
console . log ( 'Error refreshing access token: ’ , error . message );
}
}
}
return accessToken
}

export async function storeAccessToken ( token ) {
console . log ( token )

const secret = {
value : stringify ( token )
}
try {
await wixSecretsBackend . updateSecret ( teamleaderSecretId , secret )
console . log ( “access token stored” )
} catch ( err ) {
console . log ( "StoringSecret error: " + err )
}
}

This is the error that I get (sorry not a 403, but a 400 )

root": {

“insertId”:“…9biwKWJu47yfs2JvutyT_s”
“timestamp”:“2021-07-08T14:32:11.621Z”

“labels”: { “siteUrl”:“https://www.reparatiewijzer.be/”
“revision”:“2700”
“namespace”:“Velo”
“tenantId”:“371a4af1-6ea4-47bd-8235-4e67027b91d6”
“viewMode”:“Site”
}

“sourceLocation”: {}

“operation”: { “id”:“1625754728.68461947210619773”
“producer”:“backend”
}

“jsonPayload”: { “message”:"["Error refreshing access token: “,“Response Error: 400 Bad Request”]”
}
“severity”:“INFO”
“receiveTimestamp”:“2021-07-08T14:32:11.819Z”
}

Welp, from what I see, this error is not on updateSecret() , but rather on your call to accessToken.refresh():

accessToken = await accessToken.refresh(refreshParams)

Even the error message that you posted states: Error refreshing access token

As far as I can tell, you never get to updateSecret().

Also, I don’t see where you set the teamleaderSecretId variable. I guess it’s a global variable that you set somewhere else in the code. Note that global variables might not behave as you expect in backend code. You should get the value of teamleaderSecretId right inside of the storeAccessToken() function to ensure it doesn’t get changed by another process.

I put the global variable inside my code now, and I am sorry, the error code i provided was wrong, I got that code because there was no valid access token in the secret to refresh.

This is the actual error I was talking about
“root”: {

“insertId”:“…KwNiVSenKBEst1IprFhWQr”
“timestamp”:“2021-07-08T15:34:52.692Z”

“labels”: { “siteUrl”:“https://www.reparatiewijzer.be/”
“revision”:“2702”
“namespace”:“Velo”
“tenantId”:“371a4af1-6ea4-47bd-8235-4e67027b91d6”
“viewMode”:“Site”
}

“sourceLocation”: {}

“operation”: { “id”:“1625758491.8346202444671329739”
“producer”:“backend”
}

“jsonPayload”: { “message”:“[“StoringSecret error: Error: PERMISSION_DENIED: Permission denied, status: 403”]”
}
“severity”:“INFO”
“receiveTimestamp”:“2021-07-08T15:34:52.891Z”
}

This does not happen if I visit the page that triggers this function with an admin user.

I’m checking with the devs about the issue of permissions. I’ll get back to you.

@yisrael-wix Thank you very much! Have a nice day

Hello, I’ve got the same issue here. I get PERMISSION_DENIED: Permission denied, status: 403" every time I try to create or update a secret if the request doesn’t come from a loggedin admin session.

I’ve got an http function that tries to update a secret which fails with this error, while the same code called from a dashboard page works just fine.

Do you have any update on this issue?

I don’t really have an update yet, for now what I do is encrypt the access token with a key from wixsecrets and store it in a wix collection and decrypt it with the key when I want to use it…

Facing the same issue here! I would like to re-open this discussion after 2 years… Im having a really hard time trying to update secrets!

Has this issue been resolved? I am facing a similar issue with an undefined 400 response every time I try to update a secret.

Any update with this issue? I am getting 400 when running updateSecret(). I am passing right parameter (triple checked)

async function refreshToken() {
    try {
        console.log("Starting token refresh process.");
        await initializeOAuthClient();

        const oldRefreshToken = await getSecret("quickbook_refreshToken");
        console.log("Current Refresh Token:", oldRefreshToken);

        const authResponse = await oauthClient.refreshUsingToken(oldRefreshToken);
        currentAccessToken = authResponse.getToken().access_token;
        const newRefreshToken = authResponse.getToken().refresh_token;

        console.log("New Access Token:", currentAccessToken);
        console.log("New Refresh Token Value:", newRefreshToken);
        // Access Token Secret
        const accessTokenSecret = {
            value: currentAccessToken
            // Add other properties like 'name', 'description' if required
        };
        const accessTokenId = "c57a1b7f-23b3-47dc-be62-cd29ae06a3b9";

        // Refresh Token Secret
        const refreshTokenSecret = {
            value: newRefreshToken
            // Add other properties like 'name', 'description' if required
        };
        const refreshTokenId = "289859b8-b912-44e0-aaa4-379ccf71c7a0";

        // Update Access Token
        await updateSecret(accessTokenId, accessTokenSecret)
            .then(() => console.log("Access token updated successfully."))
            .catch(e => console.error("Error updating access token:", e));

        // Update Refresh Token
        if (newRefreshToken !== oldRefreshToken) {
            await updateSecret(refreshTokenId, refreshTokenSecret)
                .then(() => console.log("Refresh token updated successfully."))
                .catch(e => console.error("Error updating refresh token:", e));
        }

    } catch (e) {
        console.error('Error refreshing token:', e);
        if (e.response) {
            console.error('Error response:', e.response);
        }
        throw e;
    }
}
Error updating access token: undefined, status: 400