I’ve successfully set up Spotify authentication in my MVC application and everything works fine on the initial login page. When users click the login button, they get redirected to Spotify, authorize my app, and I can fetch their playlists without any issues.
However, I’m running into a problem when users navigate to different pages in my application. Since each page load is a new HTTP request, I lose the access token and can’t make API calls to Spotify anymore.
What’s the best practice for storing and retrieving Spotify access tokens? Should I store them in browser cookies, server-side sessions, or pass them as URL parameters? I’m worried about security implications and want to make sure I’m following the right approach. Any recommendations would be really helpful.
In-memory caching with secure cookies works great for me in production. I keep tokens in a server-side cache temporarily and use encrypted session cookies to map users to their cached tokens. It’s faster than database storage and automatically cleans up stale tokens when the app restarts. For MVC apps, I use a custom action filter that checks token validity before each controller action. If the cached token’s missing or expired, the filter triggers the refresh flow or redirects to auth. This cuts database overhead while staying secure, though you’ll need to handle app restarts by detecting missing cache entries.
Yeah, server-side sessions are definitely the way to go for access tokens. I tried localStorage first because it seemed easier, but the security risks just aren’t worth it. Here’s what worked for me: store tokens in encrypted server-side sessions and only keep a session ID on the client through a secure HTTP-only cookie. This handles token refresh automatically - you can store both access and refresh tokens server-side and refresh them behind the scenes when needed. Just watch out for session timeouts - make sure they match how long users actually stay in your app. Also, set up proper error handling for expired/invalid tokens so you can smoothly redirect users back to auth if something breaks.
cookies work great for this - just set them to httponly and secure. i’ve been using this setup for months with zero problems. one heads up though: make sure you handle refresh tokens right, otherwise users get randomly logged out when access tokens expire.
Database storage with session management works great for this. I store access tokens in a table linked to user accounts, then use session cookies to connect browser sessions to the stored tokens. The big win is persistence - users stay logged in even after closing their browser, which feels way smoother. Just encrypt the tokens before storing and clean up expired entries. Pro tip I learned the hard way: always validate tokens before API calls since Spotify can revoke them anytime. This scales better than pure session storage and you get way more control over the token lifecycle.