Coder Social home page Coder Social logo

afoauth2manager's Introduction

AFOAuth2Manager

AFOAuth2Manager is an extension for AFNetworking that simplifies the process of authenticating against an OAuth 2 provider.

Example Usage

Authentication

NSURL *baseURL = [NSURL URLWithString:@"http://example.com/"];
AFOAuth2Manager *OAuth2Manager =
            [[AFOAuth2Manager alloc] initWithBaseURL:baseURL
                                            clientID:kClientID
                                              secret:kClientSecret];

[OAuth2Manager authenticateUsingOAuthWithURLString:@"/oauth/token"
                                          username:@"username"
                                          password:@"password"
                                             scope:@"email"
                                           success:^(AFOAuthCredential *credential) {
                                               NSLog(@"Token: %@", credential.accessToken);
                                           }
                                           failure:^(NSError *error) {
                                               NSLog(@"Error: %@", error);
                                           }];

Authorizing Requests

AFHTTPSessionManager *manager =
    [[AFHTTPSessionManager alloc] initWithBaseURL:baseURL];

[manager.requestSerializer setAuthorizationHeaderFieldWithCredential:credential];

[manager GET:@"/path/to/protected/resource"
  parameters:nil
    progress:nil
     success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
         NSLog(@"Success: %@", responseObject);
     }
     failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
         NSLog(@"Failure: %@", error);
     }];

Storing Credentials

[AFOAuthCredential storeCredential:credential
                    withIdentifier:serviceProviderIdentifier];

Retrieving Credentials

AFOAuthCredential *credential =
        [AFOAuthCredential retrieveCredentialWithIdentifier:serviceProviderIdentifier];

Documentation

Documentation for all releases of AFOAuth2Manager are available on CocoaDocs.

License

AFOAuth2Manager is available under the MIT license. See the LICENSE file for more info.

afoauth2manager's People

Contributors

brendanjerwin avatar echoz avatar ejensen avatar fjaeger avatar gabrielrinaldi avatar gertig avatar hwaxxer avatar imanzarrabian avatar juanuribeo13 avatar kcharwood avatar ldrr avatar mattt avatar priteshshah1983 avatar seut avatar svenmuennich avatar westonplatter avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

afoauth2manager's Issues

Refresh token using NSTimer scheduled relative to TTL

A helpful addition to this could be (optionally) scheduling an NSTimer to refresh the access token a handful of seconds short of its expiry. We would have a good opportunity to schedule a non-repeating timer at the time that the credential is received and subsequently stored in the keychain.

This would give users a good first defense of their tokens expiring without incurring the overhead of refreshing the token on the "read path". It's obviously not foolproof as entering the background will obviate the timer firing, but ostensibly the user will need to handle this case anyway.

My hunch is that scheduling the timer on the run loop of the AFOAuth2Client would be fine, but we could present the user the option if it was really necessary.

This is separate of trying to catch 401 Unauthorized errors and refresh in the user's primary http client as this is rightly left to the user. I think the pushback presented here is completely valid and also exclusive of this idea.

Would be happy to draft up a pull request if there is interest/not-disgust.

AFNetworking 2.2.x compatibility

I realize there are multiple issues open for AFNetworking 2.0 compatibility but it seems that there isn't much activity or interest in merging those patches. Is there any specific reason that these patches aren't acceptable?

I am developing a library/podspec that depends on both AFNetworking and AFOAuth2Client and I am worried that end users of the library may experience AFNetworking version conflicts. As far as I know, it isn't possible for me to point to an "unofficial" version of AFOAuth2Client in my podspec, so for now I guess I am limited to AFNetworking 1.3.x until the official podspec is updated as well.

oAutoh to google

Does anyone have an example code of how to use AFOAuth2Manager to connect with Google?
Best

Use HTTP Basic Auth

The OAuth2 Spec strongly recommends AGAINST sending the client ID and secret in the body of the request for confidential clients (ie 2-legged auth, ie user/password and client-credential grant types, ie sections 4.3 and 4.4 of the spec)

Instead it recommends using HTTP basic auth as a bare minimum, implemented as (pseudocode):

Authorization: 'Basic' + Base64Encode(client_id + ':' + client_secret)

i.e. using the client_id as the username and the secret as the password

I checked that this worked with a default OAuth2 server (flask_oauthlib) as follows (in 'init'):

[self setDefaultHeader:@"Authorization" value:[NSString stringWithFormat:@"Basic %@", [[NSString stringWithFormat:@"%@:%@",clientID,secret] base64EncodedString]]];

With no extra server functionality this allowed auth with the server. We should consider this instead of sending the client_id and secret in the body for these kinds of grants.

Furthermore, the spec allows extension to many types of HTTP auth (http://tools.ietf.org/html/rfc6749#section-2.3.2). This would be a significant extension to support though.

Tag for version 2.2.1

When using cocoapods, the default version is 2.2.0 (even though the podspec version is 2.2.1) which unfortunately doesn't have changes included in this pull request: #100

the workaround if using cocoapods

pod 'AFOAuth2Manager', :git => "https://github.com/AFNetworking/AFOAuth2Manager.git"

Does not support authorization code grant type

From the latest version of the spec:

1.3.1. Authorization Code

The authorization code is obtained by using an authorization server
as an intermediary between the client and resource owner. Instead of
requesting authorization directly from the resource owner, the client
directs the resource owner to an authorization server (via its user-
agent as defined in [RFC2616]), which in turn directs the resource
owner back to the client with the authorization code.

Before directing the resource owner back to the client with the
authorization code, the authorization server authenticates the
resource owner and obtains authorization. Because the resource owner
only authenticates with the authorization server, the resource
owner's credentials are never shared with the client.

The authorization code provides a few important security benefits
such as the ability to authenticate the client, and the transmission
of the access token directly to the client without passing it through
the resource owner's user-agent, potentially exposing it to others,
including the resource owner.

The auth code grant type is used by all Google services, and would be awesome to have in this project.

If I don't get around to writing this addition, hopefully someone else will, and work on it!

Getting expires_in type as double value

It seems to me that for permanent expiration dates the following method is not setting the expiration date correctly ...

[credential setRefreshToken:refreshToken expiration:[NSDate dateWithTimeIntervalSinceNow:[[responseObject valueForKey:@"expires_in"] integerValue]]];

It's working when changing the integerValue call to doubleValue aka NSTimeInterval

client attempts to use the token for auth

Following [self setAuthorizationHeaderWithCredential:credential]; if the server invalidates the token, another call to authenticate will cause a failure from the server due to trying to use the credential token to auth.

In addition to adding Basic Auth, I think [self setAuthorizationHeaderWithCredential:credential]; should be removed (the docs clearly stated that the client should be used standalone and credentials transferred to a subclass of AFHTTPClient) OR [self setAuthorizationHeaderWithUsername:self.clientID password:self.secret]; should be called before every auth attempt.

I believe this did not cause issue previously as the clientID and secret were being sent in the form data of the auth request and the server was happy to accept this and ignore the authorization header field. Now I am using basic auth there is a conflict in the auth header being set.

Please publicly expose expiration on AFOAuthCredential

I'd like to be able to test how soon a credential will expire - not just if it has expired. This can easily be done if expiration is exposed publicly as a readonly property on AFOAuthCredential by adding

@Property (readonly, nonatomic) NSDate *expiration;

to the AFOAuthCredential interface in AFOAuth2Client.h.

Thanks,

M.

Memory leak in AFOAuth2Manager.m

Found via Facebook's Infer tool:

ios/thirdparty/AFOAuth2Manager/AFOAuth2Manager.m:374: error: MEMORY_LEAK

memory dynamically allocated to updateDictionary by call to dictionary at line 365, column 45 is not reachable after line 376, column 9

I tried reporting this via email but got no response

Parse error response according to standard

According to http://tools.ietf.org/html/rfc6749#section-5.2 in the case of error response "authorization server responds with an HTTP 400 (Bad Request) status code (unless specified otherwise)" ("server MAY return an HTTP 401 (Unauthorized) status code to indicate which HTTP authentication schemes are supported"), but in fact much of OAuth 2 servers responds with HTTP 200.

Please add parsing error also in failure block.

Problem with cocoapods 0.36 use_framework!

After update cocoapods to version 0.36 and use Framework. I found that AFOauth2Manager cannot import AFNetworking library to use in code. Xcode show error in AFOauth2Manager code where import AFNetworking code.

AFNetworking 3.0

Upon trying to update my project to use AFNetworking in CocoaPods I was greeted with:

'[!] Unable to satisfy the following requirements:

  • AFNetworking/NSURLConnection (~> 2.2) required by AFOAuth2Manager (2.1.0)
  • AFNetworking (~> 3.0) required by Podfile
  • AFNetworking (~> 2.2) required by AFOAuth2Manager (2.0.0)

Specs satisfying the AFNetworking/NSURLConnection (~> 2.2) dependency were found, but they required a higher minimum deployment target.'

Any plans to update it?

SystemConfiguration ad MobileCoreService missing

I'm not entirely sure what's going on but since one of the last updates I keep getting this during the build of AFOAuth2Client:

/Users/kain/src/myproj/Pods/AFNetworking/AFNetworking/AFHTTPClient.h:84:9: SystemConfiguration framework not found in project, or not included in precompiled header. Network reachability functionality will not be available.

/Users/kain/src/myproj/Pods/AFNetworking/AFNetworking/AFHTTPClient.h:89:9: MobileCoreServices framework not found in project, or not included in precompiled header. Automatic MIME type detection when uploading files in multipart requests will not be available.

Using latest cocoapods. http://d.pr/i/s5D1
I cannot figure out why, it happens during the AFHTTPClient.h import in AFOAuth2Client.

project pch

#ifdef __OBJC__
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#import <SystemConfiguration/SystemConfiguration.h>
#import <MobileCoreServices/MobileCoreServices.h>
...
#endif

Podfile

platform :ios, '6.0'
pod 'AFNetworking', git: 'git://github.com/AFNetworking/AFNetworking.git'
pod 'AFOAuth2Client', git: 'git://github.com/AFNetworking/AFOAuth2Client.git'
...

Is there any solution to use a base URL different between AFHTTPClient and AFOAuth2Client?

I'm currently writing an Imgur API based on AFNetworking and the AFOAuth2Client extension but I'm stuck on a point: the base URL differs between the OAuth access and the general access. For OAuth, the base URL is https://api.imgur.com/oauth2/ while it's https://api.imgur.com/3/ or https://imgur-apiv3.p.mashape.com/ for all the others request.

I didn't find how to handle this particularity, is there any solution without rewriting the library?

Support OAuth endpoints with no expiration

I'm hitting an OAuth endpoint that does not return an expiration. According to the oath draft, expirations are not required. The server I'm hitting only returns access_token and token_type.

I think this may be related to #66 and this commit: ff106e1

asserting that expires_in is defined contradicts the spec, no?

setAuthorizationHeaderFieldWithCredential: produces wrong header

(talking about the 3.0.0. branch here)

When using setAuthorizationHeaderFieldWithCredential: the library produces the following header field

Authorization = "Basic <wrong token here>";

To my knowledge, it should be
Authorization = "Bearer <token here>";

Also, the token in the 'Basic' case is NOT the access token stored in the AFOAuthCredential for given provider identifier.

When setting the Authorization header myself with the bearer keyword and my valid access token the call works.

"AFJSONRequestOperation.h" File Not Found

I am using cocoapods to install AFNetworking and your extension. When trying to compile I am getting the error that it can't find AFJsonRequestOperation.h. It is not clear where this dependency is or if another pod or extension should be installed. Can you advise?

It's not possible to retrieve secondary data from the authentication request

It's not uncommon to include additional data in a successful OAuth response. How come only the token is accessible in the success handler?

I realize this won't be easy to change for backwards compatibility reasons, but if a major version is coming up, it would be nice to have the block signatures (mostly) match all the standard AFNetworking ones by simply adding the AFHTTPRequestOperation *operation parameter in front. While the second argument to success would still be AFOAuthCredential, the developer can choose to extract extra parameters from the AFHTTPRequestOperation instance's responseObject property.

In the meantime, perhaps something could be done to support accessing the additional parameters?

Create method to return Authorization request

Create a method to return an authorization NSURLRequest given the path, response type (code or token), redirect URI, and scope. The returned NSURLRequest can be loaded into an UIWebView to commence authorization.

iOS 8 AFOAuthCredential store/retrieve

NSString *identifier = @"id.entif.ier";
[AFOAuthCredential storeCredential:credential withIdentifier:identifier];
AFOAuthCredential *credential = [AFOAuthCredential retrieveCredentialWithIdentifier:identifier];

iOS 7: credential != nil, iOS 8: credential == nil

Client credentials are included in the request body [NOT RECOMMENDED]

i've brought this up before:

Including the client credentials in the request body using the two
parameters is NOT RECOMMENDED, and SHOULD be limited to clients
unable to directly utilize the HTTP Basic authentication scheme (or
other password-based HTTP authentication schemes). The parameters
can only be transmitted in the request body and MUST NOT be included
in the request URI.

AFNetworking already supports basic auth headers so this shouldn't be hard to change.

Minor import paths issue

Hello,

In AFHTTPRequestSerializer+OAuth2.h and AFOAuth2Manager.h, I suggest you change

#import <AFNetworking/...h>

to:

#import <AFNetworking.h>

for increased compatibility. They currently result in an error if include paths aren't set to include system paths, which is important to many developers.

Thanks,
Drew

Add default expires_in lifetime parameter

According RFC 6749 expires_in parameter has status "RECOMMENDED":
If omitted, the authorization server SHOULD provide the expiration time via other means or document the default value.

Server may not transmit this parameter and we must provide it manually (by adding "defaultLifetime" property in AFOAuth2Client?)

AFOAuth1Token Expected a type error.

Adding AFOAuth1Client and AFOAuth2Client via CocoaPods. XCode generating Expected a type error on method:

+ (BOOL)storeCredential:(AFOAuth1Token *)credential
         withIdentifier:(NSString *)identifier

missing scope in usage exampe

In the ReadMe Usage example , the scope: is not stated as it should be
If I use authenticateUsingOAuthWithPath wo the scope parameter I get a warning
-authenticateUsingOAuthWithPath instance method not found

what's should be the scope value to be supplied ?

Simple Request for Documentation

Hey, i have encountered linker errors that I couldn't understand. I tried another library trying to get it work, i built the project without last step, which was adding Security.framework as a build dependency. (https://github.com/nxtbgthng/OAuth2Client)

I saw the same errors starting with sec... sec... then i realized it was a dependency for this project, too. Maybe you can add this to project's readme file? :)

Remove NSLogs

Is it please possible to remove the NSLogs in the AFOAuth2Mangaer.m ?
It logs the identifier of the keychain entry. This can be used by other apps to get the credentials.

Regards David

Make Bearer token usage more flexible

According http://tools.ietf.org/html/rfc6750#section-2 Bearer token may be used in three different ways:

  • as "Authorization Request Header Field"
  • as "Form-Encoded Body Parameter"
  • as "URI Query Parameter"

But in authenticateUsingOAuthWithPath:parameters:success:failure: hardcoded "Authorization Request Header Field" way.

Many services often use of the token in the query parameters ("Form-Encoded Body Parameter" or "URI Query Parameter"), and not in the query headers (e.g. VKontakte).

I think that better solution would be remove [self setAuthorizationHeaderWithCredential:credential]; and allow the developer to choose what he want to use. I think this is a more flexible solution.

This class will be super class for developers' purposes. As for me, I make subclass and override requestWithMethod:path:parameters: and multipartFormRequestWithMethod:path:parameters:constructingBodyWithBlock: methods to add "access_token" (bearer token) parameter.

Add support to refresh the token on expiry

Currently if the token expires - no check is made before to make sure the token is not expired.

It should check for expiration before making the request - if expired - use refresh token to get a fresh access token.

  • Note - I am not sure if this is how it should work. e.g. It could be left up to the developer to check before each call is made using AFOAuth2 but would be useful if this was handled by the framework.

AFJSONRequestOperation with POST Method give "signature_invalid"

I am using OAuth1 to authorise API and get access token.
When I call POST method it give me "oauth_problem=signature_invalid".

 NSMutableURLRequest *request = [self.myClient requestWithMethod:@"POST" path:apiURL parameters:jsonObj];
    NSDictionary *dict = @{ @"Content-Type":@"application/json",@"Accept":@"*/*"};

    [request setAllHTTPHeaderFields:dict];
    [request setHTTPShouldHandleCookies:true];

 AFJSONRequestOperation *jsonOperation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
     NSLog(@"Success: %@", JSON);

     } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
         NSLog(@"Header: %@",[request allHTTPHeaderFields]);
     NSLog(@"Error: %@", error);
     }];

     [jsonOperation start];

Please help me.

Update Podfile

AFNetworking is now 2.0 and it should be a good idea to update the Podfile.

Installation cookbook for newbies

I just don't get why is it so hard to write a usual Installation topic.

For anyone who just don't-know-what-the-hell-you-need-to-do-to-install-this-extension just add it to your Podfile as pod "AFOAuth2Manager" and make sure you have #import "AFOAuth2Manager.h" line in your header file

And please don't write it in documentation, newbies must squirm in agony and die!

Expiration not considered unless refresh token is present

I could be mistaken, but shouldn't the expiration be set regardless the refresh token - as long as expires_in is present?

It seems a recent change 7340904 / cfdf599 made use of the expiration conditional on a refresh token being present, which isn't always the case. See also #71. The expiration and refresh_token should be considered separately, not together in an all-or-nothing fashion,

When requesting a client_credentials grant, I receive an access token with a limited lifetime (e.g., 1 second for testing, below), but the AFOAuthCredential will always tell you the token has not expired.

{
    "access_token": "0c06a430f3f649837f412a011cf19a0e93bd41a075cc45876db601070d862ec4",
    "token_type": "bearer",
    "expires_in": 1,
    "scope": "public"
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.