Home  >  Article  >  Computer Tutorials  >  Spring Security permission control framework usage guide

Spring Security permission control framework usage guide

WBOY
WBOYforward
2024-02-18 17:00:041265browse

Spring Security权限控制框架使用指南

In the background management system, access permission control is usually required to limit the access capabilities of different users to the interface. If a user lacks specific permissions, he or she cannot access certain interfaces.

This article will use the waynboot-mall project as an example to introduce how to introduce the permission control framework Spring Security into common back-end management systems. The outline is as follows:

waynboot-mall project address: https://github.com/wayn111/waynboot-mall

1. What is Spring Security

Spring Security is an open source project based on the Spring framework, designed to provide powerful and flexible security solutions for Java applications. Spring Security provides the following features:

  • Authentication: Supports multiple authentication mechanisms, such as form login, HTTP basic authentication, OAuth2, OpenID, etc.
  • Authorization: Supports role- or permission-based access control, as well as expression-based fine-grained control.
  • Protection: Provides a variety of protection measures, such as preventing session fixation, click hijacking, cross-site request forgery and other attacks.
  • Integration: Seamless integration with Spring Framework and other third-party libraries and frameworks, such as Spring MVC, Thymeleaf, Hibernate, etc.

2. How to introduce Spring Security

Directly introduce the spring-boot-starter-security dependency into the waynboot-mall project,


org.springframework.boot
spring-boot-starter-security
3.1.0

3. How to configure Spring Security

Configuring Spring Security in Spring Security 3.0 is a little different from the past. For example, it no longer inherits WebSecurityConfigurerAdapter. In the waynboot-mall project, the specific configuration is as follows,

@Configuration
@EnableWebSecurity
@AllArgsConstructor
@EnableMethodSecurity(securedEnabled = true, jsr250Enabled = true)
public class SecurityConfig {
private UserDetailsServiceImpl userDetailsService;
private AuthenticationEntryPointImpl unauthorizedHandler;
private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;
private LogoutSuccessHandlerImpl logoutSuccessHandler;

@Bean
public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
httpSecurity
// cors启用
.cors(httpSecurityCorsConfigurer -> {})
.csrf(AbstractHttpConfigurer::disable)
.sessionManagement(httpSecuritySessionManagementConfigurer -> {
httpSecuritySessionManagementConfigurer.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
})
.exceptionHandling(httpSecurityExceptionHandlingConfigurer -> {
httpSecurityExceptionHandlingConfigurer.authenticationEntryPoint(unauthorizedHandler);
})
// 过滤请求
.authorizeHttpRequests(authorizationManagerRequestMatcherRegistry -> {
authorizationManagerRequestMatcherRegistry
.requestMatchers("/favicon.ico", "/login", "/favicon.ico", "/actuator/**").anonymous()
.requestMatchers("/slider/**").anonymous()
.requestMatchers("/captcha/**").anonymous()
.requestMatchers("/upload/**").anonymous()
.requestMatchers("/common/download**").anonymous()
.requestMatchers("/doc.html").anonymous()
.requestMatchers("/swagger-ui/**").anonymous()
.requestMatchers("/swagger-resources/**").anonymous()
.requestMatchers("/webjars/**").anonymous()
.requestMatchers("/*/api-docs").anonymous()
.requestMatchers("/druid/**").anonymous()
.requestMatchers("/elastic/**").anonymous()
.requestMatchers("/message/**").anonymous()
.requestMatchers("/ws/**").anonymous()
// 除上面外的所有请求全部需要鉴权认证
.anyRequest().authenticated();
})
.headers(httpSecurityHeadersConfigurer -> {
httpSecurityHeadersConfigurer.frameOptions(HeadersConfigurer.FrameOptionsConfig::disable);
});
// 处理跨域请求中的Preflight请求(cors),设置corsConfigurationSource后无需使用
// .requestMatchers(CorsUtils::isPreFlightRequest).permitAll()
// 对于登录login 验证码captchaImage 允许匿名访问

httpSecurity.logout(httpSecurityLogoutConfigurer -> {
httpSecurityLogoutConfigurer.logoutUrl("/logout");
httpSecurityLogoutConfigurer.logoutSuccessHandler(logoutSuccessHandler);
});
// 添加JWT filter
httpSecurity.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
// 认证用户时用户信息加载配置,注入springAuthUserService
httpSecurity.userDetailsService(userDetailsService);
return httpSecurity.build();
}
@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
return authenticationConfiguration.getAuthenticationManager();
}
/**
 * 强散列哈希加密实现
 */
@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
}

Here is a detailed introduction to the SecurityConfig configuration class:

  • filterChain(HttpSecurity httpSecurity) method is the core method of access control. Here you can set whether permission authentication is required for the url, cors configuration, csrf configuration, user information loading configuration, jwt filter interception configuration and many other functions.
  • authenticationManager(AuthenticationConfiguration authenticationConfiguration) method is suitable for enabling the authentication interface and needs to be declared manually, otherwise an error will be reported at startup.
  • bCryptPasswordEncoder() method allows the user to define the password encryption policy when the user logs in. It needs to be declared manually, otherwise an error will be reported at startup.

4. How to use Spring Security

To use Spring Security, you only need to add the corresponding @PreAuthorize annotation to the method or class that needs to control access permissions, as follows,

@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("system/role")
public class RoleController extends BaseController {

private IRoleService iRoleService;

@PreAuthorize("@ss.hasPermi('system:role:list')")
@GetMapping("/list")
public R list(Role role) {
Page page = getPage();
return R.success().add("page", iRoleService.listPage(page, role));
}
}

We added the @PreAuthorize("@ss.hasPermi('system:role:list')") annotation to the list method to indicate that the currently logged in user has system:role:list permissions to access the list method, otherwise a permission error will be returned .

5. Obtain the permissions of the currently logged in user

In the SecurityConfig configuration class, we define UserDetailsServiceImpl as our implementation class for loading user information, so as to compare the user's account and password in the database with the account and password passed in by the front end. code show as below,

@Slf4j
@Service
@AllArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {

private IUserService iUserService;

private IDeptService iDeptService;

private PermissionService permissionService;

public static void main(String[] args) {
BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
System.out.println(bCryptPasswordEncoder.encode("123456"));
}

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// 1. 读取数据库中当前用户信息
User user = iUserService.getOne(new QueryWrapper().eq("user_name", username));
// 2. 判断该用户是否存在
if (user == null) {
log.info("登录用户:{} 不存在.", username);
throw new UsernameNotFoundException("登录用户:" + username + " 不存在");
}
// 3. 判断是否禁用
if (Objects.equals(UserStatusEnum.DISABLE.getCode(), user.getUserStatus())) {
log.info("登录用户:{} 已经被停用.", username);
throw new DisabledException("登录用户:" + username + " 不存在");
}
user.setDept(iDeptService.getById(user.getDeptId()));
// 4. 获取当前用户的角色信息
Set rolePermission = permissionService.getRolePermission(user);
// 5. 根据角色获取权限信息
Set menuPermission = permissionService.getMenuPermission(rolePermission);
return new LoginUserDetail(user, menuPermission);
}
}

Let’s give an explanation of the code logic of UserDetailsServiceImpl. You can understand it with the help of the code.

  • Read current user information in the database
  • Determine whether the user exists
  • Determine whether to disable
  • Get the current user’s role information
  • Get permission information based on role

in conclusion

This article explains to you how to introduce the permission control framework Spring Security 3.0 version into the back-end management system and code practice. I believe it can help everyone have a clear understanding of the permission control framework Spring Security. Later, you can follow the usage guide in this article to introduce Spring Security into your own projects step by step for access control.

The above is the detailed content of Spring Security permission control framework usage guide. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:mryunwei.com. If there is any infringement, please contact admin@php.cn delete