Skip to content
This repository has been archived by the owner on Jan 17, 2023. It is now read-only.

Request failed: unauthorized (401) #118

Open
praveenkumar56060 opened this issue Apr 6, 2016 · 3 comments
Open

Request failed: unauthorized (401) #118

praveenkumar56060 opened this issue Apr 6, 2016 · 3 comments

Comments

@praveenkumar56060
Copy link

Always, returns only Request failed: unauthorized (401) But, working with postman client plugin.

NSURL *baseURL = [NSURL URLWithString:BASEURL];
AFOAuth2Manager *manager = [[AFOAuth2Manager alloc] initWithBaseURL:baseURL clientID:CONSUMERKEY secret:CONSUMERSECRET];
[manager GET:PATH parameters:[self parameters] success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"Success: %@", responseObject);
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
     }
     failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         NSLog(@"Failure: %@", error.localizedDescription);
         [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}];

What could be the problem? Am i setting wrong place for the CONSUMERKEY and CONSUMERSECRET

@gundelsw
Copy link

gundelsw commented Apr 6, 2016

Hi - first make sure all your paths and variables are correct. Be sure you put the correct clientID and secret to the initialisation. These are NOT the OAUTH2 Tokens but the key and secret for your client as defined in your oauth2 backend! I suppose you do not have much experience with the oauth2 workflow. Please be sure to post a call first for getting an oauth2 token. Now it depends on which oauth2 flow you have implemented in your backend. There are multiple possibilites! For example I am using oauth2 bearer tokens. So first I use this method for initialization:
[manager initWithBaseURL:[NSURL URLWithString:urlString] clientID:kClientID secret:kClientSecret];
Then I need to make a post call to my backend with a correct username and secret to get a oauth2 bearer token. I do this by calling the correct auth endpoint at my backend e.g. serverpath/signin.
As soon as you got the token you need to make sure to sign all following requests with this token to be authorized. Therefore I use this:
[manager.requestSerializer setAuthorizationHeaderFieldWithCredential:newCredential];
When the user logs out you need to clean the token. You will also need some logic to check if the user already has a valid token or needs to signin for a new token first.
Good luck! Hope this helps.

@praveenkumar56060
Copy link
Author

Actually, i was impressed with AFNetworking, obviously everyone too 👍 So, i have started integrating all my API calls with AFNetworking instead of using NSURLConnection Previously, my OAuth works with TDOAuth which will create a NSMutableURLRequest For sample check my below code, [I've written this code 2 years back]

NSURLRequest *request = [TDOAuth URLRequestForPath:[NSString stringWithFormat:@"%@%@", PATH, path] GETParameters:params scheme:@"http" host:HOST consumerKey:CONSUMER_KEY consumerSecret:CONSUMER_SECRET accessToken:@"" tokenSecret:@""];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    NSLog(@"Request URL: %@", response.URL.absoluteString);
    if (connectionError) {
        block(connectionError, nil);
    } else {
        NSError *localError = nil;
        id result = [NSJSONSerialization JSONObjectWithData:data options:0 error:&localError];
        if (localError) {
            block(localError, nil);
        } else {
            block(nil, result);
        }
    }
}];

Still, this produces the result which AFOAuth2Manager not. What's the different in this? @gundelsw

@gundelsw
Copy link

gundelsw commented Apr 6, 2016

well I suppose your request is not signed. hmm interesting - well i was using another version of oauth2 based on afnetworking too. I had to recode stuff when I switched to new version of afnetworking but for me the pain was to rewrite my calls (similar to yours) to new afoauth2manager. For me it is working fine. Here you have a complete GET call in objC that works on my backend - I changed the name of the endpoint. There must be sth wrong with your request signing or with the stuff you are sending to the endpoint.

TGHttpClient *client = [TGHttpClient sharedClient];
    NSString *path = @"/theendpointname";
    [client GET:path parameters:nil
            success:success
            failure:^(AFHTTPRequestOperation *operation, NSError *error)
            {
                //NSLog(@"Failing request headers: %@", operation.request.allHTTPHeaderFields);
                NSLog(@"error was:%@", error);
                if (operation.response.statusCode == 401)
                    [[TGHttpClient sharedClient] refreshTokenAndRetryOperation:operation success:success failure:failure];
            }
     ];

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants