Role-based Access Control Web Service with Spring Boot

Project Design

  • Front-end pass username and web url to back-end then back-end will return boolean value to indicate whether the user can access the coresponding website.
  • Front-end calls RESTful APIs implemented by back-end to add, update, delete users and roles;

    RBAC Model

  • The relation between user and role is many to many, so as that between role and access;
  • Admin is a special type of role which has all web accesses and can manage users and other roles;
  • Admin create a set of roles with corresponding access permissions and assign part of them to a new-added user.
  • User gain accesses based on the roles he/she is assigned with.

    Database Table Design

  • User Table:
id name create_time update_time
  • Role Table:
id type create_time update_time
  • Access Table:
id name url create_time update_time
  • User-Role Table:
id user_id role_id create_time update_time
  • Role-Access Tabe:
id role_id access_id create_time update_time

RESTful APIs(According to company’s policy, url and request method are not provided):

  • listAllUsers
  • loadUserRoles
  • addUser
  • updateUser
  • deleteUser
  • listAllRoles
  • loadRoleAccesses
  • addRole
  • updateRole
  • deleteRole

Spring Boot Project Structure

RESTful API

  • Jackson maps JSON <-> Java POJO Automatically

    Parameter Acquiring and Sending

  • @GetMapping('/url'): @RequestParam
  • @PostMapping('/url'): @RequestBody
  • @PutMapping('/url'): @RequestBody
  • @DeleteMapping('/url/{id}') : @PathVariable
  • response: code, message, data
  • @Autowired
  • @RestController

Test

Postman

Mockito Unit Test

  • @InjectMocks
  • @Mock
  • MockMVC: perform(), andExpect()
  • when-return
  • verify

Redis

What is Redis

  • Redis is a in-memory data store, used as database, cache and message broker.
  • Redis is NoSQL.
  • Redis is non-volatile, different from memcached. Redis has built-in data persistency to avoid data disappearing from restart.

Commands

  • SCAN: cursor-based
  • MATCH: match pattern
  • CONFIG: related to configuration of the server
  • INFO: related to information of the server
  • COMMAND: return details on redis commands
  • CLIENT: manage clients

Data Types

  • LISTS(Ordered): LPUSH, RPUSH, LRANGE, LLEN, LPOP, RPOP
  • SETS(Unordered, No Repeating): SADD, SREM, SISMEMBER, SMEMBERS, SCARD, SMOVE, SUNION, SDIFF, SRANDOMEMBER, SPOP
  • SORTED SETS(Ordered, Values No Repeating, Scores can repeat): ZADD, ZREM, ZRANGE, ZRANGEBYSCORE, ZRANK, ZCARD, ZCOUNT, ZINCBY, ZSCORE,
  • HASH(Field-Value): HSET, HMSET, HGET, HMGET, HGETALL, HDEL, HEXISITS, HINCBY, HKEYS, HLEN, HVALS, HSTRLEN

Data Persistence(From Memory To Disk)

  • RDB(Redis Database):Point-in-time Snapshots; SAVE, BGSAVE
  • AOF(Append Only File): Write Operation Logging; rewrite, fsync;

Java Client

  • Lettuce;
  • Jedis;

MVC with Java

Preview

In this article we discuss:

  • MVC
  • JSP(JSTL)
  • Servlet
  • Test

MVC

  • Both Servlet(print HTML) and JSP(embed Java in HTML: expression, scriptlet, declaration) can create web pages without the other.
  • In MVC pattern, JSP handles the presentation view, generate dynamic web pages, while Servlet focuses on the business logic.
  • Comparsion of JSP and Serlet when creating pages alone:
JSP Servlet
HTML file with .jsp extension.
Contains static HTML.
JSP to generate HTML.
Has built-in JSP objects
Java class file.
Generate all HTML.
More steps to access web objects.

Benefits of MVC

  • Minimize the HTML code in Servlet.
  • Minimize the business logic in JSP.

Interaction between Controller and Model

  • Define an object together with helper classes to fetch or modify data from the database as data model.
  • Pass the dataSource to DB model in the controller to perform database pooling injection.
  • Call method of DB model in controller to fetch or modify data from the database, avoid the direct interaction between controller and database. This achieves good code logic, make code easily maintained and ensure the safety of database.

Interaction between Controller and View

  • Servlet access the data from request.
  • Servlet can forward the data to JSP using Dispatcher.
  • Servlet can add data to request object.
  • JSP access the data through requestor JSTL(brief grammar). ${data}$
  • JSP can redirect to Servlet using response.sendRedirect(<thePageUrl>).
  • User can not see the change of url when using forward, but can see when using redirect.
1
2
3
4
5
6
7
// Servlet
RequestDispatcher dispatcher = request.getRequestDispatcher("/view-students.jsp");
String[] students = ...;
request.setAttribute("student_list", students);
dispatcher.forward(request, response);
// JSP
request.getAttribute("student_list");

JSP(Java Server Pages)

JSP Tags

  • Custom JSP Tags(Another way of avoiding heavy business logic in JSP) and JSTL.
  • JSP Tags are reusable.
  • JSP Tags minimize the scriptlet in JSP.

JSTL(Java Standard Tag Library), I18N

JSTL Core Tags(prefix c)

  • Include a reference for core tags. (uri not need to connect to the Internet)
  • Loop over an array variable:
1
2
3
<c:forEach var="tmpCity" items="${myCity}">
$<tmpCity> </br>
</c:forEach>

JSTL Function Tags

  • Include a reference for function tags.
  • Length of a string:
1
2
<c:set var="data" value="ericsayshi"/>
Length of the String <b> ${data} </b>: ${fn: length(data)}
  • Split string into array:
1
<c:set var="citiesArray" value="${fn:split(data, ',')}"/>

I18N

  • JSTL uses Formatting Message labels and locale to achieve internationalization: fmt:setLocale, fmt:bundle, fmt:message
  • Resource Files(translated version of labels)
  • Achieve locale from user’s selection or pageContext.request.locale
1
2
3
4
5
6
7
<!-->JSP will append locale after the basename automatically.<-->
<fmt:setLocale value="es_ES"/>
<fmt:bundle basename="com.tutorialspoint.Example">
<fmt:message key="count.one"/><br/>
<fmt:message key="count.two"/><br/>
<fmt:message key="count.three"/><br/>
</fmt:bundle>

State Management

  • Session is stored in the server while Cookie is stored in user’s web browser.
1
2
response.addCookie(...);
Cookie[] theCookies = request.getCookies();

Servlet

Form Processing

  • HTML Form: name="xxx", method="GET" or method="POST".
  • Servlet access data through: request.getParameter("xxx").

doGet() and doPost()

  • Form data appears as name-value pair in the URL of doGet() method: theUrl?field1=value1&field2=value2…
  • Form data is stored in the body of request(header and body) in doPost() method.
doGet() doPost()
URL can be bookmarked or emailed.
Good for debugging.
Limitations on data length.
URL can not be bookmarked or emailed.
No limitations on data length.
Can send binary data.
Form data won’t appear in the url.

Configuration Parameters Reading

  • Store parameters in WEB-INF/web.xml.
1
2
ServletContext context = getServletContext();
context.getInitParameter("...") // the return value is of String type
  • Define parameter per Servlet: use <servlet>, <servlet-mappings> tags in web.xml; do not use Annotations @WebServlet in servlet file.