OAuth2 to Authenticate API - Cannot Redirect Back to my App

oauth2 desktop application
oauth redirect uri example
google oauth redirect uri
app-claimed https url redirection
google oauth callback url
registered redirect uri
oauth redirect url twitch
oauth2 authorization code example

I'm trying to use the Trakt API to get a list of TV shows and other data. However, I'm stuck on authenticating my app with Trakt. I have my API key, secret, and redirect URI, but am struggling on how to authorise my app. I've tried the following:

Method 1, using the sample code from Trakt:


    NSString *redirectURI = @"http://myappredirect://";
    NSString *clientID = @"MY_CLIENT_ID";
    NSString *clientSecret = @"MY_CLIENT_SECRET";
    NSString *username = @"USERNAME";
    NSString *authURL = [NSString stringWithFormat:@"https://trakt.tv/oauth/authorize?response_type=code&client_id=%@&redirect_uri=%@&state=state&username=%@", clientID, redirectURI, username];

    NSURL *URL = [NSURL URLWithString:authURL];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
    [request setHTTPMethod:@"GET"];

    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

    [[UIApplication sharedApplication] openURL:URL];

    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                  ^(NSData *data, NSURLResponse *response, NSError *error) {

                                      if (error) {
                                          // Handle error...

                                      if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                          NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                          NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);

                                      NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                      NSLog(@"Response Body:\n%@\n", body);
    [task resume];

This opens Safari on my iPhone, loads the web page successfully with Trakt asking to authorise my account for my app. I tap 'Authorize' and then Safari loads a URL 'myappredirect//?code=a_really_long_string_of_characters", but with an error

Safari cannot open the page because the server cannot be found.

When I enter myappredirect:// in Safari, my app opens, so I'm wondering if the URL that Safari loads is incorrect as it's missing a semi-colon before the double //?

So I tried adding a UIWebView to my app and load the URL in there. It loads the URL but this time after I tap 'Authorize', it doesn't change the webpage. The UIWebView delegate webViewDidStartLoad does tell me that it loads a page after I tap 'Authorize', but nothing changes on-screen.

Method 2, using OAuth2Client:


    webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 300, 300)];
    webView.backgroundColor = [UIColor greenColor];
    webView.delegate = self;
    [self.view addSubview:webView];


-(void)webViewDidStartLoad:(UIWebView *)webView{

    NSString *redirectURI = @"http://myappredirect://";
    NSString *clientID = @"MY_CLIENT_ID";
    NSString *clientSecret = @"MY_CLIENT_SECRET";
    NSString *username = @"USERNAME";
    NSString *authURL = [NSString stringWithFormat:@"https://api-v2launch.trakt.tv/oauth/authorize?response_type=code&client_id=%@&redirect_uri=%@&state=state&username=%@", clientID, redirectURI, username];
    NSString *tokenURL = @"https://api-v2launch.trakt.tv";

    [[NXOAuth2AccountStore sharedStore] setClientID:clientID
                                   authorizationURL:[NSURL URLWithString:authURL]
                                           tokenURL:[NSURL URLWithString:tokenURL]
                                        redirectURL:[NSURL URLWithString:redirectURI]

    [[NXOAuth2AccountStore sharedStore] requestAccessToAccountWithType:@"Trakt"
                                   withPreparedAuthorizationURLHandler:^(NSURL *preparedURL){
                                       // Open a web view or similar
                                       [webView loadRequest:[NSURLRequest requestWithURL:preparedURL]];

    [super viewWillAppear:YES];

    [[NSNotificationCenter defaultCenter] addObserverForName:NXOAuth2AccountStoreAccountsDidChangeNotification
                                                      object:[NXOAuth2AccountStore sharedStore]
                                                  usingBlock:^(NSNotification *aNotification){
                                                      // Update your UI

    [[NSNotificationCenter defaultCenter] addObserverForName:NXOAuth2AccountStoreDidFailToRequestAccessNotification
                                                      object:[NXOAuth2AccountStore sharedStore]
                                                  usingBlock:^(NSNotification *aNotification){
                                                      NSError *error = [aNotification.userInfo objectForKey:NXOAuth2AccountStoreErrorKey];
                                                      // Do something with the error

Here, I'm not sure what the token URL is. Again, my UIWebView loads the URL perfectly but after I press 'Authorize', it doesn't change its webpage. The delegate method webViewDidStartLoad does tell me that it loads another page, but nothing changes on-screen. Also, neither of the NXOAuth2 notifications are sent.

I'm new to OAuth2 and would really appreciate any help anybody may have to offer. I apologise if this is a silly question, I'm really struggling on what to do, and confused as to why Safari won't open my app after I've authorised Trakt.


With the UIWebView you have interrupt the load in UIWebView delegate shouldStartLoadWithRequest when the url starts with your redirect url and get the parameter authorization code from url, concatenate with "get token url" and call [[NXOAuth2AccountStore sharedStore] handleRedirectURL:getTokenURL];

May not be the best way, but it works for me. :)

English isn’t my first language, so please excuse any mistakes. I hope this can help you.

OAuth 2.0 for Mobile & Desktop Apps, They can access Google APIs while the user is present at the app or when Note: See the redirect_uri parameter definition for details about the format of to Google's authorization server at https://accounts.google.com/o/oauth2/v2/auth . Determines whether the Google OAuth 2.0 endpoint returns an authorization code. OAuth 2.0 has been a supported authentication scheme in Insomnia for some time now but – if you are new to OAuth – can still be quite complicated. This post walks through an example using OAuth 2.0 to authenticate and create a repository on GitHub using the GitHub API .

NSString *redirectURI = @"myappredirect://";

instead of

NSString *redirectURI = @"http://myappredirect://";

Redirect URLs for Native Apps - OAuth 2.0 Simplified, The authorization endpoint normally redirects the user back to the client's registered redirect URL. Depending on the platform, native apps can  The OAuth 2.0 authorization code grant can be used in apps that are installed on a device to gain access to protected resources, such as web APIs. Using the Microsoft identity platform implementation of OAuth 2.0, you can add sign in and API access to your mobile and desktop apps.

Redirect URLs - OAuth 2.0 Simplified, After a user successfully authorizes an application, the authorization server will redirect the user back to the application with either an  In the menu on the Azure Active Directory blade, select App registrations. In the list of registered applications, select New application registration. Enter a name for your application, and leave Web app / API selected. For Sign-on URL, enter an appropriate value for your organization, such as https://login.windows.net. Select Create.

Authenticating with OAuth2 — Support, Learn how to link an OAuth2 application with your account, then use it to act on Uploading via the API is allowed, as well as fetching data about a single We will redirect back to the Redirect URI with error and error_description URL params. This might be desirable if you want to maintain state but can't store it in the  If the user has not previously authorized the app, then the app launches the OAuth 2.0 flow. Two buttons that allow the user to either sign out of the app or to revoke access previously granted to the app.

Redirect Users After Login Authentication, To return users to whitelisted callback URLs, it is necessary for your application to know how to continue the user on their journey. There are two methods for doing  But when instead trying to redirect to the redirect_uri, the access_token field in postman is blank. I have tried setting both access_token and accessToken as query parameters, but no luck. So the questions are: 1: Why is the redirect_uri passed in to the resource 2: Which parameters should be passed back to the redirect_uri? 👍

Authorizing OAuth Apps, GitHub's OAuth implementation supports the standard authorization code grant type. Users are redirected back to your site by GitHub; Your app accesses the API Note: When using the non-web application flow to create an OAuth2 token,​  It's possible to use the WebAuthenticator API with any web back end service. To use it with an ASP.NET core app, first you need to configure the web app with the following steps: Setup your desired external social authentication providers in an ASP.NET Core web app.

  • How to get the parameter authorization code from redirect url. Because after authorization it goes to redirect URL and its not return back to my app. please suggest me
  • UIWebView . and WebView is not supported for Redirect_url
  • I ended up making my own version of NXOAuth2 and this was part of the solution. I forgot to close this question but since you've answered it with the solution, I've marked it as the solution. Thanks!
  • @Murilo Alborghette How to get the parameter authorization code from redirect url. Because after authorization it goes to redirect URL and its not return back to my app. please suggest me
  • Thanks for your answer. I tried this and the Trakt page loads but says 'OAuth Error, the redirect uri included is not valid'. On the Trakt API page on my desktop, I can set the URI but I cannot enter it without 'http://'. So I think http:// is necessary?
  • If API requires http:// to be URL scheme used in redirect uri, then it is not possible to be redirected from safari back to your app. Every app can be registered to open some URL schemes - for http:// its Safari.
  • That's strange, every time I try to enter it without http:// on Trakt it says 'Must be an absolute uri.'. How would I handle the user tapping 'Authorize'?
  • It would seem, that Trakt API does not support authorization in mobile app via external browser. However, OAuth2Client you are using has other options of authorizing user. If i were you, I would take closer look at those
  • I'm not sure which method to use, I tried the requestAccessToAccountWithType:@"Trakt" withPreparedAuthorizationURLHandler: but that opens it up in a UIWebView, and then I don't know how to handle the response. I also tried the method with username:password: but that also does not work. :S