


1. Introduction to Spring Security
Spring Security is a core project of Spring. It is a powerful and highly customizable authentication and access control framework. It provides authentication and authorization capabilities as well as protection against common attacks, and it has become the de facto standard for protecting spring-based applications.
Spring Boot provides automatic configuration, which can be used by introducing starter dependencies.
Summary of Spring Security features:
Easy to use, provides Spring Boot starter dependencies, and is easy to integrate with Spring Boot projects.
Professional, providing CSRF protection, clickjacking protection, XSS protection, etc., and providing various security header integrations (X-XSS-Protection, X-Frame-Options, etc.).
Password encrypted storage, supports multiple encryption algorithms
Extremely scalable and customizable
-
OAuth3 JWT authentication support
- ##… …
Note that this article demonstrates the use of JDK and Spring Boot versions as follows:Add the following dependencies to the pom.xml file of the Spring Boot project:Spring Boot: 2.7.2
JDK: 11
Different Spring Boot versions have different configurations, but the principles are the same.
<!-- Spring Security的Spring boot starter,引入后将自动启动Spring Security的自动配置 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <!-- 下面的依赖包含了OAuth3 JWT认证实现 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-oauth3-resource-server</artifactId> </dependency>The above two dependencies are enough. 4. Configure Spring Security to use JWT authentication
Mainly configures HttpSecurity Bean to generate SecurityFilterBean. The configuration is as follows:Note: Different Spring Boot versions have different configurations, but the principle is the same. This article uses Spring Boot: 2.7.2.
import com.nimbusds.jose.jwk.JWK; import com.nimbusds.jose.jwk.JWKSet; import com.nimbusds.jose.jwk.RSAKey; import com.nimbusds.jose.jwk.source.ImmutableJWKSet; import com.nimbusds.jose.jwk.source.JWKSource; import com.nimbusds.jose.proc.SecurityContext; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.oauth3.jwt.JwtDecoder; import org.springframework.security.oauth3.jwt.JwtEncoder; import org.springframework.security.oauth3.jwt.NimbusJwtDecoder; import org.springframework.security.oauth3.jwt.NimbusJwtEncoder; import org.springframework.security.oauth3.server.resource.authentication.JwtAuthenticationConverter; import org.springframework.security.oauth3.server.resource.authentication.JwtGrantedAuthoritiesConverter; import org.springframework.security.oauth3.server.resource.web.BearerTokenAuthenticationEntryPoint; import org.springframework.security.oauth3.server.resource.web.access.BearerTokenAccessDeniedHandler; import org.springframework.security.web.SecurityFilterChain; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; /** * Spring Security 配置 * * @author cloudgyb * @since 2022/7/30 18:31 */ @Configuration(proxyBeanMethods = false) @EnableMethodSecurity public class WebSecurityConfigurer { //使用RSA对JWT做签名,所以这里需要一对秘钥。 //秘钥文件的路径在application.yml文件中做了配置(具体配置在下面)。 @Value("${jwt.public.key}") private RSAPublicKey key; @Value("${jwt.private.key}") private RSAPrivateKey priv; /** * 构建SecurityFilterChain bean */ @Bean SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception { //"/login"是系统的登录接口,所以需要匿名可访问 http.authorizeRequests().antMatchers("/login").anonymous(); //其他请求都需认证后才能访问 http.authorizeRequests().anyRequest().authenticated() .and() //采用JWT认证无需session保持,所以禁用掉session管理器 .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and() //login接口可能来自其他站点,所以对login不做csrf防护 .csrf((csrf) -> csrf.ignoringAntMatchers("/login")) //配置认证方式为JWT,并且配置了一个JWT认证装换器,用于去掉解析权限时的SCOOP_前缀 .oauth3ResourceServer().jwt().jwtAuthenticationConverter( JwtAuthenticationConverter() ); //配置认证失败或者无权限时的处理器 http.exceptionHandling((exceptions) -> exceptions .authenticationEntryPoint(new BearerTokenAuthenticationEntryPoint()) .accessDeniedHandler(new BearerTokenAccessDeniedHandler()) ); //根据配置生成SecurityFilterChain对象 return http.build(); } /** * JWT解码器,用于认证时的JWT解码 */ @Bean JwtDecoder jwtDecoder() { return NimbusJwtDecoder.withPublicKey(this.key).build(); } /** * JWT编码器,生成JWT */ @Bean JwtEncoder jwtEncoder() { JWK jwk = new RSAKey.Builder(this.key).privateKey(this.priv).build(); JWKSource<SecurityContext> jwks = new ImmutableJWKSet<>(new JWKSet(jwk)); return new NimbusJwtEncoder(jwks); } /** * JWT认证解码时,去掉Spring Security对权限附带的默认前缀SCOOP_ */ @Bean JwtAuthenticationConverter JwtAuthenticationConverter() { final JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter(); jwtGrantedAuthoritiesConverter.setAuthorityPrefix(""); final JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter(); jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(jwtGrantedAuthoritiesConverter); return jwtAuthenticationConverter; } }
application.yml
jwt: private.key: classpath:app.key public.key: classpath:app.pubThe above configuration needs to be done in Spring Boot Generate a pair of RSA keys in the project's Resource directory.
You can use the following website to generate: http://tools.jb51.net/password/rsa_encode/,
Note: The key format uses PKCS#8, and the private key password is empty.
There is one more thing that needs to be explained. I used Spring Boot’s value injection in the code:@Value("${jwt.public.key}") private RSAPublicKey key; @Value("${jwt.private.key}") private RSAPrivateKey priv;
Are you curious about what Spring Boot is? How to convert the file corresponding to the string in the yaml file to RSAPublicKey and RSAPrivateKey?So far our project has supported JWT authentication.In fact, Spring Security did the processing for us. It helped us implement a converter ResourceKeyConverterAdapter in Spring Security. You can read the relevant source code for a deeper understanding.
But the user needs to carry a legal JWT in the request header Authorization to pass the authentication and then access the server resources. So how to issue a legal JWT to the user?
It's very simple. You can provide a login interface, let the user enter the user name and password, and issue the token after successful matching.
In fact, this is not necessary. There are other ways. For example, when we call a third-party interface, our usual approach is to apply to the third party first. After the application is approved, we can get a token. This process is the same as the issuance of a token after the login is passed above. Both of them obtain a token through legal means!5. Implement the login interface The login interface has only one purpose, which is to issue tokens to legitimate users!
Login API interface:
@RestController public class SysLoginController { private final SysLoginService sysLoginService; public SysLoginController(SysLoginService sysLoginService) { this.sysLoginService = sysLoginService; } @PostMapping("/login") public String login(@RequestBody LoginInfo loginInfo) { return sysLoginService.login(loginInfo); } }Login logic implementation:
@Service public class SysLoginService { private final JwtEncoder jwtEncoder; private final SpringSecurityUserDetailsService springSecurityUserDetailsService; public SysLoginService(JwtEncoder jwtEncoder, SpringSecurityUserDetailsService springSecurityUserDetailsService) { this.jwtEncoder = jwtEncoder; this.springSecurityUserDetailsService = springSecurityUserDetailsService; } public String login(LoginInfo loginInfo) { //从用户信息存储库中获取用户信息 final UserDetails userDetails = springSecurityUserDetailsService.loadUserByUsername(loginInfo.getUsername()); final String password = userDetails.getPassword(); //匹配密码,匹配成功生成JWT令牌 if (password.equals(loginInfo.getPassword())) { return generateToken(userDetails); } //密码不匹配,抛出异常,Spring Security发现抛出该异常后会将http响应状态码设置为401 unauthorized throw new BadCredentialsException("密码错误!"); } private String generateToken(UserDetails userDetails) { Instant now = Instant.now(); //JWT过期时间为36000秒,也就是600分钟,10小时 long expiry = 36000L; String scope = userDetails.getAuthorities().stream() .map(GrantedAuthority::getAuthority) .collect(Collectors.joining(" ")); //将用户权限信息使用空格分割拼为字符串,放到JWT的payload的scope字段中,注意不要改变scope这个属性,这是Spring Security OAuth3 JWT默认处理方式,在JWT解码时需要读取该字段,转为用户的权限信息! JwtClaimsSet claims = JwtClaimsSet.builder() .issuer("self") .issuedAt(now) .expiresAt(now.plusSeconds(expiry)) .subject(userDetails.getUsername()) .claim("scope", scope) .build(); return this.jwtEncoder.encode(JwtEncoderParameters.from(claims)).getTokenValue(); } }Other non-core code will not be posted here. I put the code on github. For details, you can go to https ://github.com/cloudgyb/spring-security-study-jwt. 6. TestUse postman to test:
Using the wrong password will return a 401 Unauthorized status code, indicating that our authentication failed!
I wrote a test interface:
@RestController public class HelloController { @GetMapping("/") @PreAuthorize("hasAuthority('test')") public String hello(Authentication authentication) { return "Hello, " + authentication.getName() + "!"; } }This interface requires the user to have "test" permission, but the logged-in user does not have this permission (only one app permission). At this time, the interface is called:
First paste the token obtained from the previous login step into the token:
我们发送请求得到了403 Forbidden的响应,意思就是我们没有访问权限,此时我们将接口权限改为“app”:
@RestController public class HelloController { @GetMapping("/") @PreAuthorize("hasAuthority('app')") public String hello(Authentication authentication) { return "Hello, " + authentication.getName() + "!"; } }
重启项目。再次发起请求:
The above is the detailed content of How to use SpringBoot+SpringSecurity+JWT to implement system authentication and authorization. For more information, please follow other related articles on the PHP Chinese website!

Canal工作原理Canal模拟MySQLslave的交互协议,伪装自己为MySQLslave,向MySQLmaster发送dump协议MySQLmaster收到dump请求,开始推送binarylog给slave(也就是Canal)Canal解析binarylog对象(原始为byte流)MySQL打开binlog模式在MySQL配置文件my.cnf设置如下信息:[mysqld]#打开binloglog-bin=mysql-bin#选择ROW(行)模式binlog-format=ROW#配置My

前言SSE简单的来说就是服务器主动向前端推送数据的一种技术,它是单向的,也就是说前端是不能向服务器发送数据的。SSE适用于消息推送,监控等只需要服务器推送数据的场景中,下面是使用SpringBoot来实现一个简单的模拟向前端推动进度数据,前端页面接受后展示进度条。服务端在SpringBoot中使用时需要注意,最好使用SpringWeb提供的SseEmitter这个类来进行操作,我在刚开始时使用网上说的将Content-Type设置为text-stream这种方式发现每次前端每次都会重新创建接。最

一、手机扫二维码登录的原理二维码扫码登录是一种基于OAuth3.0协议的授权登录方式。在这种方式下,应用程序不需要获取用户的用户名和密码,只需要获取用户的授权即可。二维码扫码登录主要有以下几个步骤:应用程序生成一个二维码,并将该二维码展示给用户。用户使用扫码工具扫描该二维码,并在授权页面中授权。用户授权后,应用程序会获取一个授权码。应用程序使用该授权码向授权服务器请求访问令牌。授权服务器返回一个访问令牌给应用程序。应用程序使用该访问令牌访问资源服务器。通过以上步骤,二维码扫码登录可以实现用户的快

1.springboot2.x及以上版本在SpringBoot2.xAOP中会默认使用Cglib来实现,但是Spring5中默认还是使用jdk动态代理。SpringAOP默认使用JDK动态代理,如果对象没有实现接口,则使用CGLIB代理。当然,也可以强制使用CGLIB代理。在SpringBoot中,通过AopAutoConfiguration来自动装配AOP.2.Springboot1.xSpringboot1.xAOP默认还是使用JDK动态代理的3.SpringBoot2.x为何默认使用Cgl

我们使用jasypt最新版本对敏感信息进行加解密。1.在项目pom文件中加入如下依赖:com.github.ulisesbocchiojasypt-spring-boot-starter3.0.32.创建加解密公用类:packagecom.myproject.common.utils;importorg.jasypt.encryption.pbe.PooledPBEStringEncryptor;importorg.jasypt.encryption.pbe.config.SimpleStrin

知识准备需要理解ApachePOI遵循的标准(OfficeOpenXML(OOXML)标准和微软的OLE2复合文档格式(OLE2)),这将对应着API的依赖包。什么是POIApachePOI是用Java编写的免费开源的跨平台的JavaAPI,ApachePOI提供API给Java程序对MicrosoftOffice格式档案读和写的功能。POI为“PoorObfuscationImplementation”的首字母缩写,意为“简洁版的模糊实现”。ApachePOI是创建和维护操作各种符合Offic

1.首先新建一个shiroConfigshiro的配置类,代码如下:@ConfigurationpublicclassSpringShiroConfig{/***@paramrealms这儿使用接口集合是为了实现多验证登录时使用的*@return*/@BeanpublicSecurityManagersecurityManager(Collectionrealms){DefaultWebSecurityManagersManager=newDefaultWebSecurityManager();

一、定义视频上传请求接口publicAjaxResultvideoUploadFile(MultipartFilefile){try{if(null==file||file.isEmpty()){returnAjaxResult.error("文件为空");}StringossFilePrefix=StringUtils.genUUID();StringfileName=ossFilePrefix+"-"+file.getOriginalFilename(


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Zend Studio 13.0.1
Powerful PHP integrated development environment
