SaaSManager API – basic operations with examples - SaaSManager/java-sdk GitHub Wiki

SaaSManager API – basic operations with examples.

SaaSManager API uses HTTP request methods to communicate with your application (it's RESTful). For this reason you need a proper library to communicate with our service. In this tutorial I am going to use Jackson library for JSON handling and Unirest for simple HTTP requests.

But first, let's prepare a model for stored data. Let's start with a Grant class.

public class Grant {
    @JsonProperty("username")
    private final String username;

    @JsonProperty("password")
    private final String password;

    @JsonCreator
    public Grant(@JsonProperty("username") String username, @JsonProperty("password") String password){
        this.password = password;
        this.username = username;
    }

    public String getUsername() {
        return username;
    }

    public String getPassword() {
        return password;
    }
}

This model is used to store credentials needed for authorization. A model to store information about authorization token is also needed.

public class Token {
    @JsonIgnore
    private final ZonedDateTime expireDate;

    @JsonProperty("access_token")
    private final String accessToken;

    @JsonProperty("token_type")
    private final String tokenType;

    @JsonProperty("expires_in")
    private final Integer expiresIn;
    
    @JsonCreator
    public Token(@JsonProperty("token_type") String tokenType,
                 @JsonProperty("access_token") String accessToken,
                 @JsonProperty("expires_in") Integer expiresIn) {
        this.accessToken = accessToken;
        this.tokenType = tokenType;
        this.expiresIn = expiresIn;
        this.expireDate = ZonedDateTime.now().plusSeconds(expiresIn);
    }
}

token_type, access_token and expires_in are fields received from the HTTP request and expireDate variable is used to store the exact moment when the token is going to expire. It will be very useful later.

Register a tenant

To register a new tenant you need neither of those objects. They will be needed later. In this case, you should create a new class, let's say Register, which will store a JSON object that looks like this:

{
    "email" : "[email protected]",
    "password" : "Password of your tenant",
    "username" : "Its username",
    "name" : "Its name",
    "billing" : {
        "name" : "Billing name",
        "address" : "Billing address",
        "taxNo" : "Taxation number"
    }
}

In my case I have also created a constructor, which looks like this:

public Register(String email,
         String password,
         String username,
         String name,
         String bname,
         String baddress,
         Integer btaxNo) {
    this.email = email;
    this.password = password;
    this.username = username;
    this.name = name;
    this.billing.setName(bname);
    this.billing.setAddress(baddress);
    this.billing.setTaxNo(btaxNo);
}

After that, we need a method to handle a request:

public Integer signIn() throws JsonProcessingException, UnirestException {
    ObjectMapper objectMapper = new ObjectMapper();
    Register register = new Register(
            EMAIL,
            PASSWORD,
            USERNAME,
            NAME,
            BNAME,
            BADDRESS,
            BTAXNO
    );

    String json = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(register);

    HttpResponse<JsonNode> jsonNodeHttpResponse = Unirest
            .post("https://app.dev.saasmgr.com/saasmgr-auth/tenantAuth/register")
            .header("content-type", "application/json")
            .header("cache-control", "no-cache")
            .body(json)
            .asJson();

    return jsonNodeHttpResponse.getStatus();
}

This method creates an object Register then parses it into a JSON object, sends this JSON object via POST to /tenantAuth/register endpoint and returns received status code, which can be handled by your application.

Get your tenant token

For communication with SaaS Manager you need to obtain a tenant token. The most convenient way to do so is to create a Spring Boot service which will get this token and renew it every time it expires. @Service annotation creates also a singleton, so everything you write with this annotation will be started at initialization of the program and will be available everywhere.

@Service
public class SaaSMgrTenantTokenProvider {

    private final Grant grant;
    public Token token;

We put in our service two, previously created, objects, Grant and Token. We can also create a constructor for this class:

@Autowired
private SaaSMgrTenantTokenProvider(@Value("${username}") String username,
                                   @Value("${password}") String password) throws IOException, UnirestException {
    grant = new Grant(username, password);
    
    token = setToken();
}

This constructor takes username and password from application.preferences file (via @Value annotation), put credentials into a grant object and sets token using the setToken() method.

public Token setToken() throws IOException, UnirestException {
    ObjectMapper objectMapper = new ObjectMapper();
    String json = null;
    Token tokenTemp = null;

    json = objectMapper.writeValueAsString(grant);

     HttpResponse<String> stringHttpResponse = Unirest
            .post("https://app.dev.saasmgr.com/saasmgr-auth/tenantAuth/oauth/token")
            .header("content-type", "application/json")
            .header("cache-control", "no-cache")
            .body(json)
            .asString();

    String stringHttpResponseBody = stringHttpResponse.getBody();

    tokenTemp = objectMapper.readValue(stringHttpResponseBody, Token.class);

    return tokenTemp;
}

This method is responsible for RESTful connection with the server and getting JSON with our tenant token. After that it mappes it on Token object and returns it. After we set the token, we need to get it.

public Token getToken() throws IOException, UnirestException {
    synchronized (token){
        if(this.token == null) {
            this.token = setToken();
        }
        else if(this.token.isExpired()) {
            this.token = setToken();
        }
    }
    return token;
}

This class is a simple getter with an extension. The synchronized part checks if token is expired or null and sets it if needed. The synchronized method is needed here to prevent thread interference.

Now you can get your tenant token anywhere you want, e.g.:

private final SaaSMgrTenantTokenProvider tokenProvider;

public YourClass(SaaSMgrTenantTokenProvider tokenProvider) {
        this.tokenProvider = tokenProvider;
}

…

String tenantToken = tokenProvider.getToken().getAccessToken(); //or getExpiredIn() or getTokenType() for another information

#Log in your user User authentication is as easy as tonent auth. You just have to provide a Grant object with user credentials, parse it as JSON and send to the proper endpoint (in this case appUsers/oauth/tokeninfo) with access_token parameter. In our case it looks like this:

Grant grant;
String tenantToken = tokenProvider.getToken().getAccessToken();
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(grant);

HttpResponse<String> httpResponse = Unirest
        .post("https://app.dev.saasmgr.com/userapp-auth/appUsers/oauth/token?access_token={tenant_token}")
        .header("content-type", "application/json")
        .header("cache-control", "no-cache")
        .routeParam("tenant_token", tenantToken)
        .body(json)
        .asString();

The httpResponse variable contains the whole response, e.g. status number (you can receive it via getStatus() method) and JSON response, which contains user token. This can be easily mapped into our Token class:

ObjectMapper objectMapper = new ObjectMapper();
Token token = objectMapper.readValue(httpResponse.getBody(), Token.class);

#Validate user token Now use of every SaaSManager function is very easy. All you have to do is to make a proper RESTful inquiry. For example, to check if your user token is valid, you just have to call an proper endpoint with parameters or JSON bodies:

HttpResponse<string> httpResponse = Unirest
    .get("https://app.dev.saasmgr.com/userapp-auth/appUsers/oauth/tokeninfo?access_token={tenant_token}&token={user_token}")
    .routeParam("tenant_token", tenantToken)
    .routeParam("user_token", userToken)
    .header("content-type", "application/json")
    .header("cache-control", "no-cache")
    .asString();

In this case we added a access_token parameter (with tenant token) and token parameter (with user token).

Now, all you have to do is check the HTTP Response number, e.g.:

Integer errorNumber = httpResponse.getStatus();

and return an answer:

if(errorNumber == 200)
    return "Token is valid.";
else
    return "Token is invalid.";
⚠️ **GitHub.com Fallback** ⚠️