Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7218565
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T21:29:58+00:00 2026-05-28T21:29:58+00:00

I’m working with a REST API that returns a 401 if my authorization token

  • 0

I’m working with a REST API that returns a 401 if my authorization token has expired. When I receive a 401, I’d like to run my authentication logic, retrieve a new token and then retry my original call. What’s the best way to do this.

Right now, I have an Authenticator class that “knows” how to authenticate with the API. The rest of the data access logic lives in a Repository object. The Repository object has the responsibility of sending requests to the API to retrieve information, using the information stored in the Authenticator.

An example of this is Repository.List() [It’s not really static, just writing it this way for brevity). Conceptually, this is what List() should do.

  • Try to connect to API and get a list of items
  • If 401 error, re-authenticate and try again
  • Return the list of items or throw an exception

This pattern will be used for all of my methods in all of my repositories, so I’d like a delegate or something that I could use with all of the API calls.

Any ideas?

Thanks,
Greg

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-28T21:29:58+00:00Added an answer on May 28, 2026 at 9:29 pm

    I came up with a solution that is working well.

    I created a static method that accepts two arguments, a Func and a reference to my
    Authentication object. The Authentication object can re-authenticate, and holds the auth info for making API calls. I used a ref because I didn’t want multiple instances of an Authenticator for one account existing with different auth tokens, but I needed to be able to support multiple accounts at the same time, so I couldn’t make it static.

    public static string ReauthenticateOn401(
        Func<Authenticator, string> method, 
        ref Authenticator authenticator)
    {
        if (method == null)
            throw new ArgumentNullException("action");
    
        if (authenticator == null)
            throw new ArgumentNullException("authenticator");
    
        int attempts_remaining = 2;
        bool reauth_attempted = false;
        while (attempts_remaining > 0)
        {
            try
            {
                return method(authenticator);
            }
            catch (WebException e)
            {
                if (e.Response != null && reauth_attempted == false)
                {
                    if (((HttpWebResponse)e.Response).StatusCode == HttpStatusCode.Unauthorized)
                    {
                        authenticator.GetAuthToken();
                        reauth_attempted = true;
                        attempts_remaining--;
                    }
                    else
                    {
                        throw;
                    }
                }
                else
                {
                    throw;
                }
            }
        }
        throw new Exception("The ReauthenticateOn401 method failed to return a response or catch/throw an exception.  The log flowed outside the while loop (not expected to be possible) and is generating this generic exception");
            }
    

    I then have different classes for requesting data from the API. Here is what one of them might look like, where _authenticator is passed into the class when the class is instantiated.

    string json = Authenticator.ReauthenticateOn401( (authenticator) =>
    {
        string apiUrl = "http:/blahblahblah.api.com"
        HttpWebRequest request = WebRequest.Create(apiUrl) as HttpWebRequest;
        //Add headers, or adjust the body as necessary for your API
        using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
        using (StreamReader reader = new StreamReader(response.GetResponseStream()))
        {
            return reader.ReadToEnd();
        }
    }, ref _authenticator);
    

    The beauty is that I can pass in whatever logic I want to ReathenticateOn401, and it will attempt to call the method, and then reauthenticate if a 401 is received. Otherwise, it will succeed or throw an exception that I can then handle.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I've got a string that has curly quotes in it. I'd like to replace
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I'm working with an upstream system that sometimes sends me text destined for HTML/XML
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I want to count how many characters a certain string has in PHP, but
I would like to count the length of a string with PHP. The string
For some reason, after submitting a string like this Jack’s Spindle from a text
Basically, what I'm trying to create is a page of div tags, each has

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.