Search code examples
iosoauthnsurlconnectionnsurl

append additional information in a web request for authentication


I am implementing my own authentication framework for OAuth 2.0. As far as my understanding is concerned server sends 401 if token has been expired.

I implemented NSURLConnection's delegate

- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge;

to catch these error and refresh token.

- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge{
// refresh token and send it to server

    if ([challenge previousFailureCount] > 0) {
            // do something may be alert message
        } 
    else
    {
         //refreshToken
    }
}

But it seems to be that there is no way I can append the token to url.


Solution

  • you can't - changing the url means a new request. the current request is in progress and it is for this URL.

    one straightforward way is to have a 'wrapper object' around the url connection itself, that could transparently do a 2nd request should the 1st fail

    e.g. PSEUDOCODE

    @interface MyConnection
    - loadRequest:(NSURLRequest*)r completionHandler:handler //not fully felshed out for this example
    @end
    
    @implementation MyConnection
    
    - loadRequest:(NSURLRequest*)r completionHandler:handler //not fully felshed out for this example 
    {
        [NSURLConnection sendRequest:r completion:{
            if(response.status == 401)
            {
                NSMutableURLRequest *r2 = [NSMutableURLRequest requestWithURL:r.URL + token];
                //refresh by sending a new request r2
                    [NSURLConnection sendRequest:r2 completion:{
                        handler(response);
                    }];
            }
            else {
                handler(response);
            }
        }];
    }
    @end