下面列出了怎么用org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
public void testDefaultConfiguration() {
this.context = new AnnotationConfigServletWebServerApplicationContext();
this.context.register(AuthorizationAndResourceServerConfiguration.class, MinimalSecureWebApplication.class);
this.context.refresh();
this.context.getBean(AUTHORIZATION_SERVER_CONFIG);
this.context.getBean(RESOURCE_SERVER_CONFIG);
this.context.getBean(OAuth2MethodSecurityConfiguration.class);
ClientDetails config = this.context.getBean(BaseClientDetails.class);
AuthorizationEndpoint endpoint = this.context.getBean(AuthorizationEndpoint.class);
UserApprovalHandler handler = (UserApprovalHandler) ReflectionTestUtils.getField(endpoint,
"userApprovalHandler");
ClientDetailsService clientDetailsService = this.context.getBean(ClientDetailsService.class);
ClientDetails clientDetails = clientDetailsService.loadClientByClientId(config.getClientId());
assertThat(AopUtils.isJdkDynamicProxy(clientDetailsService)).isTrue();
assertThat(AopUtils.getTargetClass(clientDetailsService).getName())
.isEqualTo(InMemoryClientDetailsService.class.getName());
assertThat(handler).isInstanceOf(ApprovalStoreUserApprovalHandler.class);
assertThat(clientDetails).isEqualTo(config);
verifyAuthentication(config);
assertThat(this.context.getBeanNamesForType(OAuth2RestOperations.class)).isEmpty();
}
@Test
public void testEnvironmentalOverrides() {
this.context = new AnnotationConfigServletWebServerApplicationContext();
TestPropertyValues.of("security.oauth2.client.clientId:myclientid",
"security.oauth2.client.clientSecret:mysecret", "security.oauth2.client.autoApproveScopes:read,write",
"security.oauth2.client.accessTokenValiditySeconds:40",
"security.oauth2.client.refreshTokenValiditySeconds:80").applyTo(this.context);
this.context.register(AuthorizationAndResourceServerConfiguration.class, MinimalSecureWebApplication.class);
this.context.refresh();
ClientDetails config = this.context.getBean(ClientDetails.class);
assertThat(config.getClientId()).isEqualTo("myclientid");
assertThat(config.getClientSecret()).isEqualTo("mysecret");
assertThat(config.isAutoApprove("read")).isTrue();
assertThat(config.isAutoApprove("write")).isTrue();
assertThat(config.isAutoApprove("foo")).isFalse();
assertThat(config.getAccessTokenValiditySeconds()).isEqualTo(40);
assertThat(config.getRefreshTokenValiditySeconds()).isEqualTo(80);
verifyAuthentication(config);
}
@Test
public void testCanUseClientCredentialsWithEnableOAuth2Client() {
this.context = new AnnotationConfigServletWebServerApplicationContext();
this.context.register(ClientConfiguration.class, MinimalSecureWebApplication.class);
TestPropertyValues
.of("security.oauth2.client.clientId=client", "security.oauth2.client.grantType=client_credentials")
.applyTo(this.context);
ConfigurationPropertySources.attach(this.context.getEnvironment());
this.context.refresh();
// The primary context is fine (not session scoped):
OAuth2ClientContext bean = this.context.getBean(OAuth2ClientContext.class);
assertThat(bean.getAccessTokenRequest()).isNotNull();
assertThat(countBeans(ClientCredentialsResourceDetails.class)).isEqualTo(1);
// Kind of a bug (should ideally be 1), but the cause is in Spring OAuth2 (there
// is no need for the extra session-scoped bean). What this test proves is that
// even if the user screws up and does @EnableOAuth2Client for client
// credentials,
// it will still just about work (because of the @Primary annotation on the
// Boot-created instance of OAuth2ClientContext).
assertThat(countBeans(OAuth2ClientContext.class)).isEqualTo(2);
}
@Test
public void testAuthorizationServerOverride() {
this.context = new AnnotationConfigServletWebServerApplicationContext();
TestPropertyValues.of("security.oauth2.resourceId:resource-id").applyTo(this.context);
this.context.register(AuthorizationAndResourceServerConfiguration.class, CustomAuthorizationServer.class,
MinimalSecureWebApplication.class);
this.context.refresh();
BaseClientDetails config = new BaseClientDetails();
config.setClientId("client");
config.setClientSecret("secret");
config.setResourceIds(Arrays.asList("resource-id"));
config.setAuthorizedGrantTypes(Arrays.asList("password"));
config.setAuthorities(AuthorityUtils.commaSeparatedStringToAuthorityList("USER"));
config.setScope(Arrays.asList("read"));
assertThat(countBeans(AUTHORIZATION_SERVER_CONFIG)).isEqualTo(1);
assertThat(countBeans(CustomAuthorizationServer.class)).isEqualTo(1);
assertThat(countBeans(RESOURCE_SERVER_CONFIG)).isEqualTo(1);
verifyAuthentication(config);
}
@Test
public void authorizationServerWhenJwtKeyStoreConfigurationAndCustomAuthorizationServerThenConfiguresJwt() {
this.context = new AnnotationConfigServletWebServerApplicationContext();
TestPropertyValues.of(
"security.oauth2.authorization.jwt.keyStore:classpath:"
+ "org/springframework/boot/autoconfigure/security/oauth2/authserver/keystore.jks",
"security.oauth2.authorization.jwt.keyStorePassword:changeme",
"security.oauth2.authorization.jwt.keyAlias:jwt").applyTo(this.context);
this.context.register(AuthorizationServerConfiguration.class, CustomAuthorizationServer.class,
MinimalSecureWebApplication.class);
this.context.refresh();
assertThat(countBeans(RESOURCE_SERVER_CONFIG)).isEqualTo(0);
assertThat(countBeans(AUTHORIZATION_SERVER_CONFIG)).isEqualTo(1);
assertThat(countBeans(CustomAuthorizationServer.class)).isEqualTo(1);
assertThat(countBeans(JwtAccessTokenConverter.class)).isEqualTo(1);
}
@Override
public void initialize()
throws ContainerInitializationException {
Timer.start("SPRINGBOOT2_COLD_START");
SpringApplicationBuilder builder = new SpringApplicationBuilder(getEmbeddedContainerClasses())
.web(springWebApplicationType); // .REACTIVE, .SERVLET
if (springProfiles != null) {
builder.profiles(springProfiles);
}
applicationContext = builder.run();
if (springWebApplicationType == WebApplicationType.SERVLET) {
((AnnotationConfigServletWebServerApplicationContext)applicationContext).setServletContext(getServletContext());
AwsServletRegistration reg = (AwsServletRegistration)getServletContext().getServletRegistration(DISPATCHER_SERVLET_REGISTRATION_NAME);
if (reg != null) {
reg.setLoadOnStartup(1);
}
}
super.initialize();
initialized = true;
Timer.stop("SPRINGBOOT2_COLD_START");
}
@Test
public void methodSecurityExpressionHandlerIsConfiguredWithRoleHierarchyFromTheContext() {
this.context = new AnnotationConfigServletWebServerApplicationContext();
this.context.register(RoleHierarchyConfiguration.class, AuthorizationAndResourceServerConfiguration.class,
MinimalSecureWebApplication.class);
this.context.refresh();
PreInvocationAuthorizationAdvice advice = this.context.getBean(PreInvocationAuthorizationAdvice.class);
MethodSecurityExpressionHandler expressionHandler = (MethodSecurityExpressionHandler) ReflectionTestUtils
.getField(advice, "expressionHandler");
RoleHierarchy roleHierarchy = (RoleHierarchy) ReflectionTestUtils.getField(expressionHandler, "roleHierarchy");
assertThat(roleHierarchy).isSameAs(this.context.getBean(RoleHierarchy.class));
}
@Test
public void methodSecurityExpressionHandlerIsConfiguredWithPermissionEvaluatorFromTheContext() {
this.context = new AnnotationConfigServletWebServerApplicationContext();
this.context.register(PermissionEvaluatorConfiguration.class, AuthorizationAndResourceServerConfiguration.class,
MinimalSecureWebApplication.class);
this.context.refresh();
PreInvocationAuthorizationAdvice advice = this.context.getBean(PreInvocationAuthorizationAdvice.class);
MethodSecurityExpressionHandler expressionHandler = (MethodSecurityExpressionHandler) ReflectionTestUtils
.getField(advice, "expressionHandler");
PermissionEvaluator permissionEvaluator = (PermissionEvaluator) ReflectionTestUtils.getField(expressionHandler,
"permissionEvaluator");
assertThat(permissionEvaluator).isSameAs(this.context.getBean(PermissionEvaluator.class));
}
@Test
public void testDisablingResourceServer() {
this.context = new AnnotationConfigServletWebServerApplicationContext();
this.context.register(AuthorizationServerConfiguration.class, MinimalSecureWebApplication.class);
this.context.refresh();
assertThat(countBeans(RESOURCE_SERVER_CONFIG)).isEqualTo(0);
assertThat(countBeans(AUTHORIZATION_SERVER_CONFIG)).isEqualTo(1);
}
@Test
public void testClientIsNotResourceServer() {
this.context = new AnnotationConfigServletWebServerApplicationContext();
this.context.register(ClientConfiguration.class, MinimalSecureWebApplication.class);
this.context.refresh();
assertThat(countBeans(RESOURCE_SERVER_CONFIG)).isEqualTo(0);
assertThat(countBeans(AUTHORIZATION_SERVER_CONFIG)).isEqualTo(0);
// Scoped target and proxy:
assertThat(countBeans(OAuth2ClientContext.class)).isEqualTo(2);
}
@Test
public void testCanUseClientCredentials() {
this.context = new AnnotationConfigServletWebServerApplicationContext();
this.context.register(TestSecurityConfiguration.class, MinimalSecureWebApplication.class);
TestPropertyValues
.of("security.oauth2.client.clientId=client", "security.oauth2.client.grantType=client_credentials")
.applyTo(this.context);
ConfigurationPropertySources.attach(this.context.getEnvironment());
this.context.refresh();
OAuth2ClientContext bean = this.context.getBean(OAuth2ClientContext.class);
assertThat(bean.getAccessTokenRequest()).isNotNull();
assertThat(countBeans(ClientCredentialsResourceDetails.class)).isEqualTo(1);
assertThat(countBeans(OAuth2ClientContext.class)).isEqualTo(1);
}
@Test
public void testDisablingAuthorizationServer() {
this.context = new AnnotationConfigServletWebServerApplicationContext();
this.context.register(ResourceServerConfiguration.class, MinimalSecureWebApplication.class);
TestPropertyValues.of("security.oauth2.resource.jwt.keyValue:DEADBEEF").applyTo(this.context);
ConfigurationPropertySources.attach(this.context.getEnvironment());
this.context.refresh();
assertThat(countBeans(RESOURCE_SERVER_CONFIG)).isEqualTo(1);
assertThat(countBeans(AUTHORIZATION_SERVER_CONFIG)).isEqualTo(0);
assertThat(countBeans(UserApprovalHandler.class)).isEqualTo(0);
assertThat(countBeans(DefaultTokenServices.class)).isEqualTo(1);
}
@Test
public void testResourceServerOverride() {
this.context = new AnnotationConfigServletWebServerApplicationContext();
this.context.register(AuthorizationAndResourceServerConfiguration.class, CustomResourceServer.class,
MinimalSecureWebApplication.class);
this.context.refresh();
ClientDetails config = this.context.getBean(ClientDetails.class);
assertThat(countBeans(AUTHORIZATION_SERVER_CONFIG)).isEqualTo(1);
assertThat(countBeans(CustomResourceServer.class)).isEqualTo(1);
assertThat(countBeans(RESOURCE_SERVER_CONFIG)).isEqualTo(1);
verifyAuthentication(config);
}
@Test
public void testDefaultPrePostSecurityAnnotations() {
this.context = new AnnotationConfigServletWebServerApplicationContext();
this.context.register(AuthorizationAndResourceServerConfiguration.class, MinimalSecureWebApplication.class);
this.context.refresh();
this.context.getBean(OAuth2MethodSecurityConfiguration.class);
ClientDetails config = this.context.getBean(ClientDetails.class);
DelegatingMethodSecurityMetadataSource source = this.context
.getBean(DelegatingMethodSecurityMetadataSource.class);
List<MethodSecurityMetadataSource> sources = source.getMethodSecurityMetadataSources();
assertThat(sources.size()).isEqualTo(1);
assertThat(sources.get(0).getClass().getName())
.isEqualTo(PrePostAnnotationSecurityMetadataSource.class.getName());
verifyAuthentication(config);
}
@Test
public void testClassicSecurityAnnotationOverride() {
this.context = new AnnotationConfigServletWebServerApplicationContext();
this.context.register(SecuredEnabledConfiguration.class, MinimalSecureWebApplication.class);
this.context.refresh();
this.context.getBean(OAuth2MethodSecurityConfiguration.class);
ClientDetails config = this.context.getBean(ClientDetails.class);
DelegatingMethodSecurityMetadataSource source = this.context
.getBean(DelegatingMethodSecurityMetadataSource.class);
List<MethodSecurityMetadataSource> sources = source.getMethodSecurityMetadataSources();
assertThat(sources.size()).isEqualTo(1);
assertThat(sources.get(0).getClass().getName())
.isEqualTo(SecuredAnnotationSecurityMetadataSource.class.getName());
verifyAuthentication(config, HttpStatus.OK);
}
@Test
public void testJsr250SecurityAnnotationOverride() {
this.context = new AnnotationConfigServletWebServerApplicationContext();
this.context.register(Jsr250EnabledConfiguration.class, MinimalSecureWebApplication.class);
this.context.refresh();
this.context.getBean(OAuth2MethodSecurityConfiguration.class);
ClientDetails config = this.context.getBean(ClientDetails.class);
DelegatingMethodSecurityMetadataSource source = this.context
.getBean(DelegatingMethodSecurityMetadataSource.class);
List<MethodSecurityMetadataSource> sources = source.getMethodSecurityMetadataSources();
assertThat(sources.size()).isEqualTo(1);
assertThat(sources.get(0).getClass().getName()).isEqualTo(Jsr250MethodSecurityMetadataSource.class.getName());
verifyAuthentication(config, HttpStatus.OK);
}
@Test
public void testMethodSecurityBackingOff() {
this.context = new AnnotationConfigServletWebServerApplicationContext();
this.context.register(CustomMethodSecurity.class, TestSecurityConfiguration.class,
MinimalSecureWebApplication.class);
this.context.refresh();
DelegatingMethodSecurityMetadataSource source = this.context
.getBean(DelegatingMethodSecurityMetadataSource.class);
List<MethodSecurityMetadataSource> sources = source.getMethodSecurityMetadataSources();
assertThat(sources.size()).isEqualTo(1);
assertThat(sources.get(0).getClass().getName())
.isEqualTo(PrePostAnnotationSecurityMetadataSource.class.getName());
}
@Test
public void resourceServerConditionWhenJwkConfigurationPresentShouldMatch() throws Exception {
this.context = new AnnotationConfigServletWebServerApplicationContext();
TestPropertyValues.of("security.oauth2.resource.jwk.key-set-uri:https://idp.example.com/token_keys")
.applyTo(this.context);
this.context.register(ResourceServerConfiguration.class, MinimalSecureWebApplication.class);
this.context.refresh();
assertThat(countBeans(RESOURCE_SERVER_CONFIG)).isEqualTo(1);
}
@Test
public void authorizationServerWhenUsingJwtConfigurationThenConfiguresJwt() {
this.context = new AnnotationConfigServletWebServerApplicationContext();
this.context.register(AuthorizationServerConfiguration.class, MinimalSecureWebApplication.class);
TestPropertyValues.of("security.oauth2.authorization.jwt.keyValue:DEADBEEF").applyTo(this.context);
ConfigurationPropertySources.attach(this.context.getEnvironment());
this.context.refresh();
assertThat(countBeans(RESOURCE_SERVER_CONFIG)).isEqualTo(0);
assertThat(countBeans(AUTHORIZATION_SERVER_CONFIG)).isEqualTo(1);
assertThat(countBeans(JwtAccessTokenConverter.class)).isEqualTo(1);
}
@Test
public void authorizationServerWhenJwtConfigurationAndCustomAuthorizationServerThenConfiguresJwt() {
this.context = new AnnotationConfigServletWebServerApplicationContext();
TestPropertyValues.of("security.oauth2.authorization.jwt.keyValue:DEADBEEF").applyTo(this.context);
this.context.register(AuthorizationServerConfiguration.class, CustomAuthorizationServer.class,
MinimalSecureWebApplication.class);
this.context.refresh();
assertThat(countBeans(RESOURCE_SERVER_CONFIG)).isEqualTo(0);
assertThat(countBeans(AUTHORIZATION_SERVER_CONFIG)).isEqualTo(1);
assertThat(countBeans(CustomAuthorizationServer.class)).isEqualTo(1);
assertThat(countBeans(JwtAccessTokenConverter.class)).isEqualTo(1);
}
public TaskScheduleCommandTemplate(JLineShellComponent dataFlowShell, ApplicationContext applicationContext) {
this.dataFlowShell = dataFlowShell;
ConfigurableListableBeanFactory beanFactory = ((AnnotationConfigServletWebServerApplicationContext) applicationContext)
.getBeanFactory();
schedule = Mockito.mock(SchedulerService.class);
BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(TaskSchedulerController.class);
builder.addConstructorArgValue(schedule);
DefaultListableBeanFactory listableBeanFactory = (DefaultListableBeanFactory) beanFactory;
listableBeanFactory.setAllowBeanDefinitionOverriding(true);
listableBeanFactory.registerBeanDefinition("taskSchedulerController", builder.getBeanDefinition());
}
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if ("adminDispatcherServlet".equals(beanName)) {
DispatcherServlet dispatcherServlet = (DispatcherServlet) bean;
AnnotationConfigServletWebServerApplicationContext context = (AnnotationConfigServletWebServerApplicationContext) dispatcherServlet.getWebApplicationContext();
context.scan(packagesToScan);
this.processed = true;
}
return bean;
}
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if (DispatcherServletAutoConfiguration.DEFAULT_DISPATCHER_SERVLET_BEAN_NAME.equals(beanName)) {
DispatcherServlet dispatcherServlet = (DispatcherServlet) bean;
AnnotationConfigServletWebServerApplicationContext context = (AnnotationConfigServletWebServerApplicationContext) dispatcherServlet.getWebApplicationContext();
context.scan(packagesToScan);
this.processed = true;
}
return bean;
}
@Bean(name = DispatcherServletAutoConfiguration.DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)
public DispatcherServlet guestDispatcherServlet() {
AnnotationConfigServletWebServerApplicationContext context = new AnnotationConfigServletWebServerApplicationContext();
context.setResourceLoader(getResourceLoader());
context.register(WebGuestConfiguration.class);
WallRideDispatcherServlet dispatcherServlet = new WallRideDispatcherServlet(context);
dispatcherServlet.setDetectParentHandlerMappings(true);
return dispatcherServlet;
}
@Bean
public DispatcherServlet adminDispatcherServlet() {
AnnotationConfigServletWebServerApplicationContext context = new AnnotationConfigServletWebServerApplicationContext();
context.setResourceLoader(getResourceLoader());
context.register(WebAdminConfiguration.class);
WallRideDispatcherServlet dispatcherServlet = new WallRideDispatcherServlet(context);
return dispatcherServlet;
}
@Override
public void onApplicationEvent(ApplicationEvent event) {
if (event instanceof ApplicationContextInitializedEvent) {
ApplicationContextInitializedEvent initialized = (ApplicationContextInitializedEvent) event;
ConfigurableApplicationContext context = initialized.getApplicationContext();
if (!(context instanceof GenericApplicationContext)) {
throw new IllegalStateException("ApplicationContext must be a GenericApplicationContext");
}
if (!isEnabled(context.getEnvironment())) {
return;
}
GenericApplicationContext generic = (GenericApplicationContext) context;
ConditionService conditions = initialize(generic);
functional(generic, conditions);
apply(generic, initialized.getSpringApplication(), conditions);
}
else if (event instanceof ApplicationEnvironmentPreparedEvent) {
ApplicationEnvironmentPreparedEvent prepared = (ApplicationEnvironmentPreparedEvent) event;
if (!isEnabled(prepared.getEnvironment())) {
return;
}
logger.info("Preparing application context");
SpringApplication application = prepared.getSpringApplication();
findInitializers(application);
WebApplicationType type = getWebApplicationType(application, prepared.getEnvironment());
Class<?> contextType = getApplicationContextType(application);
if (type == WebApplicationType.NONE) {
if (contextType == AnnotationConfigApplicationContext.class || contextType == null) {
application.setApplicationContextClass(GenericApplicationContext.class);
}
}
else if (type == WebApplicationType.REACTIVE) {
if (contextType == AnnotationConfigReactiveWebApplicationContext.class || contextType == null) {
application.setApplicationContextClass(ReactiveWebServerApplicationContext.class);
}
}
else if (type == WebApplicationType.SERVLET) {
if (contextType == AnnotationConfigServletWebServerApplicationContext.class || contextType == null) {
application.setApplicationContextClass(ServletWebServerApplicationContext.class);
}
}
}
}
public static void main(String[] args) {
AnnotationConfigServletWebServerApplicationContext a;
SpringApplication.run(SpringcustomizeApplication.class, args);
}