推荐项目:Spring Boot 3.0 Security with JWT 实现
// 导入Spring Boot和Spring Security依赖的库
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.web.server.SecurityWebFilterChain;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
// 使用Spring Boot 3.0和Spring Security的JWT进行身份验证和授权
@SpringBootApplication
@EnableWebFluxSecurity
public class SecurityJwtApplication {
// 配置跨源资源共享
@Bean
public CorsWebFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
return new CorsWebFilter(source);
}
// 配置安全策略
@Bean
public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
http
.csrf().disable()
.authorizeExchange()
.pathMatchers("/login").permitAll()
.anyExchange().authenticated()
.and()
.addFilter ... // 添加JWT登录过滤器和其他安全过滤器配置
.build();
return http.build();
}
public static void main(String[] args) {
SpringApplication.run(SecurityJwtApplication.class, args);
}
}
这个代码实例展示了如何在Spring Boot 3.0应用中使用Spring Security和JWT实现用户认证。它配置了跨源资源共享,并定义了安全策略,其中登录路径是公开的,其余路径需要用户通过认证。同时,它提供了一个主方法来启动Spring Boot应用。在实际应用中,你需要添加JWT登录过滤器和其他相关的安全过滤器配置。
评论已关闭