To make a call to a website that requires username, password, and a token-based authentication (like JWT), you'll typically follow these steps:
✅ 1. Login to the Website and Get a Token
You send a POST
request with username and password, and receive a token (commonly JWT) in return.
java
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;
import java.util.HashMap;
import java.util.Map;
public class AuthService {
private final RestTemplate restTemplate = new RestTemplate();
public String loginAndGetToken(String loginUrl, String username, String password) {
// Create the login request body
Map<String, String> loginRequest = new HashMap<>();
loginRequest.put("username", username);
loginRequest.put("password", password);
// Set headers
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
// Wrap body and headers into entity
HttpEntity<Map<String, String>> request = new HttpEntity<>(loginRequest, headers);
// Make the request
ResponseEntity<String> response = restTemplate.exchange(loginUrl, HttpMethod.POST, request, String.class);
// Extract token from response (simplified)
return extractTokenFromResponse(response.getBody());
}
private String extractTokenFromResponse(String responseBody) {
// Simplified: Use a JSON library like Jackson or Gson in real code
return "your-jwt-token";
}
}
✅ 2. Use the Token for Authenticated API Calls
Use the received token to access protected endpoints.
java
public class ApiService {
private final RestTemplate restTemplate = new RestTemplate();
public String callApiWithToken(String apiUrl, String token) {
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer " + token);
HttpEntity<String> request = new HttpEntity<>(headers);
ResponseEntity<String> response = restTemplate.exchange(apiUrl, HttpMethod.GET, request, String.class);
return response.getBody();
}
}
✅ 3. Putting It All Together
java
public class Application {
public static void main(String[] args) {
AuthService authService = new AuthService();
ApiService apiService = new ApiService();
String loginUrl = "https://example.com/api/login";
String username = "your-username";
String password = "your-password";
String token = authService.loginAndGetToken(loginUrl, username, password);
String apiUrl = "https://example.com/api/data";
String response = apiService.callApiWithToken(apiUrl, token);
System.out.println("API Response: " + response);
}
}
🔍 Explanation
- Login Request: A
POST
request is sent to the login URL with the user's credentials. - Token Extraction: The response is parsed to extract the authentication token.
- Authenticated API Call: The token is passed in the
Authorization
header using the Bearer
schema.