Spring Security permission control framework usage guide
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!

What is Windows 11 Education? If you want to install this system on your PC, how can you do this work? This post from php.cn gives a detailed guide on Windows 11 Education download ISO and how to install it from the ISO file.

Are your Outlook emails not showing up in Inbox, but showing in search? What steps can you do when Outlook not showing all emails? Now in this post given by php.cn Solution, we will introduce several useful methods to help you address the issue and g

If you are trying to power off your computer but encountering the Windows stuck on shutting down screen issue, you can find several helpful fixes from this php.cn guide. Just keep reading to see the details.
![[Complete Guide] How to Fix Microsoft Teams Error CAA50021? - MiniTool](https://img.php.cn/upload/article/001/242/473/174559963580964.png?x-oss-process=image/resize,p_40)
If you are looking for effective solutions to the Microsoft Teams error code CAA50021, this post is worth reading. In this post, php.cn introduces how to get rid of this error in detail. Simply follow it to solve your problem.

Do you want to make Windows 11 or Windows 10 look like Windows XP? Do you know how to do this on your device? You can try the WindowBlinds 11 Beta version now. In this post, php.cn Software will tell you how to download WindowBlinds 11 and introduce

If you can’t use the universal way to uninstall Windows updates due to An error has occurred, Not all of the updates were successfully uninstalled, you can try the methods mentioned in the php.cn post to solve the issue.

What is wacom_tablet.exe? Is the Windows process safe to run? Some people find wacom_tablet.exe can't end process and when this Windows system error happens, you may be overwhelmed and don’t know where to start. On php.cn, this article will resolve y

ChatGPT errors are various and we’ve detected suspicious behavior is a common one. If you are trapped in this issue, what should you do? Go on reading this post from php.cn and you can find some useful fixes to help you get rid of trouble.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.
