Authentication
In this step we're going to extend the server implementation so that it can authenticate itself to the APS platform, guide the user through a 3-legged OAuth workflow, and generate access tokens for various needs.
Access tokens
- Node.js & VSCode
- .NET & VSCode
- .NET & VS2022
Create an aps.js file under the services folder. This is where we will be implementing
all the APS logic that will be used in different areas of our server application. Let's start
by adding the following code to the file:
const { SdkManagerBuilder } = require('@aps_sdk/autodesk-sdkmanager');
const { AuthenticationClient, Scopes, ResponseType } = require('@aps_sdk/authentication');
const { APS_CLIENT_ID, APS_CLIENT_SECRET, APS_CALLBACK_URL } = require('../config.js');
const service = module.exports = {};
const sdk = SdkManagerBuilder.create().build();
const authenticationClient = new AuthenticationClient(sdk);
service.getAuthorizationUrl = () => authenticationClient.authorize(APS_CLIENT_ID, ResponseType.Code, APS_CALLBACK_URL, [
Scopes.DataRead,
Scopes.AccountRead,
Scopes.AccountWrite
]);
service.authCallbackMiddleware = async (req, res, next) => {
const credentials = await authenticationClient.getThreeLeggedToken(APS_CLIENT_ID, req.query.code, APS_CALLBACK_URL,{clientSecret:APS_CLIENT_SECRET});
req.session.token = credentials.access_token;
req.session.refresh_token = credentials.refresh_token;
req.session.expires_at = Date.now() + credentials.expires_in * 1000;
next();
};
service.authRefreshMiddleware = async (req, res, next) => {
const { refresh_token, expires_at } = req.session;
if (!refresh_token) {
res.status(401).end();
return;
}
if (expires_at < Date.now()) {
const credentials = await authenticationClient.getRefreshToken(APS_CLIENT_ID, refresh_token, {
clientSecret: APS_CLIENT_SECRET,
scopes: [
Scopes.DataRead,
Scopes.AccountRead,
Scopes.AccountWrite
]
});
req.session.token = credentials.access_token;
req.session.refresh_token = credentials.refresh_token;
req.session.expires_at = Date.now() + credentials.expires_in * 1000;
}
req.oAuthToken = {
access_token: req.session.token,
expires_in: Math.round((req.session.expires_at - Date.now()) / 1000)
};
next();
};
service.getUserProfile = async (token) => {
const resp = await authenticationClient.getUserInfo(token.access_token);
return resp;
};
The code provides a couple of helper functions:
- the
getAuthorizationUrlfunction generates a URL for our users to be redirected to when initiating the 3-legged authentication workflow - the
authCallbackMiddlewarefunction can be used as an Express.js middleware when the user logs in successfully and is redirected back to our application - the
authRefreshMiddlewarefunction is then used as an Express.js middleware for all requests that will need to make use of the APS access tokens - the
getUserProfilefunction returns additional details about the authenticated user based on an existing access token
Create an APS.cs file under the Models subfolder. This is where we will be implementing
the APS-specific logic that will be used in different areas of our server application. Let's
start by adding the following code to the file:
using System;
using System.Collections.Generic;
using Autodesk.SDKManager;
using Autodesk.Authentication.Model;
public class Tokens
{
public string? AccessToken;
public string? RefreshToken;
public DateTime ExpiresAt;
}
public partial class APS
{
private readonly string _clientId;
private readonly string _clientSecret;
private readonly string _callbackUri;
private SDKManager _SDKManager;
private readonly List<Scopes> TokenScopes = new List<Scopes> { Scopes.DataRead, Scopes.AccountRead, Scopes.AccountWrite };
public APS(string clientId, string clientSecret, string callbackUri)
{
_clientId = clientId;
_clientSecret = clientSecret;
_callbackUri = callbackUri;
_SDKManager = SdkManagerBuilder.Create().Build();
}
}
Notice that the APS class is declared as partial. We're going to extend it
in other *.cs files later. An APS singleton will then be provided to our server
through ASP.NET's dependency injection.
Next, let's create an APS.Auth.cs file under the Models subfolder with the following code:
using System;
using System.Threading.Tasks;
using Autodesk.Authentication;
using Autodesk.Authentication.Model;
public partial class APS
{
public string GetAuthorizationURL()
{
AuthenticationClient authenticationClient = new AuthenticationClient(_SDKManager);
return authenticationClient.Authorize(_clientId, ResponseType.Code, _callbackUri, TokenScopes);
}
public async Task<Tokens> GenerateTokens(string code)
{
AuthenticationClient authenticationClient = new AuthenticationClient(_SDKManager);
dynamic Token = await authenticationClient.GetThreeLeggedTokenAsync(_clientId,code,_callbackUri, _clientSecret);
return new Tokens
{
AccessToken = Token.AccessToken,
RefreshToken = Token.RefreshToken,
ExpiresAt = DateTime.Now.ToUniversalTime().AddSeconds(Token.ExpiresIn)
};
}
public async Task<Tokens> RefreshTokens(Tokens tokens)
{
AuthenticationClient authenticationClient = new AuthenticationClient(_SDKManager);
dynamic Token = await authenticationClient.RefreshTokenAsync(tokens.RefreshToken, _clientId, _clientSecret,TokenScopes);
return new Tokens
{
AccessToken = Token.AccessToken,
RefreshToken = Token.RefreshToken,
ExpiresAt = DateTime.Now.ToUniversalTime().AddSeconds(Token.ExpiresIn)
};
}
public async Task<dynamic> GetUserProfile(Tokens tokens)
{
AuthenticationClient authenticationClient = new AuthenticationClient(_SDKManager);
dynamic profile = await authenticationClient.GetUserInfoAsync(tokens.AccessToken);
return profile;
}
}
These helper methods will later be used in our server's controllers to handle various types of requests related to authentication, for example, redirecting the user to the Autodesk login page, processing the callback when the user gets redirected back to our application, or refreshing tokens that have expired.
Finally, let's update our Startup.cs file to make a singleton instance of the APS class
available to our server application:
using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers().AddNewtonsoftJson();
var clientID = Configuration["APS_CLIENT_ID"];
var clientSecret = Configuration["APS_CLIENT_SECRET"];
var callbackURL = Configuration["APS_CALLBACK_URL"];
var server_Session_Secret = Configuration["SERVER_SESSION_SECRET"];
if (string.IsNullOrEmpty(clientID) || string.IsNullOrEmpty(clientSecret) || string.IsNullOrEmpty(callbackURL) || string.IsNullOrEmpty(server_Session_Secret))
{
throw new ApplicationException("Missing required environment variables APS_CLIENT_ID, APS_CLIENT_SECRET,APS_CALLBACK_URL or SERVER_SESSION_SECRET");
}
services.AddSingleton(new APS(clientID, clientSecret, callbackURL));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
Create an APS.cs file under the Models subfolder. This is where we will be implementing
the APS-specific logic that will be used in different areas of our server application. Let's
start by adding the following code to the file:
using System;
using System.Collections.Generic;
using Autodesk.SDKManager;
using Autodesk.Authentication.Model;
public class Tokens
{
public string? AccessToken;
public string? RefreshToken;
public DateTime ExpiresAt;
}
public partial class APS
{
private readonly string _clientId;
private readonly string _clientSecret;
private readonly string _callbackUri;
private SDKManager _SDKManager;
private readonly List<Scopes> TokenScopes = new List<Scopes> { Scopes.DataRead, Scopes.AccountRead, Scopes.AccountWrite };
public APS(string clientId, string clientSecret, string callbackUri)
{
_clientId = clientId;
_clientSecret = clientSecret;
_callbackUri = callbackUri;
_SDKManager = SdkManagerBuilder.Create().Build();
}
}
Notice that the APS class is declared as partial. We're going to extend it
in other *.cs files later. An APS singleton will then be provided to our server
through ASP.NET's dependency injection.
Next, let's create an APS.Auth.cs file under the Models subfolder with the following code:
using System;
using System.Threading.Tasks;
using Autodesk.Authentication;
using Autodesk.Authentication.Model;
public partial class APS
{
public string GetAuthorizationURL()
{
AuthenticationClient authenticationClient = new AuthenticationClient(_SDKManager);
return authenticationClient.Authorize(_clientId, ResponseType.Code, _callbackUri, TokenScopes);
}
public async Task<Tokens> GenerateTokens(string code)
{
AuthenticationClient authenticationClient = new AuthenticationClient(_SDKManager);
dynamic Token = await authenticationClient.GetThreeLeggedTokenAsync(_clientId,code,_callbackUri, _clientSecret);
return new Tokens
{
AccessToken = Token.AccessToken,
RefreshToken = Token.RefreshToken,
ExpiresAt = DateTime.Now.ToUniversalTime().AddSeconds(Token.ExpiresIn)
};
}
public async Task<Tokens> RefreshTokens(Tokens tokens)
{
AuthenticationClient authenticationClient = new AuthenticationClient(_SDKManager);
dynamic Token = await authenticationClient.RefreshTokenAsync(tokens.RefreshToken, _clientId, _clientSecret,TokenScopes);
return new Tokens
{
AccessToken = Token.AccessToken,
RefreshToken = Token.RefreshToken,
ExpiresAt = DateTime.Now.ToUniversalTime().AddSeconds(Token.ExpiresIn)
};
}
public async Task<dynamic> GetUserProfile(Tokens tokens)
{
AuthenticationClient authenticationClient = new AuthenticationClient(_SDKManager);
dynamic profile = await authenticationClient.GetUserInfoAsync(tokens.AccessToken);
return profile;
}
}
These helper methods will later be used in our server's controllers to handle various types of requests related to authentication, for example, redirecting the user to the Autodesk login page, processing the callback when the user gets redirected back to our application, or refreshing tokens that have expired.
Finally, let's update our Startup.cs file to make a singleton instance of the APS class
available to our server application:
using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers().AddNewtonsoftJson();
var clientID = Configuration["APS_CLIENT_ID"];
var clientSecret = Configuration["APS_CLIENT_SECRET"];
var callbackURL = Configuration["APS_CALLBACK_URL"];
var server_Session_Secret = Configuration["SERVER_SESSION_SECRET"];
if (string.IsNullOrEmpty(clientID) || string.IsNullOrEmpty(clientSecret) || string.IsNullOrEmpty(callbackURL) || string.IsNullOrEmpty(server_Session_Secret))
{
throw new ApplicationException("Missing required environment variables APS_CLIENT_ID, APS_CLIENT_SECRET,APS_CALLBACK_URL or SERVER_SESSION_SECRET");
}
services.AddSingleton(new APS(clientID, clientSecret, callbackURL));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
Server endpoints
Now let's expose this functionality via a collection of endpoints in our server.
- Node.js & VSCode
- .NET & VSCode
- .NET & VS2022
Create an auth.js file under the routes subfolder with the following content:
const express = require('express');
const { getAuthorizationUrl, authCallbackMiddleware, authRefreshMiddleware, getUserProfile } = require('../services/aps.js');
let router = express.Router();
router.get('/api/auth/login', function (req, res) {
res.redirect(getAuthorizationUrl());
});
router.get('/api/auth/logout', function (req, res) {
req.session = null;
res.redirect('/');
});
router.get('/api/auth/callback', authCallbackMiddleware, function (req, res) {
res.redirect('/');
});
router.get('/api/auth/profile', authRefreshMiddleware, async function (req, res, next) {
try {
const profile = await getUserProfile(req.oAuthToken);
res.json({ name: `${profile.name}` });
} catch (err) {
next(err);
}
});
module.exports = router;
Here we implement a new Express.js router that
will handle all the authentication-related endpoints. Let's "mount" the router to our server
application by modifying server.js:
const express = require('express');
const session = require('cookie-session');
const { PORT, SERVER_SESSION_SECRET } = require('./config.js');
let app = express();
app.use(express.static('wwwroot'));
app.use(session({ secret: SERVER_SESSION_SECRET, maxAge: 24 * 60 * 60 * 1000 }));
app.use(require('./routes/auth.js'));
app.listen(PORT, () => console.log(`Server listening on port ${PORT}...`));
The router will now handle the following requests:
GET /api/auth/loginwill redirect the user to the Autodesk login pageGET /api/auth/callbackis the URL our user will be redirected to after logging in successfully, and it is where we're going to generate a new set of tokens for the userGET /api/auth/logoutwill remove any cookie-based session data for the given user, effectively logging the user out of our applicationGET /api/auth/profilewill return a simple JSON with additional information about the logged in user
Create an AuthController.cs file under the Controllers subfolder with the following content:
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
[ApiController]
[Route("api/[controller]")]
public class AuthController : ControllerBase
{
private readonly ILogger<AuthController> _logger;
private readonly APS _aps;
public AuthController(ILogger<AuthController> logger, APS aps)
{
_logger = logger;
_aps = aps;
}
public static async Task<Tokens> PrepareTokens(HttpRequest request, HttpResponse response, APS aps)
{
if (!request.Cookies.ContainsKey("access_token"))
{
return null;
}
var tokens = new Tokens
{
AccessToken = request.Cookies["access_token"],
RefreshToken = request.Cookies["refresh_token"],
ExpiresAt = DateTime.Parse(request.Cookies["expires_at"])
};
if (tokens.ExpiresAt < DateTime.Now.ToUniversalTime())
{
tokens = await aps.RefreshTokens(tokens);
response.Cookies.Append("access_token", tokens.AccessToken);
response.Cookies.Append("refresh_token", tokens.RefreshToken);
response.Cookies.Append("expires_at", tokens.ExpiresAt.ToString());
}
return tokens;
}
[HttpGet("login")]
public ActionResult Login()
{
var redirectUri = _aps.GetAuthorizationURL();
return Redirect(redirectUri);
}
[HttpGet("logout")]
public ActionResult Logout()
{
Response.Cookies.Delete("access_token");
Response.Cookies.Delete("refresh_token");
Response.Cookies.Delete("expires_at");
return Redirect("/");
}
[HttpGet("callback")]
public async Task<ActionResult> Callback(string code)
{
var tokens = await _aps.GenerateTokens(code);
Response.Cookies.Append("access_token", tokens.AccessToken);
Response.Cookies.Append("refresh_token", tokens.RefreshToken);
Response.Cookies.Append("expires_at", tokens.ExpiresAt.ToString());
return Redirect("/");
}
[HttpGet("profile")]
public async Task<dynamic> GetProfile()
{
var tokens = await PrepareTokens(Request, Response, _aps);
if (tokens == null)
{
return Unauthorized();
}
dynamic profile = await _aps.GetUserProfile(tokens);
return new
{
name = profile.Name
};
}
}
The controller handles several different endpoints:
GET /api/auth/loginwill redirect the user to the Autodesk login pageGET /api/auth/callbackis the URL our user will be redirected to after logging in successfully, and it is where we're going to generate a new set of tokens for the userGET /api/auth/logoutwill remove any cookie-based session data for the given user, effectively logging the user out of our applicationGET /api/auth/profilewill return a simple JSON with additional information about the logged in user
Create an AuthController.cs file under the Controllers subfolder with the following content:
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
[ApiController]
[Route("api/[controller]")]
public class AuthController : ControllerBase
{
private readonly ILogger<AuthController> _logger;
private readonly APS _aps;
public AuthController(ILogger<AuthController> logger, APS aps)
{
_logger = logger;
_aps = aps;
}
public static async Task<Tokens> PrepareTokens(HttpRequest request, HttpResponse response, APS aps)
{
if (!request.Cookies.ContainsKey("access_token"))
{
return null;
}
var tokens = new Tokens
{
AccessToken = request.Cookies["access_token"],
RefreshToken = request.Cookies["refresh_token"],
ExpiresAt = DateTime.Parse(request.Cookies["expires_at"])
};
if (tokens.ExpiresAt < DateTime.Now.ToUniversalTime())
{
tokens = await aps.RefreshTokens(tokens);
response.Cookies.Append("access_token", tokens.AccessToken);
response.Cookies.Append("refresh_token", tokens.RefreshToken);
response.Cookies.Append("expires_at", tokens.ExpiresAt.ToString());
}
return tokens;
}
[HttpGet("login")]
public ActionResult Login()
{
var redirectUri = _aps.GetAuthorizationURL();
return Redirect(redirectUri);
}
[HttpGet("logout")]
public ActionResult Logout()
{
Response.Cookies.Delete("access_token");
Response.Cookies.Delete("refresh_token");
Response.Cookies.Delete("expires_at");
return Redirect("/");
}
[HttpGet("callback")]
public async Task<ActionResult> Callback(string code)
{
var tokens = await _aps.GenerateTokens(code);
Response.Cookies.Append("access_token", tokens.AccessToken);
Response.Cookies.Append("refresh_token", tokens.RefreshToken);
Response.Cookies.Append("expires_at", tokens.ExpiresAt.ToString());
return Redirect("/");
}
[HttpGet("profile")]
public async Task<dynamic> GetProfile()
{
var tokens = await PrepareTokens(Request, Response, _aps);
if (tokens == null)
{
return Unauthorized();
}
dynamic profile = await _aps.GetUserProfile(tokens);
return new
{
name = profile.Name
};
}
}
The controller handles several different endpoints:
GET /api/auth/loginwill redirect the user to the Autodesk login pageGET /api/auth/callbackis the URL our user will be redirected to after logging in successfully, and it is where we're going to generate a new set of tokens for the userGET /api/auth/logoutwill remove any cookie-based session data for the given user, effectively logging the user out of our applicationGET /api/auth/profilewill return a simple JSON with additional information about the logged in user
Try it out
- Node.js & VSCode
- .NET & VSCode
- .NET & VS2022
If the application is still running, restart it (for example, using Run > Restart Debugging,
or by clicking the green restart icon), otherwise start it again (using Run > Start Debugging,
or by pressing F5).
When you navigate to http://localhost:8080/api/auth/login
in the browser, you should be redirected to Autodesk login page, and after logging in,
you should be redirected back to your application, for now simply showing Cannot GET /.
This is expected as we haven't implemented the GET / endpoint yet. However, if you use
browser dev tools and explore the cookies stored by your browser for the localhost origin,
you'll notice that the application is already storing the authentication data there.

If the application is still running, restart it (for example, using Run > Restart Debugging,
or by clicking the green restart icon), otherwise start it again (using Run > Start Debugging,
or by pressing F5).
When you navigate to http://localhost:8080/api/auth/login
in the browser, you should be redirected to Autodesk login page, and after logging in, you should
be redirected back to your application, for now simply returning 404. This is expected as we haven't
implemented the GET / endpoint yet. However, if you use browser dev tools and explore the cookies
stored by your browser for the localhost origin, you'll notice that the application is already
storing the authentication data there.

If the application is still running, restart it (for example, using Debug > Restart,
or by pressing Ctrl+Shift+F5), otherwise start it again (using Debug > Start Debugging,
or by pressing F5).
When you navigate to http://localhost:8080/api/auth/login
in the browser, you should be redirected to Autodesk login page, and after logging in, you should
be redirected back to your application, for now simply returning 404. This is expected as we haven't
implemented the GET / endpoint yet. However, if you use browser dev tools and explore the cookies
stored by your browser for the localhost origin, you'll notice that the application is already
storing the authentication data there.
