Using Java to manage FusionAuth

What we’ll cover

  • Setting up FusionAuth
  • Setting up Maven dependency
  • Creating an application
  • Creating a user
  • Retrieving a user’s profile details
  • Logging in a user
  • Changing a user’s password
  • Deactivating a user
  • Reactivating a user
  • Deleting a user
  • Deactivating an application
  • Reactivating an application
  • Deleting an application

What you’ll need

Setting up FusionAuth

FusionAuth can be deployed on nearly any platform. Depending on the platform you’re using, you can get the installation instructions from here.

Setting up the Maven dependency

To set up the dependencies needed for this project, let’s create a Maven utility project and add the FusionAuth Java client library to the pom.xml file. We’ll use version 1.15.4 of the FusionAuth Maven dependency:

<dependency>
<groupId>io.fusionauth</groupId>
<artifactId>fusionauth-java-client</artifactId>
<version>1.15.4</version>
</dependency>

Setup

The API key and location of the FusionAuth server are stored in a properties file called application.properties. Many Java application environments provide secrets management, but for this tutorial, we’ll just load the properties file into a class. Make sure you update your application.properties file with the correct values.

package io.fusionauth.example;import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class ApplicationProperties {
private static String apiKey;
private static String fusionAuthURL;
public static String getApiKey() {
return apiKey;
}
public static String getFusionAuthURL() {
return fusionAuthURL;
}
public static void setupProperties() {
try (InputStream input = ApplicationProperties.class.getResourceAsStream("/application.properties")) {
Properties prop = new Properties();
// load a properties file
prop.load(input);
fusionAuthURL = prop.getProperty("fusionAuthURL");
apiKey = prop.getProperty("apiKey");
} catch (IOException ex) {
ex.printStackTrace();
}
}
}

Creating an application

In FusionAuth, an application refers to a place where a user can log into. Before you begin integrating authentication capabilities with FusionAuth, you’ll need to create at least one application.

package io.fusionauth.example;import com.inversoft.error.Errors;
import com.inversoft.rest.ClientResponse;
import io.fusionauth.client.FusionAuthClient;
import io.fusionauth.domain.Application;
import io.fusionauth.domain.api.ApplicationRequest;
import io.fusionauth.domain.api.ApplicationResponse;
public class CreateApplication {
public static void main(String[] args) {
ApplicationProperties.setupProperties();
// Instantiate the client
FusionAuthClient client = new FusionAuthClient(ApplicationProperties.getApiKey(),
ApplicationProperties.getFusionAuthURL());
// Instantiate the application with a name (using the FusionAuth builder pattern)
Application app = new Application().with(a -> a.name = "Todo");
// Creating the request object
ApplicationRequest request = new ApplicationRequest(app, null);
// Use the returned ClientResponse object
ClientResponse<ApplicationResponse, Errors> response = client.createApplication(null, request);
if (response.wasSuccessful()) {
System.out.println("Application creation successful");
} else {
// Handle errors
System.out.println(response.exception);
}
}
}
{
"fieldErrors" : {
"application.name" : [ {
"code" : "[duplicate]application.name",
"message" : "An Application with name = [Todo] already exists."
} ]
},
"generalErrors" : [ ]
}

Creating a user

Applications are no good without users. In FusionAuth, a user refers to someone that has been granted the right to use your FusionAuth application — such as an employee, client, or an end-user. So, let’s see how you can create a user and also carry out various user management tasks for the Todo app.

package io.fusionauth.example;import java.util.UUID;
import com.inversoft.error.Errors;
import io.fusionauth.client.FusionAuthClient;
import io.fusionauth.domain.User;
import io.fusionauth.domain.UserRegistration;
import io.fusionauth.domain.api.user.RegistrationRequest;
import io.fusionauth.domain.api.user.RegistrationResponse;
import com.inversoft.rest.ClientResponse;
public class CreateUser {
public static void main(String[] args) {
ApplicationProperties.setupProperties();
// Instantiate the client
FusionAuthClient client = new FusionAuthClient(ApplicationProperties.getApiKey(),
ApplicationProperties.getFusionAuthURL());
// Instantiate the user and provide login details
User user = new User().with(u -> u.email = "fusionjava@example.com")
.with(u -> u.password = "mypassword101");
// Instantiate the user registration and request object
UserRegistration registration = new UserRegistration();
registration.applicationId = UUID.fromString("1aae68ac-d4d3-4e96-b24c-c9478a309673");
RegistrationRequest request = new RegistrationRequest(user, registration); // Use the returned ClientResponse object
ClientResponse<RegistrationResponse, Errors> response = client.register(null, request);
if (response.wasSuccessful()) {
System.out.println("Registration successful");
} else {
// Handle errors
System.out.println(response.errorResponse);
}
}
}

Retrieving a user’s profile details

Now, let’s see how to retrieve the profile details of the user we created previously. To do this, we’ll use the retrieveUser method.

package io.fusionauth.example;import java.util.UUID;
import com.inversoft.error.Errors;
import io.fusionauth.client.FusionAuthClient;
import io.fusionauth.domain.api.UserResponse;
import com.inversoft.rest.ClientResponse;
public class RetrieveUserInfo {
public static void main(String[] args) {
ApplicationProperties.setupProperties();
// Instantiate the client
FusionAuthClient client = new FusionAuthClient(ApplicationProperties.getApiKey(),
ApplicationProperties.getFusionAuthURL());
UUID userId = UUID.fromString("5eb46e47-927c-41ac-ae60-ed88e3840edd"); // Use the returned ClientResponse object
ClientResponse<UserResponse, Errors> response = client.retrieveUser(userId);
if (response.wasSuccessful()) {
// Output the user's profile details
System.out.println(response.successResponse.user);
} else {
// Handle errors
System.out.println(response.errorResponse);
}
}
}
{
"encryptionScheme" : null,
"factor" : null,
"id" : "812478d4-c99d-4e55-9606-9e58e83938d3",
"password" : null,
"passwordChangeRequired" : false,
"passwordLastUpdateInstant" : 1587287741465,
"salt" : null,
"verified" : true,
"preferredLanguages" : [ ],
"memberships" : [ ],
"registrations" : [ {
"data" : { },
"preferredLanguages" : [ ],
"tokens" : { },
"applicationId" : "3c219e58-ed0e-4b18-ad48-f4f92793ae32",
"authenticationToken" : null,
"cleanSpeakId" : null,
"id" : "7c105c78-c49d-40c1-a5a1-fcff013fd4eb",
"insertInstant" : 1587299377006,
"lastLoginInstant" : null,
"roles" : [ "admin" ],
"timezone" : null,
"username" : null,
"usernameStatus" : "ACTIVE",
"verified" : true
} ],
"active" : true,
"birthDate" : null,
"cleanSpeakId" : null,
"data" : { },
"email" : "fusionjava@gmail.com",
"expiry" : null,
"firstName" : null,
"fullName" : null,
"imageUrl" : null,
"insertInstant" : 1587287741325,
"lastLoginInstant" : null,
"lastName" : null,
"middleName" : null,
"mobilePhone" : null,
"parentEmail" : null,
"tenantId" : "31626538-3731-3762-3664-303931343339",
"timezone" : null,
"twoFactorDelivery" : "None",
"twoFactorEnabled" : false,
"twoFactorSecret" : null,
"username" : "fusionjava",
"usernameStatus" : "ACTIVE"
}

Log in a user

Let’s say we want to use the FusionAuth Java client to log in the user we created. We’d do this if we wanted to log a user in from our own application, rather than using FusionAuth’s OAuth capabilities and the Authorization Code grant. You might do this if you were building a command line tool to add Todos or a mobile application.

package io.fusionauth.example;import java.util.UUID;
import com.inversoft.error.Errors;
import io.fusionauth.client.FusionAuthClient;
import io.fusionauth.domain.api.LoginRequest;
import io.fusionauth.domain.api.LoginResponse;
import com.inversoft.rest.ClientResponse;
public class UserLogin {
public static void main(String[] args) {
ApplicationProperties.setupProperties();
// Instantiate the client
FusionAuthClient client = new FusionAuthClient(ApplicationProperties.getApiKey(),
ApplicationProperties.getFusionAuthURL());
UUID appId = UUID.fromString("1aae68ac-d4d3-4e96-b24c-c9478a309673"); // Create the request object
LoginRequest request = new LoginRequest(appId, "fusionjava@example.com", "mypassword101");
// Use the returned ClientResponse object
ClientResponse<LoginResponse, Errors> response = client.login(request);
if (response.wasSuccessful()) {
System.out.println("Login successful");
} else {
// Handle errors
System.out.println(response.errorResponse);
}
}
}

Changing a user’s password

To change a user’s password, we’ll use the changePasswordByIdentity method. This method allows us to change a user’s password using their identity – login ID and current password. This means we can let our users change their password in our Todo application. Note that doing this will change their password across all FusionAuth applications running within this tenant.

package io.fusionauth.example;import com.inversoft.error.Errors;
import io.fusionauth.client.FusionAuthClient;
import io.fusionauth.domain.api.user.ChangePasswordRequest;
import com.inversoft.rest.ClientResponse;public class ChangePassword {
public static void main(String[] args) {
ApplicationProperties.setupProperties();
// Instantiate the client
FusionAuthClient client = new FusionAuthClient(ApplicationProperties.getApiKey(),
ApplicationProperties.getFusionAuthURL());
// Creating the request object
ChangePasswordRequest request = new ChangePasswordRequest("fusionjava@gmail.com", "oldpassword", "newpassword");
// Use the returned ClientResponse object
ClientResponse<Void, Errors> response = client.changePasswordByIdentity(request);
if (response.wasSuccessful()) {
System.out.println("Password change successful");
} else {
// Handle errors
System.out.println(response.errorResponse);
}
}
}

Deactivating a user

To deactivate a user, we’ll use the deactivateUser method. We’ll provide the ID of the user we are deactivating to this method. Deactivation means they cannot log in, which might happen if the credit card they used to sign up for the Todo app was declined.

package io.fusionauth.example;import java.util.UUID;
import com.inversoft.error.Errors;
import io.fusionauth.client.FusionAuthClient;
import com.inversoft.rest.ClientResponse;
public class DeactivateUser {
public static void main(String[] args) {
ApplicationProperties.setupProperties();
// Instantiate the client
FusionAuthClient client = new FusionAuthClient(ApplicationProperties.getApiKey(),
ApplicationProperties.getFusionAuthURL());
UUID userId = UUID.fromString("5eb46e47-927c-41ac-ae60-ed88e3840edd"); // Use the returned ClientResponse object
ClientResponse<Void, Errors> response = client.deactivateUser(userId);
if (response.wasSuccessful()) {
System.out.println("User deactivated successfully");
} else {
// Handle errors
System.out.println(response.errorResponse);
}
}
}

Reactivating a user

Next, to reactivate the user we just deactivated (perhaps they paid their bill and are now itching to add some todos), let’s use the reactivateUser method and provide the ID of the user as its parameter.

package io.fusionauth.example;import java.util.UUID;
import com.inversoft.error.Errors;
import io.fusionauth.client.FusionAuthClient;
import io.fusionauth.domain.api.UserResponse;
import com.inversoft.rest.ClientResponse;public class ReactivateUser {
public static void main(String[] args) {
ApplicationProperties.setupProperties();
// Instantiate the client
FusionAuthClient client = new FusionAuthClient(ApplicationProperties.getApiKey(),
ApplicationProperties.getFusionAuthURL());
UUID userId = UUID.fromString("5eb46e47-927c-41ac-ae60-ed88e3840edd"); // Use the returned ClientResponse object
ClientResponse<UserResponse, Errors> response = client.reactivateUser(userId);
if (response.wasSuccessful()) {
// Outputting the user's profile details
System.out.println(response.successResponse.user);
} else {
// Handle errors
System.out.println(response.errorResponse);
}
}
}

Deleting a user

Finally, let’s see how to delete a user from the FusionAuth server. To do this, we’ll use the deleteUser method and provide the ID of the user as its parameter. You might do this if a user cancels their Todo app membership.

package io.fusionauth.example;import java.util.UUID;
import com.inversoft.error.Errors;
import io.fusionauth.client.FusionAuthClient;
import com.inversoft.rest.ClientResponse;
public class DeleteUser {
public static void main(String[] args) {
ApplicationProperties.setupProperties();
// Instantiate the client
FusionAuthClient client = new FusionAuthClient(ApplicationProperties.getApiKey(),
ApplicationProperties.getFusionAuthURL());
UUID userId = UUID.fromString("5eb46e47-927c-41ac-ae60-ed88e3840edd"); // Use the returned ClientResponse object
ClientResponse<Void, Errors> response = client.deleteUser(userId);
if (response.wasSuccessful()) {
System.out.println("Deleted!");
} else {
// Handle errors
System.out.println(response.errorResponse);
}
}
}

Deactivating an application

To deactivate an application, we’ll use the deactivateApplication method and provide the ID of the application as its parameter. This disables the application but does not delete all the data. You might do this if you need to disable logins for all users due for system maintenance.

package io.fusionauth.example;import java.util.UUID;
import io.fusionauth.client.FusionAuthClient;
import com.inversoft.error.Errors;
import com.inversoft.rest.ClientResponse;
public class DeactivateApplication {
public static void main(String[] args) {
ApplicationProperties.setupProperties();
// Instantiate the client
FusionAuthClient client = new FusionAuthClient(ApplicationProperties.getApiKey(),
ApplicationProperties.getFusionAuthURL());
UUID appId = UUID.fromString("991001b4-d196-4204-b483-a0ed5dbf7666"); // Use the returned ClientResponse object
ClientResponse<Void, Errors> response = client.deactivateApplication(appId);
if (response.wasSuccessful()) {
System.out.println("Application deactivated successfully");
} else {
// Handle errors
System.out.println(response.errorResponse);
}
}
}

Reactivating an application

To reactivate the application we just deactivated, because the system maintenance is done, let’s use the reactivateApplication method and provide the ID of the application as its parameter.

package io.fusionauth.example;import java.util.UUID;
import io.fusionauth.client.FusionAuthClient;
import io.fusionauth.domain.api.ApplicationResponse;
import com.inversoft.error.Errors;
import com.inversoft.rest.ClientResponse;
public class ReactivateApplication {
public static void main(String[] args) {
ApplicationProperties.setupProperties();
// Instantiate the client
FusionAuthClient client = new FusionAuthClient(ApplicationProperties.getApiKey(),
ApplicationProperties.getFusionAuthURL());
UUID appId = UUID.fromString("991001b4-d196-4204-b483-a0ed5dbf7666"); // Use the returned ClientResponse object
ClientResponse<ApplicationResponse, Errors> response = client.reactivateApplication(appId);
if (response.wasSuccessful()) {
// Output the application's details
System.out.println(response.successResponse.application);
} else {
// Handle errors
System.out.println(response.errorResponse);
}
}
}

Deleting an application

Lastly, let’s see how to delete an application from FusionAuth. To do this, we’ll use the deleteApplication method and provide the ID of the application as its parameter.

package io.fusionauth.example;import java.util.UUID;
import io.fusionauth.client.FusionAuthClient;
import com.inversoft.error.Errors;
import com.inversoft.rest.ClientResponse;
public class DeleteApplication {
public static void main(String[] args) {
ApplicationProperties.setupProperties();
// Instantiate the client
FusionAuthClient client = new FusionAuthClient(ApplicationProperties.getApiKey(),
ApplicationProperties.getFusionAuthURL());
UUID appId = UUID.fromString("991001b4-d196-4204-b483-a0ed5dbf7666"); // Use the returned ClientResponse object
ClientResponse<Void, Errors> response = client.deleteApplication(appId);
if (response.wasSuccessful()) {
// Output the application's details
System.out.println("Deleted!");
} else {
// Handle errors
System.out.println(response.errorResponse);
}
}
}

Conclusion

Throughout this article, you’ve seen how it is easy to integrate FusionAuth with Java using the client library. The library provides an easy-to-use native Java binding to the FusionAuth REST API, which allows you to quickly complete your identity and user management tasks.

  • Add a user to a group
  • Retrieve all the users in a group
  • Log a user out

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
FusionAuth

FusionAuth

49 Followers

FusionAuth solves the problem of building essential user security without distracting from the primary application.