Designing Universal Permission Systems: RBAC Models & Spring Security Implementation with JWT
This article explains RBAC permission models (RBAC0 through RBAC3) and demonstrates practical Spring Security integration covering basic setup, JWT token authentication, JSON login customization, BCrypt password encryption, and database-backed authentication with code examples.
RBAC Permission Analysis
RBAC (Role-Based Access Control) assigns permissions to users through roles. Instead of granting permissions directly to each user, roles act as intermediaries: users receive roles, roles receive permissions. This reduces administrative overhead and permission vulnerabilities when multiple users share identical permissions.
RBAC Model Classification
RBAC0
The simplest model with two variants:
User-to-role many-to-one : each user holds exactly one role; a role can be assigned to many users.
User-to-role many-to-many : a user can hold multiple roles simultaneously; a role can be assigned to many users. Example: Zhang San acts as both administrator and finance officer, thus possessing both permission sets.
RBAC1
Extends RBAC0 by introducing role inheritance (sub-roles). Child roles inherit permissions from parent roles, enabling hierarchical permission structures.
RBAC2
Adds constraints on top of RBAC0:
Role mutual exclusion : a user cannot hold two mutually exclusive roles simultaneously (e.g., accountant and auditor in a financial system).
Cardinality constraint : a role may have a fixed maximum number of members (e.g., only one CEO).
Prerequisite roles : acquiring a higher role requires first holding a lower role (e.g., vice-general-manager before general-manager).
Runtime mutual exclusion : a user may possess two roles but can only exercise one at a time, requiring explicit role switching.
RBAC3
Unified model combining RBAC1 (inheritance) and RBAC2 (constraints).
What Is a Permission?
Permissions are collections of resources: page operation rights, page access rights, and data CRUD rights. For example, a system may grant access to modules such as plan management, customer management, contract management, inventory notification, grain traceability, statistical queries, and equipment management — including both menu visibility and page access.
User Groups
User groups batch-assign roles to collections of users. Instead of granting roles individually to thousands of employees in a department, administrators assign the role once to the group. Benefits: reduced workload, clearer structure, multi-level management support.
Spring Security Basic Usage
Dependency
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>Simple Controller
@RestController
@RequestMapping("/test")
public class Test {
@RequestMapping("/test")
public String test() {
return "test";
}
}Default Login
On startup, Spring Security prints a generated password in the logs (e.g., 984cccf2-ba82-468e-a404-7d32123d0f9c). Accessing any endpoint redirects to the default login form with username user and the printed password.
Custom Username/Password via Configuration
spring:
security:
user:
name: ming
password: 123456
roles: adminIn-Memory Authentication (WebSecurityConfigurerAdapter)
@Configuration
public class MyWebSecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
PasswordEncoder passwordEncoder() {
return NoOpPasswordEncoder.getInstance();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("admin").password("123").roles("admin");
}
}HttpSecurity Request Interception
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("itguang").password("123456").roles("USER")
.and()
.withUser("admin").password("{noop}123456").roles("ADMIN");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest().permitAll()
.and()
.formLogin().permitAll()
.and()
.logout().permitAll();
}
}This configuration permits all requests while retaining form login and logout endpoints.
Spring Security JWT Integration
A complete demo returning a JWT token upon successful login.
Dependencies
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
<version>2.3.1.RELEASE</version>
</dependency>JwtUser Implements UserDetails
public class JwtUser implements UserDetails {
private String username;
private String password;
private Integer state;
private Collection<? extends GrantedAuthority> authorities;
// constructors, getters, and all UserDetails methods returning true for account status flags
}JwtTokenUtil — Token Generation, Refresh, Validation
public class JwtTokenUtil implements Serializable {
private String secret;
private Long expiration;
private String header;
private String generateToken(Map<String, Object> claims) { ... }
private Claims getClaimsFromToken(String token) { ... }
public String generateToken(UserDetails userDetails) { ... }
public String getUsernameFromToken(String token) { ... }
public Boolean isTokenExpired(String token) { ... }
public String refreshToken(String token) { ... }
public Boolean validateToken(String token, UserDetails userDetails) { ... }
}Uses HS512 signing, embeds subject ( sub) and creation timestamp in claims.
JwtAuthenticationTokenFilter — OncePerRequestFilter
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
@Autowired UserDetailsService userDetailsService;
@Autowired JwtTokenUtil jwtTokenUtil;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) {
String authHeader = request.getHeader(jwtTokenUtil.getHeader());
if (authHeader != null && StringUtils.isNotEmpty(authHeader)) {
String username = jwtTokenUtil.getUsernameFromToken(authHeader);
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
UserDetails userDetails = userDetailsService.loadUserByUsername(username);
if (jwtTokenUtil.validateToken(authHeader, userDetails)) {
UsernamePasswordAuthenticationToken authentication =
new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authentication);
}
}
}
chain.doFilter(request, response);
}
}UserDetailsService Implementation
@Service
public class JwtUserDetailsServiceImpl implements UserDetailsService {
@Autowired UserMapper userMapper;
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
User user = userMapper.selectByUserName(s);
if (user == null) throw new UsernameNotFoundException("'" + s + "'.这个用户不存在");
List<SimpleGrantedAuthority> authorities = user.getRoles().stream()
.map(Role::getRolename)
.map(SimpleGrantedAuthority::new)
.collect(Collectors.toList());
return new JwtUser(user.getUsername(), user.getPassword(), user.getState(), authorities);
}
}Login Service Returning JWT
@Service
public class UserServiceImpl implements UserService {
@Autowired AuthenticationManager authenticationManager;
@Autowired UserDetailsService userDetailsService;
@Autowired JwtTokenUtil jwtTokenUtil;
public RetResult login(String username, String password) throws AuthenticationException {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);
Authentication authentication = authenticationManager.authenticate(token);
SecurityContextHolder.getContext().setAuthentication(authentication);
UserDetails userDetails = userDetailsService.loadUserByUsername(username);
return new RetResult(RetCode.SUCCESS.getCode(), jwtTokenUtil.generateToken(userDetails));
}
}Security Configuration (WebSecurityConfigurerAdapter)
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableWebSecurity
public class WebSecurity extends WebSecurityConfigurerAdapter {
@Autowired UserDetailsService userDetailsService;
@Autowired JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
@Bean(name = BeanIds.AUTHENTICATION_MANAGER)
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and().authorizeRequests()
.antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
.antMatchers("/auth/**").permitAll()
.anyRequest().authenticated()
.and().headers().cacheControl();
http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = http.authorizeRequests();
registry.requestMatchers(CorsUtils::isPreFlightRequest).permitAll();
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration cors = new CorsConfiguration();
cors.setAllowCredentials(true);
cors.addAllowedOrigin("*");
cors.addAllowedHeader("*");
cors.addAllowedMethod("*");
source.registerCorsConfiguration("/**", cors);
return new CorsFilter(source);
}
}Stateless session policy, CORS enabled, JWT filter inserted before UsernamePasswordAuthenticationFilter.
Spring Security JSON Login
Customizes authentication to accept JSON payloads instead of form data.
CustomAuthenticationFilter Extending UsernamePasswordAuthenticationFilter
public class CustomAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) {
if (request.getContentType().equals(MediaType.APPLICATION_JSON_UTF8_VALUE)
|| request.getContentType().equals(MediaType.APPLICATION_JSON_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 getAuthenticationManager().authenticate(authRequest);
} catch (IOException e) {
e.printStackTrace();
UsernamePasswordAuthenticationToken authRequest =
new UsernamePasswordAuthenticationToken("", "");
setDetails(request, authRequest);
return getAuthenticationManager().authenticate(authRequest);
}
} else {
return super.attemptAuthentication(request, response);
}
}
}SecurityConfig Registering Custom Filter
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and()
.antMatcher("/**").authorizeRequests()
.antMatchers("/", "/login**").permitAll()
.anyRequest().authenticated()
.and().formLogin().loginPage("/")
.and().csrf().disable();
http.addFilterAt(customAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
}
@Bean
CustomAuthenticationFilter customAuthenticationFilter() throws Exception {
CustomAuthenticationFilter filter = new CustomAuthenticationFilter();
filter.setAuthenticationSuccessHandler(new SuccessHandler());
filter.setAuthenticationFailureHandler(new FailureHandler());
filter.setFilterProcessesUrl("/login/self");
filter.setAuthenticationManager(authenticationManagerBean());
return filter;
}Reuses the adapter's AuthenticationManager via authenticationManagerBean().
Spring Security Password Encryption
BCryptPasswordEncoder Bean
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}Service-Layer Usage
@Service
@Transactional
public class UserServiceImpl implements UserService {
@Resource UserRepository userRepository;
@Resource BCryptPasswordEncoder bCryptPasswordEncoder;
@Override
public User add(User user) {
user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
return userRepository.save(user);
}
@Override
public ResultInfo login(User user) {
User dbUser = userRepository.findByName(user.getName());
if (dbUser == null) return error("用户名不存在");
if (!bCryptPasswordEncoder.matches(user.getPassword(), dbUser.getPassword()))
return error("密码不正确");
return success("登录成功");
}
}Passwords are hashed on save and verified via matches(raw, encoded).
Database Authentication
Schema Design
Tables for users, roles, and user-role mapping (illustrated in the article's diagram).
WebSecurityConfig with UserDetailsService
@Configurable
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired UserService userService;
@Bean
PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userService);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin/**").hasRole("admin")
.anyRequest().authenticated()
.and()
.formLogin().loginProcessingUrl("/login").permitAll()
.and()
.csrf().disable();
}
}UserServiceimplements UserDetailsService; the adapter delegates authentication to it.
Summary
The article covers RBAC theory (models RBAC0–RBAC3, permissions, user groups) and provides end-to-end Spring Security examples: basic setup, in-memory and database authentication, JWT stateless integration with custom filter and token utility, JSON login via filter replacement, and BCrypt password encoding. All code is presented as runnable snippets with explicit configuration steps.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
