XeroOauth2Controller.cs
Код: Выделить всё
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Newtonsoft.Json; // For JSON serialization and deserialization
using Xero.NetStandard.OAuth2.Config;
using Xero.NetStandard.OAuth2.Client;
using Xero.NetStandard.OAuth2.Token;
public class XeroOauth2Controller : Controller
{
private readonly ILogger _logger;
private readonly XeroConfiguration _xeroConfig;
public XeroOauth2Controller(ILogger logger, IOptions xeroConfig)
{
_logger = logger;
_xeroConfig = xeroConfig.Value;
}
// Initiates the login and redirects to Xero login page
public IActionResult Index()
{
var client = new XeroClient(_xeroConfig);
var loginUri = client.BuildLoginUri();
return Redirect(loginUri.ToString());
}
// Callback after Xero redirects back with the authorization code
public async Task Callback(string code, string state)
{
if (string.IsNullOrEmpty(code))
{
_logger.LogError("Authorization code not found in the callback request.");
return RedirectToAction("Error", "Home");
}
var client = new XeroClient(_xeroConfig);
try
{
// Exchange the authorization code for a full token (access + refresh tokens)
var xeroToken = (XeroOAuth2Token)await client.RequestAccessTokenAsync(code);
if(xeroToken == null)
{
_logger.LogError("Failed to retrieve the token");
return RedirectToAction("Error", "Home");
}
// Serialize the token and store it in cookies
var tokenJson = JsonConvert.SerializeObject(xeroToken);
Response.Cookies.Append("XeroToken", tokenJson, new CookieOptions
{
HttpOnly = true,
Secure = true
});
var cookieExists = Request.Cookies.ContainsKey("XeroToken");
_logger.LogInformation($"Cookie exists: {cookieExists}");
_logger.LogInformation("Access and refresh tokens stored successfully.");
return RedirectToAction("GetOrganizations", "Home");
}
catch (Exception ex)
{
_logger.LogError("Error occurred while requesting access token: " + ex.Message);
return RedirectToAction("Error", "Home");
}
}
// Refresh the access token using the refresh token
public async Task RefreshToken()
{
// Retrieve the serialized token from the cookie
var tokenJson = Request.Cookies["XeroToken"];
if (string.IsNullOrEmpty(tokenJson))
{
_logger.LogError("Xero token is missing or invalid.");
return RedirectToAction("Index", "XeroOauth2"); // Redirect to login if no token is found
}
// Deserialize the XeroOAuth2Token object
var xeroToken = JsonConvert.DeserializeObject(tokenJson);
var client = new XeroClient(_xeroConfig);
try
{
// Pass the entire token object to refresh the access token
var newToken = await client.RefreshAccessTokenAsync(xeroToken);
// Serialize and store the new token
var newTokenJson = JsonConvert.SerializeObject(newToken);
Response.Cookies.Append("XeroToken", newTokenJson, new CookieOptions
{
HttpOnly = true,
Secure = true
});
_logger.LogInformation("Access token refreshed successfully.");
return RedirectToAction("GetOrganizations", "Organizations");
}
catch (Exception ex)
{
_logger.LogError($"Error occurred while refreshing token: {ex.Message}");
return RedirectToAction("Error", "Home");
}
}
}
Код: Выделить всё
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using XeroOAuth2._0_V3_.Models;
namespace XeroOAuth2._0_V3_.Controllers
{
public class HomeController : Controller
{
private readonly ILogger _logger;
public HomeController(ILogger logger)
{
_logger = logger;
}
public IActionResult Index()
{
return View();
}
public IActionResult Privacy()
{
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
Код: Выделить всё
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Xero.NetStandard.OAuth2.Config;
using Xero.NetStandard.OAuth2.Api;
using Xero.NetStandard.OAuth2.Client;
using Xero.NetStandard.OAuth2.Token;
public class OrganizationsController : Controller
{
private readonly ILogger _logger;
private readonly XeroConfiguration _xeroConfig;
public OrganizationsController(ILogger logger, IOptions xeroConfig)
{
_logger = logger;
_xeroConfig = xeroConfig.Value;
}
// Fetch and display organizations
public async Task GetOrganizations()
{
// Retrieve the serialized token from the cookie
var tokenJson = Request.Cookies["XeroToken"];
if (string.IsNullOrEmpty(tokenJson))
{
_logger.LogError("Access token is missing. Redirecting to login.");
return RedirectToAction("Index", "XeroOauth2"); // Redirect to login if no access token is found
}
// Deserialize the XeroOAuth2Token object
var xeroToken = JsonConvert.DeserializeObject(tokenJson);
try
{
// Create an instance of AccountingApi to fetch organizations
var accountingApi = new AccountingApi();
// Get the organizations associated with the access token
var response = await accountingApi.GetOrganisationsAsync(xeroToken.AccessToken, xeroToken.Tenants[0].TenantId.ToString());
// Pass the organizations to the view
return View(response._Organisations);
}
catch (Exception ex)
{
_logger.LogError("Error occurred while fetching organizations: " + ex.Message);
return RedirectToAction("Error", "Home");
}
}
}
Код: Выделить всё
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.Extensions.Options;
using Xero.NetStandard.OAuth2.Config;
using Xero.NetStandard.OAuth2.Client;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
// Add configuration options from appsettings.json for Xero OAuth2
builder.Services.Configure(builder.Configuration.GetSection("XeroOAuth2"));
// Enable cookie authentication
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.LoginPath = "/XeroOauth2/Index";
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication(); // Add authentication middleware
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
Когда я запускаю его, он отлично входит в систему, но после этого он должен показать мне подробную информацию об организации. Он все еще показывает мне кнопку входа в систему. Я попытался изменить перенаправление в методе обратного вызова в XeroOauth2Controller.cs, но оно все равно приводит меня на ту же страницу: экран с кнопкой входа в систему или домашнюю страницу.
Экран, который я вижу после входа в систему:

Подробнее здесь: https://stackoverflow.com/questions/790 ... redirected