Mobile

If you want to add Yammer authentication and functionality to your smartphone and tablet apps, the easiest way is to use the iOS and Windows Phone SDKs.

 

iOS

The iOS SDK enables you to perform Yammer authentication to obtain an OAuth 2 token and then read/write to the Yammer REST API using this token. The SDK and a sample app using the SDK are available at: https://github.com/yammer/ios-oauth-demo.

Setup

Register Custom Redirect URI

The first step is to register a new Yammer app that represents your iOS app. During registration, set the Redirect URI to a custom URI Scheme i.e. AppName://your.custom.uri. Make sure the Scheme name (in this case AppName) is unique to your company and iOS app. Here’s an example for an iOS app named Move to Locker :

LoginWithYammer

Specify URL Scheme

During the login process, users will be directed to the mobile Safari web browser to complete the OAuth handshake. In order for the browser to be able to switch back to your iOS app after the handshake is done, the custom URL Scheme from above should be registered in the iOS application.

Here’s how you do that: In the XCode Project Navigator of your iOS app, expand the Supporting Files group and open your app’s plist file. Add a new row by going to the menu and clicking Editor > Add Item. Select URL Types. Expand the URL Types key, expand Item 0, and add a new item: URL Schemes. For the Move to Locker app, this looks like:

URLScheme

Configure Yammer OAuth service

At this point you can either add the OAuthSDK folder ( https://github.com/yammer/ios-oauth-demo/tree/master/OAuthSDK ) into your iOS app or use the code from the SDK and adapt it to your folder structure. If you have added the folder, you will be using the YMConstants.m file in your app.

To configure the Yammer OAuth service, open YMConstants.m and

1) Change YAMMER_AUTH_REDIRECT_URI to point to the Redirect URI from above. In our example: movetolocker://a.custom.uri

2) Change YAMMER_APP_CLIENT_ID and YAMMER_APP_CLIENT_SECRET to the values you obtained when registering your app above.

Initiate User Login

Typically, a “Login with Yammer” button on your app’s login view will initiate OAuth 2 based user authentication.

LoginWithYammer

Look at the “login” method in YMSampleHomeViewController.m to see how to initiate the OAuth login.

- (IBAction)login:(id)sender
{
    [[YMLoginController sharedInstance] startLogin];
}

The “startLogin” method in YMLoginController.m launches the iOS Safari web browser to bring up the OAuth login page where the user enters their Yammer credentials. After they enter their credentials, they are presented with an app authorization page for your iOS app with an “Allow” button.

- (void)startLogin
{
    NSString *stateParam = [self uniqueIdentifier];
    [[PDKeychainBindings sharedKeychainBindings] setObject:stateParam forKey:YAMMER_KEYCHAIN_STATE_KEY];

    NSDictionary *params = @{@"client_id": YAMMER_APP_CLIENT_ID,
                             @"redirect_uri": YAMMER_AUTH_REDIRECT_URI,
                             @"state": stateParam};

    NSString *query = AFQueryStringFromParametersWithEncoding(params, NSUTF8StringEncoding);
    NSString *urlString = [NSString stringWithFormat:@"%@/dialog/oauth?%@", YAMMER_BASE_URL, query];

    // Yammer SDK: This will launch mobile (iOS) Safari and begin the two-step login process.
    // The app delegate will intercept the callback from the login page.  See app delegate for method call.
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
}

Handle Redirect URI

Once the user authorizes your iOS app by clicking on the “Allow” button, the browser redirects to the custom URL that you specified above. In order for the user to re-enter your app functionality, your app delegate should handle this redirect.

For details on handling the redirect, open the sample app’s YMAppDelegate.m file and look at the following method:

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {

    // If we arrive here it means the login was successful, so now let's get the authToken to be used on all subsequent requests
-[YMLoginController handleLoginRedirectFromUrl:sourceApplication:]
    if ([[YMLoginController sharedInstance] handleLoginRedirectFromUrl:url sourceApplication:sourceApplication])
        return YES;

    // URL was not a match, or came from an application other than Safari
    return NO;
}

Note: Once the server sees that a user has clicked the Allow button, future login requests do not display the page with the Allow button. This is a one time occurance for each unique user/iOS app combination. Subsequent login attempts will return directly to the iOS app without the Allow page. You can manually Revoke Access to your app by going to https://www.yammer.com/account/applications.

Obtain User Auth Token

The “handleLoginRedirectFromUrl” method in YMLoginController.m, called on handling the redirect, runs a few checks and then calls a method to obtain a user auth token from Yammer. The auth token is stored in the keychain. All subsequent calls to the Yammer API use this authToken as the key into the system. Here’s the method in YMLoginController.m for obtaining the auth token.

- (void)obtainAuthTokenForCode:(NSString *)code
{
    // The YMHTTPClient uses a "baseUrl" with paths appended.  The baseUrl looks like "https://www.mydomain.com"
    NSURL *baseURL = [NSURL URLWithString: YAMMER_BASE_URL];

    // Query params
    NSDictionary *params =
            @{@"client_id" : YAMMER_APP_CLIENT_ID,
            @"client_secret" : YAMMER_APP_CLIENT_SECRET,
            @"code" : code};

    // Yammer SDK: Note that once we have the authToken, we use a different constructor to create the client:
    //- (id)initWithBaseURL:(NSURL *)baseURL authToken:(NSString *)authToken.
    // But we don't have the authToken yet, so we use this:
    YMHTTPClient *client = [[YMHTTPClient alloc] initWithBaseURL:baseURL];

    __weak YMLoginController* weakSelf = self;

    [client postPath:@"/oauth2/access_token.json"
          parameters:params
             success:^(id responseObject) {

                 NSDictionary *jsonDict = (NSDictionary *) responseObject;
                 NSDictionary *access_token = jsonDict[@"access_token"];
                 NSString *authToken = access_token[@"token"];

                 // For debugging purposes only
                 NSLog(@"Yammer Login JSON: %@", responseObject);
                 NSLog(@"authToken: %@", authToken);

                 // Save the authToken in the KeyChain
                 [weakSelf storeAuthTokenInKeychain:authToken];

                 [self.delegate loginController:self didCompleteWithAuthToken:authToken];
             }
             failure:^(NSInteger statusCode, NSError *error) {
                 NSMutableDictionary *userInfo = [@{NSLocalizedDescriptionKey: @"Unable to retrieve authentication token from cod                                                                                                                e"} mutableCopy];
                 if (error) {
                     userInfo[NSUnderlyingErrorKey] = error;
                     userInfo[NSLocalizedFailureReasonErrorKey] = [error localizedDescription];
                 }

                 [NSError errorWithDomain:YMYammerSDKErrorDomain code:YMYammerSDKLoginObtainAuthTokenError userInfo:userInfo];
                 [self.delegate loginController:self didFailWithError:error];
             }
     ];
}

Note: The Safari browser in iOS will hold on to the auth token in a cookie in the browser. So if you have already logged in during testing, and you’re trying to test the full login workflow again with the login dialog, you will need to delete cookies from Safari first. You can do this by going to the iOS settings app, selecting Safari and then Clear Cookies and Data. You will also need to delete the authToken from the keychain. There is a button on the YMSampleHomeViewController view that calls the deleteToken method so you can test this.

Make a Yammer REST API Call

The “attemptYammerApiCall” method in YMSampleHomeViewController.m shows what you would typically do in your app to access the Yammer API. FIrst the code determines if the auth token is already available in the keychain. If it is, it makes the API call using the auth token. If not, it initiates the login process to obtain the token.

- (IBAction)attemptYammerApiCall:(id)sender
{
    // Get the authToken if it exists
    NSString *authToken = [[YMLoginController sharedInstance] storedAuthToken];

    // If the authToken exists, then attempt the sample API call.
    if (authToken) {

        NSLog(@"authToken: %@", authToken);
        [self makeSampleAPICall: authToken];

    } else {
        self.attemptingSampleAPICall = YES;

        // If no auth token is found, go to step one of the login flow.
        // The setPostLoginProcessDelegate is one possible way do something after login.  In this case, we set that delegate
        // to self so that when the login controller is done logging in successfully, the processAfterLogin method
        // is called in this class.  Usually in an application that post-login process will just be an
        // app home page or something similar, so this dynamic delegate is not really necessary, but provides some
        // added flexibility in routing the app to a delegate after login.
        [[YMLoginController sharedInstance] setDelegate:self];
        [[YMLoginController sharedInstance] startLogin];
    }
}

 

Windows Phone 8

The Windows Phone 8 SDK provides you with the code necessary to integrate Yammer functionality into Windows Phone apps. It enables the following:

1. Allows users to do an OAuth 2 login to the Yammer network using the IE browser

2. Obtains an authToken and stores it securely to the Isolated Storage

3. Uses that authToken to make all subsequent calls to the Yammer API

In order to provide this functionality, some setup must be done.

Setup

The SDK is available at https://github.com/yammer/windows-phone-oauth-sdk-demo. It consists of two projects:

Yammer.OAuthSDK - is a Windows Phone 8 class library project that contains helper methods to help you handle the OAuth login and authorization process, as well as giving a headstart of how to call an API once we have a token.

OAuthWPDemo - is an actual Windows Phone 8 application that demonstrates how to setup and use these helper classes in an App.

To setup your own working app:

Step 1) Register a new Yammer app that represents your Windows Phone app.

Step 2) As part of the application setup in step 1, set the Redirect URI to a custom URI scheme. This must be unique to your WP8 app. Here’s an example: wp8oauthdemo://something. Make sure the scheme name (in this case “wp8oauthdemo”) is unique to your company and WP8 app.

Step 3) You will need to create an instance of Yammer.OAuthSDK.Model.OAuthClientInfo with your app’s values, obtained when registering your app above. The best place to do this is on the Application resource dictionary in your App.xaml file e.g.

<!--Application Resources-->
<Application.Resources>
  <!- ... ->
  <model:OAuthClientInfo xmlns:model="clr-namespace:Yammer.OAuthSDK.Model;assembly=Yammer.OAuthSDK" x:Key="MyOAuthClientInfo"
      ClientId="XXXXXXXXXXXXXX" 
      ClientSecret="YYYYYYYYYYYYYYYYYYYY" 
      RedirectUri="wp8oauthdemo://something" />
</Application.Resources>

Note the creation of a Property getter to facilitate access to this object Application-wide in App.xaml.cs:

/// <summary>
/// Easy access to the OAuth Client information defined in the App resource dictionary.
/// </summary>
public OAuthClientInfo MyOAuthClientInfo
{
    get
    {
        return Resources["MyOAuthClientInfo"] as OAuthClientInfo;
    }
}

Step 4) During the login process, users will be directed to the mobile IE web browser. In order for the browser to be able to switch back to your WP app, the custom URL Scheme from step 2 must be registered in the WP application. Here’s how you do that:

To register for a URI association, you must edit WMAppManifest.xml using the XML (Text) Editor. In Solution Explorer, expand the Properties folder and right-click the WMAppManifest.xml file, and then click Open With. In the Open With window, select XML(Text) Editor, and then click OK.

In the Extensions element of the app manifest file, a URI association is specified with a Protocol element (note that the Extensions element must immediately follow the Tokens element). Your Extensions element should look like this:

<Extensions>
  <Protocol Name="wp8oauthdemo" NavUriFragment="encodedLaunchUri=%s" TaskID="_default" />
</Extensions>

Also make sure to override the default URI-mapper class with our OAuth URI handler in the InitializePhoneApplication() method in App.xaml.cs:

// Override the default URI-mapper class with our OAuth URI handler.
RootFrame.UriMapper = new OAuthResponseUriMapper(MyOAuthClientInfo.RedirectUri);

Initiate User Login

After that you should be ready to go. Take a look at how the method

OAuthUtils.LaunchSignIn(string clientId, string redirectUri)

is implemented and used in MainPage.xaml.cs::btnSignInWithYammer_Click. That’s the method that launches the IE browser and lets the user both authenticate, and Authorize the app.

Handle Redirect

After that take a look at

OAuthUtils.HandleApprove(string clientId,
            string clientSecret,
            string code, 
            string state,
            Action onSuccess, 
            Action onCSRF = null, 
            Action<AuthenticationResponse> onErrorResponse = null, 
            Action<Exception> onException = null)

which is used in MainPage.xaml.cs::OnNavigatedTo after a user has been redirected back from the Login/Authorization page.

Make a Yammer REST API Call

Finally, note the use of

OAuthUtils.GetJsonFromApi(Uri endpoint, 
            Action<string> onSuccess, 
            Action<AuthenticationResponse> onErrorResponse = null, 
            Action<Exception> onException = null)

in MainPage.xaml.cs::btnCallFollowingApi_Click to handle the simple dump of a json result of an API call after the user has been succesfully authenticated.

Note: Once the server sees that a user has clicked the Allow button, future login requests do not display the page with the Allow button. This is a one time occurance for each unique user/yammer-app combination. Subsequent login attempts will return directly to the WP8 app without the Allow page. You can manually Revoke Access to your app by going to https://www.yammer.com/account/applications.