DEV Community

Cover image for Building a Secure Autodesk Platform Services (APS) API App: Session Management and Middleware Configuration
chuongmep
chuongmep

Posted on

Building a Secure Autodesk Platform Services (APS) API App: Session Management and Middleware Configuration

Building a Secure Autodesk Platform Services (APS) API App: Session Management and Middleware Configuration

When building applications with Autodesk Platform Services (APS), secure and persistent authentication is crucial for ensuring a smooth user experience. One of the key components in any web application is proper session management. In this post, we'll walk through how to set up session management using express-session and cookie-session while building an APS API app.

What Is Autodesk Platform Services (APS)?

Autodesk Platform Services (APS) provides a cloud-based API platform that allows developers to integrate Autodesk tools into their applications. These APIs can be used for everything from model viewing to data exchange and file management, and they require proper authentication to ensure security.

When building an APS application, handling OAuth 2.0 authentication is a critical part of the process. This typically involves handling access tokens, refresh tokens, and user sessions. For this reason, you need to carefully manage how session data is stored and accessed.

Session Management in APS API Applications

In APS, after you authenticate a user and obtain an access token, you typically need to manage the session to maintain the user’s login state. Session management involves storing the authentication data securely and making it available across multiple requests. This is where express-session or cookie-session come into play.

Using cookie-session

cookie-session is a lightweight solution where the session data is stored directly in the browser's cookies. It's perfect for smaller-scale apps or scenarios where session data doesn’t need to be too large. Here's a basic setup:

const express = require('express');
const session = require('cookie-session');
const { PORT, SERVER_SESSION_SECRET } = require('./config.js');

let app = express();

// Serve static files
app.use(express.static('wwwroot'));

// Session configuration using cookie-session
app.use(session({
    secret: SERVER_SESSION_SECRET,           // A secret key to sign the cookie
    maxAge: 24 * 60 * 60 * 1000,             // Session expiration (1 day)
    httpOnly: true,                          // Cookie can't be accessed via JS
    secure: false,                           // Set to true if using HTTPS
}));

// Route handlers
app.use(require('./routes/auth.js'));
app.use(require('./routes/hubs.js'));

// Start the server
app.listen(PORT, () => console.log(`Server running on http://localhost:${PORT}`));
Enter fullscreen mode Exit fullscreen mode

With this setup, the session data (like refresh_token and user-specific data) will be stored in a cookie. The cookie will automatically be sent with every request, allowing you to retrieve and update session data without needing a database.

Using express-session for Larger Apps

While cookie-session is great for lightweight sessions, larger applications or those requiring more robust session handling might benefit from express-session. This session middleware stores session data server-side, allowing for more complex and secure storage solutions like Redis or a database.

Here’s how you can use express-session:

npm install express-session
Enter fullscreen mode Exit fullscreen mode

And configure it in your app:

const express = require('express');
const session = require('express-session');
const { PORT, SERVER_SESSION_SECRET } = require('./config.js');

let app = express();

// Serve static files
app.use(express.static('wwwroot'));

// Session middleware configuration using express-session
app.use(session({
    secret: SERVER_SESSION_SECRET,           // Secret key to sign the session cookie
    resave: false,                           // Don't save session if not modified
    saveUninitialized: true,                 // Create session even if it's empty
    cookie: {
        maxAge: 24 * 60 * 60 * 1000,         // Session expiration (1 day)
        httpOnly: true,                      // Cookie can't be accessed via JS
        secure: false,                       // Set to true if using HTTPS
    }
}));

// Route handlers
app.use(require('./routes/auth.js'));
app.use(require('./routes/hubs.js'));

// Start the server
app.listen(PORT, () => console.log(`Server running on http://localhost:${PORT}`));
Enter fullscreen mode Exit fullscreen mode

This configuration allows session data to be stored on the server (in memory, Redis, or another store), which is generally more secure for large applications. Unlike cookie-session, express-session doesn't store the actual session data in the cookie itself. Instead, it stores only a session ID, and the actual session data is kept server-side.

Authentication Flow and Session Management

After the user authenticates with APS via OAuth 2.0, you’ll typically handle tokens (access and refresh tokens) to maintain authentication. Here's an overview of the flow:

  1. Initial Authentication:

    • The user is redirected to Autodesk’s OAuth endpoint for authentication.
    • Once authenticated, APS returns an authorization code, which is exchanged for an access token and refresh token.
  2. Storing Tokens:

    • Once you obtain the access and refresh tokens, you store them in the session so that they can be used in subsequent requests.
    • This typically looks like this in your middleware:
     req.session.refresh_token = publicCredentials.refresh_token;
     req.session.access_token = publicCredentials.access_token;
    
  3. Token Refresh:

    • When the access token expires, you’ll need to use the refresh token to obtain a new access token. This involves checking the session for the stored refresh token and making a request to APS to refresh the session.
    • Example of refreshing a token:
     if (expires_at < Date.now()) {
         const internalCredentials = await authenticationClient.refreshToken(refresh_token, APS_CLIENT_ID, {
             clientSecret: APS_CLIENT_SECRET,
             scopes: INTERNAL_TOKEN_SCOPES
         });
         req.session.refresh_token = internalCredentials.refresh_token;
         req.session.access_token = internalCredentials.access_token;
     }
    
  4. Using Tokens in Requests:

    • After authenticating and refreshing tokens, you can use the session tokens to interact with the Autodesk APIs and access model data, manage files, and more.

Security Considerations

When working with session management, especially in authentication-heavy apps, security is crucial. Here are some best practices:

  • Use HTTPS: Always use HTTPS for production to encrypt data in transit, including session cookies.
  • Secure Cookies: Set the secure: true option for cookies if you’re using HTTPS, ensuring cookies are only sent over secure connections.
  • Session Expiry: Use appropriate session expiry times (via maxAge) to limit session duration and reduce the risk of stale sessions being hijacked.
  • Protect Against CSRF: Ensure your app implements CSRF protection to prevent malicious requests from being sent on behalf of the user.

Conclusion

Session management is a crucial part of building secure and efficient Autodesk Platform Services apps. Whether you’re using cookie-session for lightweight sessions or express-session for more robust storage solutions, managing tokens and session data effectively will ensure that your application works seamlessly while maintaining security.

With the correct session setup, you can easily manage user authentication, refresh tokens, and secure communication with Autodesk APIs—creating a smooth experience for your users.

Heroku

Amplify your impact where it matters most — building exceptional apps.

Leave the infrastructure headaches to us, while you focus on pushing boundaries, realizing your vision, and making a lasting impression on your users.

Get Started

Top comments (0)

👋 Kindness is contagious

Please show some love ❤️ or share a kind word in the comments if you found this useful!

Got it!