15.Spring Boot 使用Spring security

Spring Boot 使用Spring security

      Spring Boot与Spring Security在一起开发非常简单,充分体现了自动装配的强大,Spring Security是Spring Boot官方推荐使用的安全框架。配置简单,功能强大。接下来将说说Spring Boot使用Spring security进行安全控制。

1.Spring Boot 内置属性参数

      Spring Boot 提供的内置配置参数以security为前缀,具体属性如下:
# SECURITY (SecurityProperties 类中)
security.basic.authorize-mode=role # 应用授权模式,ROLE=成员必须是安全的角色,AUTHENTICATED=经过身份验证的用户,NONE=没有设置安全授权
security.basic.enabled=true # 启用基本身份认证
security.basic.path=/** # 拦截策略,以逗号分隔
security.basic.realm=Spring # HTTP基本realm
security.enable-csrf=false # 启用csrf支持
security.filter-order=0 # 过滤器执行顺序
security.filter-dispatcher-types=ASYNC, FORWARD, INCLUDE, REQUEST # security 过滤器链dispatcher类型
security.headers.cache=true # 启用缓存控制 HTTP headers.
security.headers.content-type=true # 启用 "X-Content-Type-Options" header.
security.headers.frame=true # 启用 "X-Frame-Options" header.
security.headers.hsts= # HTTP Strict Transport Security (HSTS) mode (none, domain, all).
security.headers.xss=true # 启用跨域脚本 (XSS) 保护.
security.ignored= # 安全策略,以逗号分隔
security.require-ssl=false # 启用所有请求SSL
security.sessions=stateless # Session 创建策略(always, never, if_required, stateless).
security.user.name=user # 默认用户名
security.user.password= # 默认用户名密码
security.user.role=USER # 默认用户角色

# SECURITY OAUTH2 CLIENT (OAuth2ClientProperties 类中)
security.oauth2.client.client-id= # OAuth2 client id.
security.oauth2.client.client-secret= # OAuth2 client secret. A random secret is generated by default

# SECURITY OAUTH2 RESOURCES (ResourceServerProperties 类中)
security.oauth2.resource.id= # Identifier of the resource.
security.oauth2.resource.jwt.key-uri= # The URI of the JWT token. Can be set if the value is not available and the key is public.
security.oauth2.resource.jwt.key-value= # The verification key of the JWT token. Can either be a symmetric secret or PEM-encoded
[ERROR] Errors: [ERROR] ApiServiceTest.testCallConsentServiceVerifyConsent_thenReturnBadRequest » IllegalState Failed to load ApplicationContext for [WebMergedContextConfiguration@2dfeb141 testClass = unit.ApiSer viceTest, locations = [], classes = [com.dahsing.api.Application], contextInitializerClasses = [], activeProfiles = [], propertySourceDescriptors = [], propertySourceProperties = ["org.springframewo rk.boot.test.autoconfigure.web.servlet.WebMvcTestContextBootstrapper=true"], contextCustomizers = [[ImportsContextCustomizer@629e8212 key = [org.springframework.boot.autoconfigure.task.TaskExecution AutoConfiguration, org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration, org.springframework.boot.autoconfigure.web.servlet.HttpEncodingAutoConfiguration, org.springframework.boot.aut oconfigure.validation.ValidationAutoConfiguration, org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration, org.springframework.boot.autoconfigure.hateoas.HypermediaAutoConfigu ration, org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration, org.springframework.boot.autoconfigure.data.web.SpringDataWebAutoConfiguration, org.springframework.boot.test.autocon figure.web.reactive.WebTestClientAutoConfiguration, org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration, org.springframework.boot.test.autoconfigure.web.servlet.MockMv cAutoConfiguration, org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration, org.springframework.boot.autoconfigure.security.servlet.SecurityFilterAutoConfiguration, org.sp ringframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration, org.springframework.boot.autoconfigure.security.oauth2.client.servlet.OAuth2ClientAutoConfiguration, org.springframework .boot.test.autoconfigure.web.servlet.MockMvcSecurityConfiguration, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcWebClientAutoConfiguration, org.springframework.boot.test.autoconfig ure.web.servlet.MockMvcWebDriverAutoConfiguration, org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration, org.springframework.boot.autoconfigure.gson.GsonAutoConfiguration, org .springframework.boot.autoconfigure.jsonb.JsonbAutoConfiguration, org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration, org.springframework.boot.autoconfigure.web.servlet.We bMvcAutoConfiguration, org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration, org.springframework.boot.autoconfigure.security.oauth2.resource.servlet.OAuth2Reso urceServerAutoConfiguration, org.springframework.boot.autoconfigure.groovy.template.GroovyTemplateAutoConfiguration, org.springframework.boot.autoconfigure.mustache.MustacheAutoConfiguration]], org. springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@28b46423, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@ 48c76607, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.web.reactor.netty.DisableReactorResourceFactoryGlobalResourcesContextCustomizerFactory$ DisableReactorResourceFactoryGlobalResourcesContextCustomizerCustomizer@3fc79729, org.springframework.boot.test.autoconfigure.OverrideAutoConfigurationContextCustomizerFactory$DisableAutoConfigurati onContextCustomizer@1187c9e8, org.springframework.boot.test.autoconfigure.actuate.observability.ObservabilityContextCustomizerFactory$DisableObservabilityContextCustomizer@1f, org.springframework.bo ot.test.autoconfigure.filter.TypeExcludeFiltersContextCustomizer@35ae581d, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@14deeb89, org.springframework.boot. test.autoconfigure.web.servlet.WebDriverContextCustomizer@9573584, org.springframework.test.context.web.socket.MockServerContainerContextCustomizer@53251a66, org.springframework.boot.test.context.SpringBootTestAnnotation@bcb91adb], resourceBasePath = "src/main/webapp", contextLoader = org.springframework.boot.test.context.SpringBootContextLoader, parent = null] [INFO] [ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0
最新发布
06-26
Spring Boot单元测试中,`ApplicationContext`加载失败是一个常见的问题,通常由配置错误、依赖缺失或组件扫描不正确引起。以下是一些常见原因及解决方法。 ### 1. 确保使用正确的注解 在测试类上使用`@SpringBootTest`注解可以确保整个上下文被加载。该注解会触发完整的上下文加载机制,并查找主配置类(带有`@SpringBootApplication`的类)[^1]。 ```java import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest public class YourTestClass { // 测试代码 } ``` 如果只需要加载特定的配置,也可以使用`@ContextConfiguration`来手动指定配置类或资源文件。 ### 2. 检查主应用类的位置 Spring Boot默认会在测试运行时尝试找到主应用类(通常是带有`@SpringBootApplication`的类)。如果该类不在默认包路径下,可以通过`classes`属性显式指定: ```java @SpringBootTest(classes = MyApplication.class) public class YourTestClass { // 测试代码 } ``` ### 3. 确保必要的Bean已正确注入 如果某个Bean未被正确注入,可能是由于组件扫描未覆盖到相关包。可以在主应用类中确认`@ComponentScan`是否包含所有需要的包,或者在测试中使用`@MockBean`或`@DataJpaTest`等更细粒度的测试注解。 ### 4. 数据源配置问题 如果应用程序依赖数据库连接而测试环境中没有提供数据源,可能导致上下文加载失败。可以使用内存数据库进行测试,例如H2: ```properties spring.datasource.url=jdbc:h2:mem:testdb spring.datasource.driverClassName=org.h2.Driver spring.datasource.username=sa spring.datasource.password= spring.jpa.hibernate.ddl-auto=update ``` 同时确保`pom.xml`或`build.gradle`中包含了相应的依赖项。 ### 5. 使用日志排查具体错误信息 当`ApplicationContext`加载失败时,控制台通常会输出详细的堆栈跟踪。检查这些信息可以帮助定位具体是哪个Bean未能正确初始化。例如,可能是因为缺少某个配置属性或依赖项未引入。 ### 6. 禁用某些自动配置 如果某些自动配置类在测试环境下无法正常工作,可以使用`@SpringBootTest(exclude = {SomeAutoConfiguration.class})`来排除它们。 ### 示例:完整测试类结构 ```java import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import static org.junit.jupiter.api.Assertions.assertNotNull; @SpringBootTest public class ApplicationTests { @Autowired private SomeService someService; @Test void contextLoads() { assertNotNull(someService); } } ``` ###
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值