Script to Remove Accesstokens in Keychain

grier30
New Contributor

Trying to figure out a script that can delete all of the Default Keychains - local items - accesstokens. Would appreciate any assistants. Kind of new to scripting.

#!/bin/bash

# Function to list access tokens
list_access_tokens() {
    security find-generic-password -a $USER -s "OAuth Access Token" -g 2>&1 | grep "acct" | cut -d '"' -f 4
}

# Main function
main() {
    echo "Access Tokens found in Keychain:"
    list_access_tokens 

    echo "Enter the name of the access token you want to remove (or type 'exit' to quit):"
    read access_token_name

    if [ "$access_token_name" == "exit" ]; then
        echo "Exiting..."
        exit 0
    fi

    # Check if the access token exists
    if security find-generic-password -a $USER -s "OAuth Access Token" -l "$access_token_name" >/dev/null 2>&1; then
        echo "Removing access token: $access_token_name"
       
        echo "Access token removed successfully."
    else
        echo "Access token not found."
    fi
}

main

1 REPLY 1

christy2951hern
New Contributor

Hello NYStateofHealth@grier30 ,
Shebang Line (#!bin/bash**):** This line specifies the interpreter to use for the script, which is Bash in this case.
list_access_tokens Function: This function uses the security find-generic-password command to search for all items in the Default Keychain for the current user ($USER) where the service name is "OAuth Access Token" (-s "OAuth Access Token") and the kind is generic password (-g). The output is piped to grep to filter lines containing "acct" (which likely indicates account information) and then piped to cut to extract the access token name from the double quotes.
Prints a message indicating access tokens will be listed.
Calls the list_access_tokens function to display the list.
Prompts the user to enter the name of the access token to remove or "exit" to quit.
Checks if the user entered "exit" and exits the script if so.
Uses security find-generic-password again to verify if the entered access token name exists.
If the token exists, it removes it using security delete-generic-password (not shown in the provided script).
Prints success or failure messages based on the removal attempt.

Best Regards,
NYStateofHealth