resty icon indicating copy to clipboard operation
resty copied to clipboard

Feature: SetAuthTokenFunc()

Open MB175 opened this issue 2 years ago • 5 comments

Add ability to pass a custom func which is called on every request to renew or check authToken validity

MB175 avatar Feb 08 '23 10:02 MB175

Hi @MB175,

I think you can setup the middleware for every request:

  • Use client func OnBeforeRequest to renew auth token
  • Use client func OnAfterResponse to check auth token validity
// Create a Resty Client
client := resty.New()

// Registering Request Middleware
client.OnBeforeRequest(func(c *resty.Client, req *resty.Request) error {
    // Now you have access to Client and current Request object
    // manipulate it as per your need

    return nil  // if its success otherwise return error
  })

// Registering Response Middleware
client.OnAfterResponse(func(c *resty.Client, resp *resty.Response) error {
    // Now you have access to Client and current Response object
    // manipulate it as per your need

    return nil  // if its success otherwise return error
  })

Source: https://github.com/go-resty/resty#request-and-response-middleware

I hope this could be help this discussion.

kecci avatar Feb 20 '23 18:02 kecci

@kecci hi, yes thats exactly how I solved it right now. Thanks for your reply anyway, appreciate it.

I just thought since there is a set auth token func, it would be just as handy to have a dedicated refresher func.

MB175 avatar Feb 20 '23 18:02 MB175

@MB175 Thanks for reaching out and proposing a new feature. I will consider this for Resty v3.

Thanks @kecci for your help and assisting the fellow Resty user.

jeevatkm avatar Mar 06 '23 05:03 jeevatkm

Hi @MB175, According to @kecci answer we can know:
We can setup the middleware for every request to do renew auth token Maybe I think your question is how to refresh or verify the auth token validity in this way. And if so, we can refer to the golang/oauth2 implementation to validate and refresh auto token for each request in ourself defined request middleware.

Yes, as quoted above I think we should check that the token has expired before refreshing the token.

1Ckpwee avatar Apr 05 '23 16:04 1Ckpwee

Yes that's the setup I use, it's not about what refresh cycle or method is used. It's more about a convince Feature since there is a method to set an token I figured it might make sense if you could pass a custom refresher func along side

MB175 avatar Apr 05 '23 16:04 MB175