Admin authentication

Updated at 1690885280000

Operating principle

  1. When a user logs in, the server will authenticate and return an access token to the client via a cookie with two pieces of information:
  • adminAccessToken: The access token string.
  • adminAccessTokenExpiredAt: The expiration time of the access token.
  1. Each time the client sends a request, the browser will automatically include the cookie in the request to the server.
  2. The server will validate this token by querying the ezy_admin_access_tokens table. If the validation is successful, it will retrieve the userId; otherwise, if unsuccessful, it will redirect to the login page or return 401 Unauthorized to the client.

Note: If an admin logs in for the first time, a new token will be generated. From the next login onwards, when the token expires, it will be renewed instead of creating a new one. This way, a token will be used across multiple devices.

Registration method

  1. To specify that a controller or a controller's function requires authentication, you need to use the @Authenticated annotation. Most of the admin controllers should use this annotation to require authentication, for example:
@Authenticated
@Controller
public class AdminAdminsController {}
  1. Typically, we also want to assign different permissions for each admin group. In that case, we can use the @EzyFeature annotation for the controller and its corresponding functions for the features we want, for example:
@EzyFeature("admin_management")
@DoGet("/admins")
public View adminsGet(
    @AdminRoles AdminRolesProxy adminRoles
) {
    return viewFactory.newAdminsViewBuilder(AdminViewName.LIST)
        .addVariable(
            "enableAddNewButton",
            adminRoles.isAccessible("/admins/add")
        )
        .build();
}

Then, to assign permissions for the admin_management feature, for example, we go to the role screen, such as /admins/roles/editor, and check the corresponding checkboxes.

Components received

After successful authentication, in the controller, you can use the following annotations:

  1. @AdminId.
  2. @AdminRolesProxy.

@AdminId annotation

This annotation allows you to retrieve the admin ID, for example:

@DoGet("/admins/me")
public AdminProfileResponse adminsMeGet(
    @AdminId long adminId
) {
    return adminProfileGet(adminService.getAdminById(adminId));
}

@AdminRolesProxy annotation

This object contains information about the admin's permissions. You can use it to check the admin's permission for the provided API, for example:

@EzyFeature("admin_management")
@DoGet("/admins")
public View adminsGet(
    @AdminRoles AdminRolesProxy adminRoles
) {
    return viewFactory.newAdminsViewBuilder(AdminViewName.LIST)
        .addVariable(
            "enableAddNewButton",
            adminRoles.isAccessible("/admins/add")
        )
        .build();
}