How to revoke APIToken after a user left

Article ID:360028857431
2 minute readKnowledge base

Issue

Sometimes, a Jenkins admin should find useful a way to revoke the APIToken for a given user.

Resolution

There are different options available to get this task accomplished.

Option 1

You should be able to take advantage of the script shown below, this script does not revoke the API token but refreshes it.

import hudson.model.User;
import jenkins.security.ApiTokenProperty;

//If set to true, no changes will be applied
def DRY=true
//You should write down here the name that the user
def userName="Put_the_user_name_here"

user = User.get(userName)
apiTokenProperty =  user.getProperty(ApiTokenProperty.class)

if(!DRY){
apiTokenProperty.changeApiToken()
user.save()
}

println DRY?"The test run successfully for "+user.displayName:" APIToken Changed for User: "+user.displayName

You can run this script from the Script console of your Jenkins instance: Manage Jenkins->Script Console. This script is valid for Versions higher than 2.138.1. It is easy to extend this script to be used as part of a parameterized job.

Option 2

You can revoke a specific API Token for a given user as long as you can locate the specific token uuid. In order to get that done, you will need to run the script below to get the corresponding uuid for the token that you want to revoke. Go to Manage Jenkins -> Script Console and run the following script.

getTokens.groovy

import hudson.model.*
import jenkins.model.*
import jenkins.security.*
import jenkins.security.apitoken.*

def userName="put_the_user_id_here"

user = User.get(userName)

def prop = user.getProperty(ApiTokenProperty.class)
// the name is up to you
def tokenList= prop.getTokenStore().getTokenListSortedByName()

tokenList.each() {

  println it.name + " uuid: "+ it.uuid

}

Alternatively, you can also invoke this script from the command line running the command shown below:

curl -k --user admin_user:admin_token --data-urlencode "script=$(< ./getTokens.groovy)" $JENKINS_URL/scriptText

Once that you have the corresponding list, you will be able to select the preferred uuid and then you can revoke it by directly running this command:

curl -k -X POST --USER admin_user:admin_token --data 'tokenUuid=put_the_uuid_here' $JENKINS_URL/user/tokentest/descriptorByName/jenkins.security.ApiTokenProperty/revoke

Option 3 (for legacy tokens)

There is another way to remove all legacy API tokens in Operations Center which is explained in the document linked below:

Essentially, what you need to do is to navigate to: $JENKINS_URL/administrativeMonitor/legacyApiToken this page will list the existing legacy tokens, the last time that these tokens were used and will give you the possibility of revoking one of them or all of them.

Tested product/plugin versions