Information Security 17 min read

RBAC Permission Analysis and Spring Security Implementation with JWT and JSON Login

This article explains the fundamentals of Role‑Based Access Control (RBAC), its model variants, permission concepts, and user‑group usage, then demonstrates practical Spring Security setups including basic configuration, JWT integration, JSON‑based login, password encryption, and database authentication with complete code examples.

Java Architect Essentials
Java Architect Essentials
Java Architect Essentials
RBAC Permission Analysis and Spring Security Implementation with JWT and JSON Login

The article begins with an introduction to Role‑Based Access Control (RBAC), describing its purpose of linking users to roles and roles to permissions to simplify permission management in systems where many users share the same rights.

RBAC Models : Four RBAC models are covered – RBAC0 (basic), RBAC1 (adds role hierarchy), RBAC2 (adds constraints such as mutually exclusive roles, cardinality, and prerequisite roles), and RBAC3 (the unified model that combines RBAC1 and RBAC2). Each model is illustrated with textual explanations and diagrams.

Permission Definition : Permissions are defined as collections of resources, including page access, CRUD operations, and menu visibility. An example system with modules like plan management, customer management, and inventory tracking is used to illustrate permission assignment.

User Group Usage : User groups allow batch assignment of roles to many users, reducing administrative effort and improving manageability, especially for large organizations.

Spring Security – Simple Usage : The article shows how to add the spring-boot-starter-security dependency, create a test controller, and configure an in‑memory user with username, password, and role. Sample code:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
package com.example.demo.web;
@RestController
@RequestMapping("/test")
public class Test {
    @RequestMapping("/test")
    public String test(){
        return "test";
    }
}

Running the application displays the default login page, where the generated username and password can be used to log in.

JWT Integration : The guide adds the jjwt dependency and walks through creating a JwtUser class implementing UserDetails , a JwtTokenUtil utility for token generation, validation, and refresh, and a JwtAuthenticationTokenFilter to validate tokens on each request. Key snippets:

package com.example.demo;
public class JwtUser implements UserDetails {
    private String username;
    private String password;
    private Integer state;
    private Collection
authorities;
    // constructors, getters, and overridden UserDetails methods
}
public class JwtTokenUtil implements Serializable {
    private String secret;
    private Long expiration;
    private String header;
    // generateToken, getClaimsFromToken, getUsernameFromToken, isTokenExpired, refreshToken, validateToken
}

The filter extracts the token from the request header, validates it, and sets the authentication context.

JSON Login : A custom CustomAuthenticationFilter extends UsernamePasswordAuthenticationFilter to read JSON payloads (username and password) using Jackson. The filter is registered in the security configuration and replaces the default form‑login filter.

public class CustomAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        if (request.getContentType().equals(MediaType.APPLICATION_JSON_VALUE) ||
            request.getContentType().equals(MediaType.APPLICATION_JSON_UTF8_VALUE)) {
            ObjectMapper mapper = new ObjectMapper();
            try (InputStream is = request.getInputStream()) {
                AuthenticationBean bean = mapper.readValue(is, AuthenticationBean.class);
                UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(bean.getUsername(), bean.getPassword());
                setDetails(request, authRequest);
                return this.getAuthenticationManager().authenticate(authRequest);
            } catch (IOException e) {
                e.printStackTrace();
                return super.attemptAuthentication(request, response);
            }
        } else {
            return super.attemptAuthentication(request, response);
        }
    }
}

The security configuration disables CSRF, permits the JSON login endpoint, and adds the custom filter:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.cors().and()
        .authorizeRequests()
        .antMatchers("/", "/login**").permitAll()
        .anyRequest().authenticated()
        .and().formLogin().loginPage("/")
        .and().csrf().disable();
    http.addFilterAt(customAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
}

Password Encryption : The article recommends using BCryptPasswordEncoder as a bean and demonstrates encrypting passwords before persisting them, as well as verifying passwords during login.

@Bean
public BCryptPasswordEncoder passwordEncoder(){
    return new BCryptPasswordEncoder();
}

In service methods, passwords are encoded with bCryptPasswordEncoder.encode() and matched with bCryptPasswordEncoder.matches() .

Database Authentication : A configuration class shows how to inject a custom UserDetailsService that loads users from a database, configure the password encoder, and protect URLs based on roles (e.g., /admin/** requires the "admin" role).

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userService).passwordEncoder(passwordEncoder());
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
        .antMatchers("/admin/**").hasRole("admin")
        .anyRequest().authenticated()
        .and().formLogin().loginProcessingUrl("/login").permitAll()
        .and().csrf().disable();
}

The article concludes by summarizing that it covered RBAC concepts, Spring Security basics, JWT‑based stateless authentication, JSON login handling, password encryption, and database‑backed authentication, providing a comprehensive guide for building secure Java backend applications.

JavaJWTRBACSpring SecurityJSON LoginPassword Encryption
Java Architect Essentials
Written by

Java Architect Essentials

Committed to sharing quality articles and tutorials to help Java programmers progress from junior to mid-level to senior architect. We curate high-quality learning resources, interview questions, videos, and projects from across the internet to help you systematically improve your Java architecture skills. Follow and reply '1024' to get Java programming resources. Learn together, grow together.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.