Java
Authorization
1. Initialize the Smartcar object
Instantiate a Smartcar object in the constructor of the App component.
// src/main/java/Main.java
// TODO: Authorization Step 1: Launch Smartcar authentication dialog
String mode = "test";
AuthClient client = new AuthClient.Builder()
.mode(mode)
.build();
2. Launch Connect
A Server-Side Rendered application will redirect to Smartcar Connect to request access to a user’s vehicle. On Connect, the user logs in with the username and password for their vehicle’s connected services account and grants the application access to their vehicle.
To launch Connect, we need to redirect the user to the appropriate url. We can make use of the getAuthUrl
function in our Smartcar
object and pass the generated URL to our view in views/home.hbs
which will redirect to the URL on a button click. views/home.hbs
is a simple view that renders an HTML button.
// src/main/java/Main.java
get("/login", (req, res) -> {
// TODO: Authorization Step 2: Launch Smartcar authentication dialog
String[] scope = {"read_odometer"};
String link = client.authUrlBuilder(scope).build();
res.redirect(link);
return null;
});
3. Receive the authorization code
Once a user has authorized the application to access their vehicle, the user is redirected to the redirect_uri
with an authorization code
as a query parameter.
In the previous section, we had set our redirect_uri
as localhost:8000/exchange
. Now, our server can be set up as follows to receive the authorization code
.
// src/main/java/Main.java
get("/exchange", (req, res) -> {
// TODO: Authorization Step 3: Handle Smartcar response
String code = req.queryMap("code").value();
System.out.println(code);
return "";
});
Try it out
Let’s try authenticating a vehicle in test
mode.
Restart your server, open up your browser and go to http://localhost:8000/login
. Notice once you log in, Smartcar showcases all the permissions your application is asking for, in this case, read_vehicle_info
. A user has to consent to all the permissions.
Once you have logged in and accepted the permissions, you should see your authorization code
printed to your console.
In the next section, we will cover how to exchange the authorization code
for an access_token
and make your first request to Smartcar API with it!