-
Notifications
You must be signed in to change notification settings - Fork 0
Authentication
RubenJ01 edited this page Jan 25, 2026
·
3 revisions
Some endpoints need authentication (like track.scrobble). Here's how to set it up:
First, create a client with your API key and secret, then request a token:
String apiKey = "your-api-key";
String apiSecret = "your-api-secret";
LastFmClient client = LastFmClient.builder()
.apiKey(apiKey)
.apiSecret(apiSecret)
.build();
String token = client.auth().getToken();Generate the authorization URL and visit it in your browser to grant permission:
String authUrl = client.auth().getAuthorizationUrl(apiKey, token);
System.out.println("Visit this URL to authorize: " + authUrl);After granting permission, you'll see a success page. Tokens expire after 60 minutes and can only be used once.
Once the token is authorized, exchange it for a session key:
Session session = client.auth().getSession(token);
String sessionKey = session.key();Session keys don't expire, so save yours and reuse it for all future requests. You only need to do the token thing once.
Now you can create an authenticated client:
LastFmClient authenticatedClient = LastFmClient.builder()
.apiKey(apiKey)
.apiSecret(apiSecret)
.sessionKey(sessionKey)
.build();This client can now use authenticated endpoints like track.scrobble, track.love, etc.
The builder pattern also supports custom configuration:
import java.net.http.HttpClient;
import java.time.Duration;
import com.fasterxml.jackson.databind.ObjectMapper;
HttpClient customHttpClient = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(10))
.build();
ObjectMapper customMapper = new ObjectMapper();
LastFmClient client = LastFmClient.builder()
.apiKey(apiKey)
.apiSecret(apiSecret)
.sessionKey(sessionKey)
.httpClient(customHttpClient)
.objectMapper(customMapper)
.baseUrl("https://ws.audioscrobbler.com/2.0/")
.userAgent("my-app/1.0")
.build();