One reason I like to build an application in public is that it keeps me accountable. I can’t run away. If I don’t finish something, it’s ok. At least, I will have something done to show to people. Building in public is not a new idea, a lot of people have used it. In this post, I discuss the design of REST API for Social KPI.
In the previous post here, we discussed the architecture of the application we are building. This will be an ongoing process as we continue to build our application and evolve.
We will follow the following tips to design REST APIs
We will use Resource to represent object for REST APIs
API endpoint will represent a resource object in the plural. Example – companies, users
We will use HTTP status codes for success or failure of the request
We will use JSON object to represent a response
And we will use versioning to represent a version of APIs
As discussed in the previous post application idea, we will have APIs for companies, users of those companies, customers, clicks, engagements data. While concluding this short post, I want to say that the next post will include database design as well as URL design for REST APIs.
In my last post design, I discussed the idea that we are going to work on building a web application. I detailed the user flow, but I missed out on some points about security and session management. I will add the details of architecture of social KPI web application.
Name of the application
Before we discuss the application, we still haven’t decided on the name for the application. This web application will indicate the performance of a small business in social media. Basically, this is a free tool for marketing and depending on how small businesses use social media, they will be able to build a campaign for their business. If small businesses are not using social media, they are already at a disadvantage. This is just a pie in the big social world. That brings me to the purpose of the application to provide social key performance indicators (social KPIs) to businesses. So the name of the application will be SocialPie.
Security and Session Management
We will use Spring Boot. We will be using spring security elements to build authentication and authorization aspect of the application. I will definitely include the details of this component when we will start working on building the application. In a previous post spring security, I have discussed how to use spring security for authentication.
For managing a session, we will be using spring provided service based on Redis. We will also be using caching considering we will be connecting to Facebook, Twitter, and Instagram APIs, so we can keep the data in cache for pre-decided time. This will be beneficial from a performance perspective. We will be using Redis caching with our own cache manager to handle caching.
I will try to include all these elements in the architecture diagram that we will be building in this post.
Architecture
Conclusion
In this post, we created an architecture for our web application Social KPI. In the next post, I will detail another user flow with some class diagrams and explain each service in detail. The application will be based on microservice architecture.
In this post of building an application, we discussed what is a saas application and how it can be designed and built. There are possibly a few ideas that I had in my mind or that I came across on the internet. So, I will discuss an idea for the saas application here.
One of the ideas that I have chosen, is to build a web application for small businesses so they can monitor their social media progress. A report that can give details about how the business is performing. From the outside, the whole idea seems very simple – build a report. But there are a lot of complexities involved here if we will be connecting to multiple social media.
We will be discussing the design of this idea and see if we can make progress to build a final design.
Discussion of the idea for the saas application –
A small business can subscribe to this application on two models. One model will be free and others will be paid.
The free model will offer a basic report about the business’ performance in social media.
The paid model will offer a detailed report along with an action plan to improve marketing ratings.
Part of this architecture and development, first we will build a free model only. Depending on how long it is going to take me to build the entire product, we will plan the paid model.
We will use Twitter, Instagram, and Facebook as the three main social media to connect to. All these three social services offer their APIs for developers.
A User flow
If a small business is looking for a marketing tool as part of its social media strategy, they can subscribe to the application that I will be building herewith.
A sign-up page. A user coming across this web application will have to sign up for an account to use the tool.
Sign up will be unique for a business. At least for an alpha version of this tool, only a single user from a business can sign up/login. Maybe next versions or paid versions will give more flexibility to sign up or log in for multiple users from the same business.
A sign-up page will ask for a business name, person’s name, contact number, email address.
A person who is signing up will receive an email for confirmation with login details.
Alpha version will have basic security to login and logout.
Once the business has signed up, that person will access the web application to login.
Alpha version will not deal with security policies at least.
A user once logged into the application will see a dashboard to access the reports.
There will be three reports available for the free subscription model and all three reports will give details about how a business is performing on social media. These three reports will correspond to Facebook, Twitter, and Instagram.
There will be a logout button available for the user to logout. Logout will clear all the session cookies.
Each report will fetch the live data from the respective social media services. Depending on the restrictions for APIs provided by Facebook, Twitter, and Instagram, fetching of new data will be developed.
The report will also show a graphical representation of performance.
How will this help?
What’s the value of this application for small businesses? Of course, this is the basic question. I had to think about the answer if I had to design this application. That is going to be a unique selling point (USP) of this app.
The tool will provide fact-based data about how the business is doing.
It will provide strategies to improve social media presence.
In turn, this will give an idea to small businesses to market themselves and improve customer satisfaction.
Technology Stack
we will be using Java, Spring Boot, MySQL, Github, and AngularJS.
References
The idea for this saas application was borrowed from here.
In this post, we will show how to use Spring Boot Security to login, authorization based on user role, log out, and error handling.
We will be discussing the following use case
A user accesses a home page for an application.
A user enters credentials
If correct credentials, we create a session and verifies the user role. User with USER role sees the user profile page. User with ADMIN role sees the list of users page.
Incorrect credentials, the user will see the login screen once again to enter credentials.
A user clicks on logout, the session is deleted and the user is redirected to the login page.
If a user (of any role) tries to login after logout, the user should be redirected to the appropriate page
In a scenario where a user is neither USER nor ADMIN, he is redirected to the error page
Handling of CSRF token
To completely understand this post, make sure you have gone through my other posts on the Spring Boot series.
Since this post involves authorization for users, we have to do some database changes. We will add a couple of tables and respective model classes in our REST API modification.
Table role
Table user_role
create table role (id int(11) auto_increment primary key not null, role varchar(255) )
create table user_role (user_id int(11) primary key not null, role_id int(11) primary key not null))
user_role the table helps to maintain a many-to-many relationship between the user and role table. We will have only two roles for demo purposes, USER and ADMIN.
Another change we have done in table user is that we have added a field called password_hash to store password set by user/administrator for a user to login. We will be storing a hash password value of the original password that the user will set.
Dependencies
Since we will be using Spring-security for authentication and authorization purposes, we will add the dependency for spring security as follows:
As shown in this controller, we have defined a user page, a login page, and an error page (403). A user with the role of either USER or ADMIN or both can access a user page which shows that logged in user’s profile.
Every user irrespective of roles will see the login page for authentication. If there are any errors during authentication or authorization, the user will see an error page displaying access denied page (403).
This login page shows a simple form to input username (email) and password and process that authentication using spring-security database authentication method.
@RequestMapping(value = "/home", method = RequestMethod.GET)
public String homepage(Model model)
{
LOGGER.info(" Enter >> homepage() ");
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String name = auth.getName();
User user = userManager.findUserByEmail(name);
model.addAttribute("name", user.getFirstname());
LOGGER.info(" Exit << homepage() ");
return "index";
}
Changes in MainController are about an authenticated user and passing that user’s first name to model to display in HTML page. UserManager in the service layer has been enhanced to return a user based on username (which is email). We have also added an email to be unique as a constraint in the database.
User page for a user with role USER is nothing but a user profile information that he can edit and update any time.
Now we have the application ready with all the required backend details for adding the authentication part. Remember we are using spring-security for authentication and authorization of an application.
When a user with role ADMIN or USER calls either /home or /user pages respectively, the user will need to log in.
Once the user inputs credentials, validation of credentials happens against the JDBC database authentication mechanism provided by spring-security.
If a user of the role USER tries to access the ADMIN home page, the user sees an error 403 page. Authentication Success Handler handles the redirection strategy.
If the user clicks the LOGOUT button on the page he is on, the session gets deleted and the user logs out of the application. The user will see the login page. All the cookies will be deleted. Logout Success Handler handles the redirection.
Changes in AngularJS User Interface Controller
As shown in user.html page, once the user with role USER is logged in, he sees URL for his profile information. If a user clicks this URL, the user sees his or her profile information. This page has a controller called UserCtrl which basically handles the logout on this initial page. User Profile is shown on userprofile.html page which has singleusercontroller. This angular js controller handles updating user profile information or logout. The github repository contains the rest of the code.
Handling CSRF Token
There are two ways we can handle Cross-Site Request Forgery token in the Spring application. The first way is by disabling this token generation. This is not a recommended approach as this put your application to possible CSRF security attacks for hackers. If you are just doing this for demo purposes, you can disable this in SecurityConfig.java by calling http.csrf().disable().
As Spring points out, a request coming through browsers should contain CSRF Protection.
We will be using spring security to handle CSRF token on the server-side rather than on the client-side. So every request that comes to the server, we will add a CSRF token and then verified. Angular JS verifies the cookie for the CSRF token before a user can post any request.
Add a CSRF Filter Class
We will add a filter that will handle setting of CSRF token in a cookie. Angular JS expects a cookie name to be as XSRF-TOKEN. This class will look like below:
We tell spring-security to expect CSRF token in the format that Angular wants to send it back , a header called X-XSRF-TOKEN instead of default X-CSRF-TOKEN. With these changes, we don’t have to do anything on client side.
In this post, we showed how to use spring security for authentication and authorization. Now we will show how to run the application. Once the application is built and run from eclipse, access the page https://localhost:8443/home , we will see below screen:
It will be the same screen if you access https://localhost:8443/user. Now if we enter credentials of an admin user, we will see below screen:
User screen will be as below:
If you click logout, it will log the user out and show login screen again. In this way, we showed how we can use spring security for authentication and authorization. Code for this is available at Github repository.
In this post, we will show how to add swagger documentation to Spring Boot rest API. We learned how to create a Spring Boot REST API. In Microservices’ world, these days documenting your API is a standard norm. Swagger provides a handy interface and a simple way to build these documentations that any client can test at any moment. They don’t need to have all the services in their environment.
What is Swagger?
Swagger was intended to provide a standard, language-agnostic interface to REST APIs which allow anyone to understand the capabilities of a service without any source code, documentation of source code. You can find more details about Swagger here.
How to add swagger documentation?
In our previous post, we added Spring boot REST API. We will add swagger to the same REST API.
Add Maven dependencies
To start with, let’s add maven dependencies for swagger jars.
In our main starting Application class, we will add a few configurations for setting up a bean that will handle swagger. In the below code, I show what I have added in Application.java the file. Basically, we have created a new bean of the type Docket which takes care of the swagger configuration.
@EnableSwagger2
@SpringBootApplication(scanBasePackages = { "com.betterjavacode.benefits" })
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
public Docket benefitsApi() {
return new Docket(DocumentationType.SWAGGER_2).groupName("Benefits")
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build()
.pathMapping("/");
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder().title("Benefits REST Service")
.description(" A simple REST service for Benefits software ")
.contact(new Contact("Yogesh Mali", "https://betterjavacode.com/", ""))
.version("1.0")
.build();
}
}
3. Show Swagger documentation
Now once we have added the configuration, we can build our project with maven clean install. After a successful build, run the project from eclipse as a Java application. We will access swagger documentation from URL http://localhost:8080/swagger-ui.html. This will look like below :