Search code examples
c#oauth-2.0asp.net-core-mvcxero-api

Xero API Authentication - Building the Authentication App using C#, ASP.NET Core MVC


I am trying to develop software that will integrate into the Xero API, but for now I first need to build an authentication app. I am unsure where to start as I am new to this and also new to dealing with APIs in general.

On Github and on the Xero Developer Portal they give valuable information and help a lot, the only problem is that I do not know how to puzzle everything together, hence the inexperience. Can someone please provide me with guidance on how and where to start?

https://github.com/XeroAPI/Xero-NetStandard?tab=readme-ov-file#configuration

Here is a link with sample code they provide for the authentication and there is also more.

I am looking to use C#, ASP.NET Core MVC to connect the Application to log in with Xero and authenticate through Xero.

This is the authentication flow they provide as example. I just need guidance on where to start and so forth.

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Xero.NetStandard.OAuth2.Client;
using Xero.NetStandard.OAuth2.Config;
using Xero.NetStandard.OAuth2.Token;
using System;
using System.Net.Http;
using System.Threading.Tasks;
using Xero.NetStandard.OAuth2.Models;
using System.Collections.Generic;

namespace XeroNetStandardApp.Controllers
{
    public class XeroOauth2Controller : Controller
    { 
        private readonly ILogger<HomeController> _logger;
        private readonly IOptions<XeroConfiguration> XeroConfig;

        public XeroOauth2Controller(IOptions<XeroConfiguration> config, ILogger<HomeController> logger)
        {
            _logger = logger;
            this.XeroConfig = config;
        }

        public IActionResult Index()
        {
            XeroConfiguration xconfig = new XeroConfiguration();
            xconfig.ClientId = "yourClientId";
            xconfig.ClientSecret = "yourClientSecret";
            xconfig.CallbackUri = new Uri("https://localhost:5001");  // default for standard webapi template
            xconfig.Scope = "openid profile email offline_access files accounting.transactions accounting.contacts";

            var client = new XeroClient(xconfig);

            return Redirect(client.BuildLoginUri());
        }
    }
}

Step 2 of the code above:

XeroConfiguration xconfig = new XeroConfiguration(); 

xconfig.ClientId = "yourClientId";
xconfig.ClientSecret = "yourClientSecret";
xconfig.CallbackUri = new Uri("https://localhost:5001") //default for standard webapi template
xconfig.Scope = "openid profile email files accounting.transactions accounting.contacts offline_access";

var client = new XeroClient(xconfig);

// before getting the access token please check that the state matches
await client.RequestAccessTokenAsync(code);

// from here you will need to access your Xero Tenants
List<Tenant> tenants = await client.GetConnections();

// you will now have the tenant id and access token
foreach (Tenant tenant in tenants)
{
    // do something with your tenant and access token
    // client.AccessToken;
    // tenant.TenantId;
}

Configuration:

XeroConfiguration xconfig = new XeroConfiguration();
xconfig.ClientId = "yourClientId";
xconfig.ClientSecret = "yourClientSecret";
xconfig.CallbackUri = new Uri("https://localhost:5001"); //default for standard webapi template
xconfig.Scope = "openid profile email offline_access files accounting.transactions accounting.contacts";

var client = new XeroClient(xconfig);
{
  "id_token": "xxx.yyy.zz",
  "access_token": "xxx.yyy.zzz",
  "expires_in": 1800,
  "token_type": "Bearer",
  "refresh_token": "xxxxxxxxx",
  "scope": "email profile openid accounting.transactions offline_access"
}
xeroToken.AccessToken
xeroToken.RefreshToken
xeroToken.IdToken
xeroToken.TokenType
xeroToken.ExpiresAtUtc

Solution

  • The link you have shared is already contains how it works.

    If you want to get the access token from Xero, you should firstly create a test XeroOauth2Controller inside this controller, you could create a login redirect method and a callback method.

    Inside the callback method, it contains the method to store the token. Then you could use the stored access token to access the Xero API.

    More details, you could refer to below codes:

    1.Install the two package inside your project:

    Install-Package Xero.NetStandard.OAuth2
    Install-Package Xero.NetStandard.OAuth2Client
    
    1. Create the controller to auth with the Xero and get the code to get the access token.

    Code as below:

    public class XeroOauth2Controller : Controller
    {
        private readonly ILogger<HomeController> _logger;
      
        public XeroOauth2Controller( ILogger<HomeController> logger)
        {
            _logger = logger;
     
        }
    
        public IActionResult Index()
        {
            XeroConfiguration xconfig = new XeroConfiguration();
            xconfig.ClientId = "yourClientId";
            xconfig.ClientSecret = "yourClientSecret";
            xconfig.CallbackUri = new Uri("https://localhost:5001"); //default for standard webapi template
            xconfig.Scope = "openid profile email offline_access files accounting.transactions accounting.contacts";
    
            var client = new XeroClient(xconfig);
    
            return Redirect(client.BuildLoginUri());
        }
       
    
        /// <summary>
        /// Callback for authorization
        /// </summary>
        /// <param name="code">Returned code</param>
        /// <param name="state">Returned state</param>
        /// <returns>Redirect to organisations page</returns>
        public async Task<IActionResult> Callback(string code, string state)
        {
            XeroConfiguration xconfig = new XeroConfiguration();
            xconfig.ClientId = "yourClientId";
            xconfig.ClientSecret = "yourClientSecret";
            xconfig.CallbackUri = new Uri("https://localhost:5001"); //default for standard webapi template
            xconfig.Scope = "openid profile email offline_access files accounting.transactions accounting.contacts";
    
            var client = new XeroClient(xconfig);
            //here we could get the accesstoken 
            var xeroToken = (XeroOAuth2Token)await client.RequestAccessTokenAsync(code);
    
          
            // store the access token , you could modify it to store the token inside the Memroy Cache or else based on your requirement
            Response.Cookies.Append("X-Access-Token", xeroToken.AccessToken);
    
            // inside the redirect method you could use the API client to the get the info based on the cookie's accesstoken
            return RedirectToAction("Index", "Home");
        }
     
    }
    

    More details, you could refer to its standard sample.