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.
It is a good practice to generate an "internal" token with more capabilities (for example, allowing the owner to create or delete files in the Data Management service) that will only be used by the server, and a "public" token with fewer capabilities that can be safely shared with the client-side logic.
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 { AuthenticationClient, ResponseType } = require('@aps_sdk/authentication');
const { DataManagementClient } = require('@aps_sdk/data-management');
const { APS_CLIENT_ID, APS_CLIENT_SECRET, APS_CALLBACK_URL, INTERNAL_TOKEN_SCOPES, PUBLIC_TOKEN_SCOPES } = require('../config.js');
const authenticationClient = new AuthenticationClient();
const dataManagementClient = new DataManagementClient();
const service = module.exports = {};
service.getAuthorizationUrl = () => authenticationClient.authorize(APS_CLIENT_ID, ResponseType.Code, APS_CALLBACK_URL, INTERNAL_TOKEN_SCOPES);
service.authCallbackMiddleware = async (req, res, next) => {
const internalCredentials = await authenticationClient.getThreeLeggedToken(APS_CLIENT_ID, req.query.code, APS_CALLBACK_URL, {
clientSecret: APS_CLIENT_SECRET
});
const publicCredentials = await authenticationClient.refreshToken(internalCredentials.refresh_token, APS_CLIENT_ID, {
clientSecret: APS_CLIENT_SECRET,
scopes: PUBLIC_TOKEN_SCOPES
});
req.session.public_token = publicCredentials.access_token;
req.session.internal_token = internalCredentials.access_token;
req.session.refresh_token = publicCredentials.refresh_token;
req.session.expires_at = Date.now() + internalCredentials.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 internalCredentials = await authenticationClient.refreshToken(refresh_token, APS_CLIENT_ID, {
clientSecret: APS_CLIENT_SECRET,
scopes: INTERNAL_TOKEN_SCOPES
});
const publicCredentials = await authenticationClient.refreshToken(internalCredentials.refresh_token, APS_CLIENT_ID, {
clientSecret: APS_CLIENT_SECRET,
scopes: PUBLIC_TOKEN_SCOPES
});
req.session.public_token = publicCredentials.access_token;
req.session.internal_token = internalCredentials.access_token;
req.session.refresh_token = publicCredentials.refresh_token;
req.session.expires_at = Date.now() + internalCredentials.expires_in * 1000;
}
req.internalOAuthToken = {
access_token: req.session.internal_token,
expires_in: Math.round((req.session.expires_at - Date.now()) / 1000),
};
req.publicOAuthToken = {
access_token: req.session.public_token,
expires_in: Math.round((req.session.expires_at - Date.now()) / 1000),
};
next();
};
service.getUserProfile = async (accessToken) => {
const resp = await authenticationClient.getUserInfo(accessToken);
return resp;
};
The code provides a couple of helper functions:
- the
getAuthorizationUrl
function generates a URL for our users to be redirected to when initiating the 3-legged authentication workflow - the
authCallbackMiddleware
function can be used as an Express.js middleware when the user logs in successfully and is redirected back to our application - the
authRefreshMiddleware
function is then used as an Express.js middleware for all requests that will need to make use of the APS access tokens - the
getUserProfile
function 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 Autodesk.Authentication.Model;
using System.Collections.Generic;
public class Tokens
{
public string InternalToken;
public string PublicToken;
public string RefreshToken;
public DateTime ExpiresAt;
}
public partial class APS
{
private readonly string _clientId;
private readonly string _clientSecret;
private readonly string _callbackUri;
private readonly List<Scopes> InternalTokenScopes = [Scopes.DataRead, Scopes.ViewablesRead];
private readonly List<Scopes> PublicTokenScopes = [Scopes.ViewablesRead];
public APS(string clientId, string clientSecret, string callbackUri)
{
_clientId = clientId;
_clientSecret = clientSecret;
_callbackUri = callbackUri;
}
}
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()
{
var authenticationClient = new AuthenticationClient();
return authenticationClient.Authorize(_clientId, ResponseType.Code, _callbackUri, InternalTokenScopes);
}
public async Task<Tokens> GenerateTokens(string code)
{
var authenticationClient = new AuthenticationClient();
var internalAuth = await authenticationClient.GetThreeLeggedTokenAsync(_clientId, code, _callbackUri, clientSecret: _clientSecret);
var publicAuth = await authenticationClient.RefreshTokenAsync(internalAuth.RefreshToken, _clientId, clientSecret: _clientSecret, scopes: PublicTokenScopes);
return new Tokens
{
PublicToken = publicAuth.AccessToken,
InternalToken = internalAuth.AccessToken,
RefreshToken = publicAuth.RefreshToken,
ExpiresAt = DateTime.Now.ToUniversalTime().AddSeconds((double)internalAuth.ExpiresIn)
};
}
public async Task<Tokens> RefreshTokens(Tokens tokens)
{
var authenticationClient = new AuthenticationClient();
var internalAuth = await authenticationClient.RefreshTokenAsync(tokens.RefreshToken, _clientId, clientSecret: _clientSecret, scopes: InternalTokenScopes);
var publicAuth = await authenticationClient.RefreshTokenAsync(internalAuth.RefreshToken, _clientId, clientSecret: _clientSecret, scopes: PublicTokenScopes);
return new Tokens
{
PublicToken = publicAuth.AccessToken,
InternalToken = internalAuth.AccessToken,
RefreshToken = publicAuth.RefreshToken,
ExpiresAt = DateTime.Now.ToUniversalTime().AddSeconds((double)internalAuth.ExpiresIn)
};
}
public async Task<UserInfo> GetUserProfile(Tokens tokens)
{
var authenticationClient = new AuthenticationClient();
UserInfo userInfo = await authenticationClient.GetUserInfoAsync(tokens.InternalToken);
return userInfo;
}
}
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();
var clientID = Configuration["APS_CLIENT_ID"];
var clientSecret = Configuration["APS_CLIENT_SECRET"];
var callbackURL = Configuration["APS_CALLBACK_URL"];
if (string.IsNullOrEmpty(clientID) || string.IsNullOrEmpty(clientSecret) || string.IsNullOrEmpty(callbackURL))
{
throw new ApplicationException("Missing required environment variables APS_CLIENT_ID, APS_CLIENT_SECRET, or APS_CALLBACK_URL.");
}
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 Autodesk.Authentication.Model;
using System.Collections.Generic;
public class Tokens
{
public string InternalToken;
public string PublicToken;
public string RefreshToken;
public DateTime ExpiresAt;
}
public partial class APS
{
private readonly string _clientId;
private readonly string _clientSecret;
private readonly string _callbackUri;
private readonly List<Scopes> InternalTokenScopes = [Scopes.DataRead, Scopes.ViewablesRead];
private readonly List<Scopes> PublicTokenScopes = [Scopes.ViewablesRead];
public APS(string clientId, string clientSecret, string callbackUri)
{
_clientId = clientId;
_clientSecret = clientSecret;
_callbackUri = callbackUri;
}
}
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()
{
var authenticationClient = new AuthenticationClient();
return authenticationClient.Authorize(_clientId, ResponseType.Code, _callbackUri, InternalTokenScopes);
}
public async Task<Tokens> GenerateTokens(string code)
{
var authenticationClient = new AuthenticationClient();
var internalAuth = await authenticationClient.GetThreeLeggedTokenAsync(_clientId, code, _callbackUri, clientSecret: _clientSecret);
var publicAuth = await authenticationClient.RefreshTokenAsync(internalAuth.RefreshToken, _clientId, clientSecret: _clientSecret, scopes: PublicTokenScopes);
return new Tokens
{
PublicToken = publicAuth.AccessToken,
InternalToken = internalAuth.AccessToken,
RefreshToken = publicAuth.RefreshToken,
ExpiresAt = DateTime.Now.ToUniversalTime().AddSeconds((double)internalAuth.ExpiresIn)
};
}
public async Task<Tokens> RefreshTokens(Tokens tokens)
{
var authenticationClient = new AuthenticationClient();
var internalAuth = await authenticationClient.RefreshTokenAsync(tokens.RefreshToken, _clientId, clientSecret: _clientSecret, scopes: InternalTokenScopes);
var publicAuth = await authenticationClient.RefreshTokenAsync(internalAuth.RefreshToken, _clientId, clientSecret: _clientSecret, scopes: PublicTokenScopes);
return new Tokens
{
PublicToken = publicAuth.AccessToken,
InternalToken = internalAuth.AccessToken,
RefreshToken = publicAuth.RefreshToken,
ExpiresAt = DateTime.Now.ToUniversalTime().AddSeconds((double)internalAuth.ExpiresIn)
};
}
public async Task<UserInfo> GetUserProfile(Tokens tokens)
{
var authenticationClient = new AuthenticationClient();
UserInfo userInfo = await authenticationClient.GetUserInfoAsync(tokens.InternalToken);
return userInfo;
}
}
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();
var clientID = Configuration["APS_CLIENT_ID"];
var clientSecret = Configuration["APS_CLIENT_SECRET"];
var callbackURL = Configuration["APS_CALLBACK_URL"];
if (string.IsNullOrEmpty(clientID) || string.IsNullOrEmpty(clientSecret) || string.IsNullOrEmpty(callbackURL))
{
throw new ApplicationException("Missing required environment variables APS_CLIENT_ID, APS_CLIENT_SECRET, or APS_CALLBACK_URL.");
}
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/token', authRefreshMiddleware, function (req, res) {
res.json(req.publicOAuthToken);
});
router.get('/api/auth/profile', authRefreshMiddleware, async function (req, res, next) {
try {
const profile = await getUserProfile(req.internalOAuthToken.access_token);
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/login
will redirect the user to the Autodesk login pageGET /api/auth/callback
is 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/logout
will remove any cookie-based session data for the given user, effectively logging the user out of our applicationGET /api/auth/token
will generate a public access token that will later be used by the Viewer to load our designsGET /api/auth/profile
will 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;
[ApiController]
[Route("api/[controller]")]
public class AuthController : ControllerBase
{
private readonly APS _aps;
public AuthController(APS aps)
{
_aps = aps;
}
public static async Task<Tokens> PrepareTokens(HttpRequest request, HttpResponse response, APS aps)
{
if (!request.Cookies.ContainsKey("internal_token"))
{
return null;
}
var tokens = new Tokens
{
PublicToken = request.Cookies["public_token"],
InternalToken = request.Cookies["internal_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("public_token", tokens.PublicToken);
response.Cookies.Append("internal_token", tokens.InternalToken);
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("public_token");
Response.Cookies.Delete("internal_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("public_token", tokens.PublicToken);
Response.Cookies.Append("internal_token", tokens.InternalToken);
Response.Cookies.Append("refresh_token", tokens.RefreshToken);
Response.Cookies.Append("expires_at", tokens.ExpiresAt.ToString());
return Redirect("/");
}
[HttpGet("profile")]
public async Task<ActionResult> GetProfile()
{
var tokens = await PrepareTokens(Request, Response, _aps);
if (tokens == null)
{
return Unauthorized();
}
var profile = await _aps.GetUserProfile(tokens);
return Ok(new { name = profile.Name });
}
[HttpGet("token")]
public async Task<ActionResult> GetPublicToken()
{
var tokens = await PrepareTokens(Request, Response, _aps);
if (tokens == null)
{
return Unauthorized();
}
var expiresIn = Math.Floor((tokens.ExpiresAt - DateTime.Now.ToUniversalTime()).TotalSeconds);
return Ok(new { access_token = tokens.PublicToken, expires_in = expiresIn });
}
}
The controller handles several different endpoints:
GET /api/auth/login
will redirect the user to the Autodesk login pageGET /api/auth/callback
is 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/logout
will remove any cookie-based session data for the given user, effectively logging the user out of our applicationGET /api/auth/token
will generate a public access token that will later be used by the Viewer to load our designsGET /api/auth/profile
will 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;
[ApiController]
[Route("api/[controller]")]
public class AuthController : ControllerBase
{
private readonly APS _aps;
public AuthController(APS aps)
{
_aps = aps;
}
public static async Task<Tokens> PrepareTokens(HttpRequest request, HttpResponse response, APS aps)
{
if (!request.Cookies.ContainsKey("internal_token"))
{
return null;
}
var tokens = new Tokens
{
PublicToken = request.Cookies["public_token"],
InternalToken = request.Cookies["internal_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("public_token", tokens.PublicToken);
response.Cookies.Append("internal_token", tokens.InternalToken);
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("public_token");
Response.Cookies.Delete("internal_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("public_token", tokens.PublicToken);
Response.Cookies.Append("internal_token", tokens.InternalToken);
Response.Cookies.Append("refresh_token", tokens.RefreshToken);
Response.Cookies.Append("expires_at", tokens.ExpiresAt.ToString());
return Redirect("/");
}
[HttpGet("profile")]
public async Task<ActionResult> GetProfile()
{
var tokens = await PrepareTokens(Request, Response, _aps);
if (tokens == null)
{
return Unauthorized();
}
var profile = await _aps.GetUserProfile(tokens);
return Ok(new { name = profile.Name });
}
[HttpGet("token")]
public async Task<ActionResult> GetPublicToken()
{
var tokens = await PrepareTokens(Request, Response, _aps);
if (tokens == null)
{
return Unauthorized();
}
var expiresIn = Math.Floor((tokens.ExpiresAt - DateTime.Now.ToUniversalTime()).TotalSeconds);
return Ok(new { access_token = tokens.PublicToken, expires_in = expiresIn });
}
}
The controller handles several different endpoints:
GET /api/auth/login
will redirect the user to the Autodesk login pageGET /api/auth/callback
is 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/logout
will remove any cookie-based session data for the given user, effectively logging the user out of our applicationGET /api/auth/token
will generate a public access token that will later be used by the Viewer to load our designsGET /api/auth/profile
will 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.