Table of Contents
1. What is Spring Security
2. How to introduce Spring Security
3. How to configure Spring Security
4. How to use Spring Security
5. Obtain the permissions of the currently logged in user
in conclusion
Home Computer Tutorials Computer Knowledge Spring Security permission control framework usage guide

Spring Security permission control framework usage guide

Feb 18, 2024 pm 05:00 PM
spring security spring security spring mvc waynboot

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

Copy after login

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();
}
}
Copy after login

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));
}
}
Copy after login

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);
}
}
Copy after login

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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Spring Security 6: cors() is deprecated and marked for removal Spring Security 6: cors() is deprecated and marked for removal Feb 10, 2024 pm 11:45 PM

I have the following code: publicSecurityFilterChainsecurityFilterChain(HttpSecurityhttp)throwsException{returnhttp.httpBasic().disable().cors().and().csrf().disable().authorizeHttpRequests().requestMatchers("

17 ways to solve the kernel_security_check_failure blue screen 17 ways to solve the kernel_security_check_failure blue screen Feb 12, 2024 pm 08:51 PM

Kernelsecuritycheckfailure (kernel check failure) is a relatively common type of stop code. However, no matter what the reason is, the blue screen error causes many users to be very distressed. Let this site carefully introduce 17 types to users. Solution. 17 solutions to kernel_security_check_failure blue screen Method 1: Remove all external devices When any external device you are using is incompatible with your version of Windows, the Kernelsecuritycheckfailure blue screen error may occur. To do this, you need to unplug all external devices before trying to restart your computer.

A new programming paradigm, when Spring Boot meets OpenAI A new programming paradigm, when Spring Boot meets OpenAI Feb 01, 2024 pm 09:18 PM

In 2023, AI technology has become a hot topic and has a huge impact on various industries, especially in the programming field. People are increasingly aware of the importance of AI technology, and the Spring community is no exception. With the continuous advancement of GenAI (General Artificial Intelligence) technology, it has become crucial and urgent to simplify the creation of applications with AI functions. Against this background, "SpringAI" emerged, aiming to simplify the process of developing AI functional applications, making it simple and intuitive and avoiding unnecessary complexity. Through "SpringAI", developers can more easily build applications with AI functions, making them easier to use and operate.

Use Spring Boot and Spring AI to build generative artificial intelligence applications Use Spring Boot and Spring AI to build generative artificial intelligence applications Apr 28, 2024 am 11:46 AM

As an industry leader, Spring+AI provides leading solutions for various industries through its powerful, flexible API and advanced functions. In this topic, we will delve into the application examples of Spring+AI in various fields. Each case will show how Spring+AI meets specific needs, achieves goals, and extends these LESSONSLEARNED to a wider range of applications. I hope this topic can inspire you to understand and utilize the infinite possibilities of Spring+AI more deeply. The Spring framework has a history of more than 20 years in the field of software development, and it has been 10 years since the Spring Boot 1.0 version was released. Now, no one can dispute that Spring

What are the implementation methods of spring programmatic transactions? What are the implementation methods of spring programmatic transactions? Jan 08, 2024 am 10:23 AM

How to implement spring programmatic transactions: 1. Use TransactionTemplate; 2. Use TransactionCallback and TransactionCallbackWithoutResult; 3. Use Transactional annotations; 4. Use TransactionTemplate in combination with @Transactional; 5. Customize the transaction manager.

GO authenticate access token (keycloak) GO authenticate access token (keycloak) Feb 09, 2024 am 09:30 AM

I'm trying to implement access token validation using GO. But the examples I've seen online seem to just use TOKEN_SECRET to verify it. But I'm used to programming in Javaspring and don't need to use TOKEN_SECRET. I just provide the jwk-set-uri and it checks for validity (auto-security filters etc.) and I know it talks to the oauth server and does this validation. Is there no library in Go to check if the token is valid by making a request to the oauth server? I know I know I can do this manually by making a request to the oauth server's userinfo endpoint: http://localh

How to set transaction isolation level in Spring How to set transaction isolation level in Spring Jan 26, 2024 pm 05:38 PM

How to set the transaction isolation level in Spring: 1. Use the @Transactional annotation; 2. Set it in the Spring configuration file; 3. Use PlatformTransactionManager; 4. Set it in the Java configuration class. Detailed introduction: 1. Use the @Transactional annotation, add the @Transactional annotation to the class or method that requires transaction management, and set the isolation level in the attribute; 2. In the Spring configuration file, etc.

JAX-RS vs. Spring MVC: A battle between RESTful giants JAX-RS vs. Spring MVC: A battle between RESTful giants Feb 29, 2024 pm 05:16 PM

Introduction RESTful APIs have become an integral part of modern WEB applications. They provide a standardized approach to creating and using Web services, thereby improving portability, scalability, and ease of use. In the Java ecosystem, JAX-RS and springmvc are the two most popular frameworks for building RESTful APIs. This article will take an in-depth look at both frameworks, comparing their features, advantages, and disadvantages to help you make an informed decision. JAX-RS: JAX-RSAPI JAX-RS (JavaAPI for RESTful Web Services) is a standard JAX-RSAPI developed by JavaEE for developing REST

See all articles