ServerHttpSecurity bean not found - spring

I have a Security config class that has a SecurityWebFilterChain bean in it. This bean requires a ServerHttpSecuirty instance but spring says that it cannot find any beans of that type though there is one created in the external library (org.springframework.security.config.annotation.web.reactive.ServerHttpSecurityConfiguration). I have seen this issue on a github page and they said try a different version but I am using spring boot 2.4.5 so it should work.
My Security Config class:
#Configuration
public class SecurityConfig {
#Bean
SecurityWebFilterChain springWebFilterChain(ServerHttpSecurity http,
JwtTokenProvider tokenProvider,
ReactiveAuthenticationManager reactiveAuthenticationManager) {
final String TAG_SERVICES = "/api/**";
return http.csrf(ServerHttpSecurity.CsrfSpec::disable)
.httpBasic(ServerHttpSecurity.HttpBasicSpec::disable)
.authenticationManager(reactiveAuthenticationManager)
.securityContextRepository(NoOpServerSecurityContextRepository.getInstance())
.authorizeExchange(it -> it
.pathMatchers(HttpMethod.POST, TAG_SERVICES).hasAnyRole("USER","ADMIN")
.pathMatchers(HttpMethod.PUT, TAG_SERVICES).hasAnyRole("USER","ADMIN")
.pathMatchers(HttpMethod.GET, TAG_SERVICES).hasAnyRole("USER","ADMIN")
.pathMatchers(HttpMethod.DELETE, TAG_SERVICES).hasAnyRole("USER","ADMIN")
.pathMatchers(TAG_SERVICES).authenticated()
.anyExchange().permitAll()
)
.addFilterAt(new JwtTokenAuthenticationFilter(tokenProvider), SecurityWebFiltersOrder.HTTP_BASIC)
.build();
}
}
My application class
#ConfigurationPropertiesScan
#SpringBootApplication(exclude={DataSourceAutoConfiguration.class})
public class TestPlatformBackendApplication {
public static void main(String[] args) {
SpringApplication.run(TestPlatformBackendApplication.class, args);
}
}
External Library Bean:
#Bean({"org.springframework.security.config.annotation.web.reactive.HttpSecurityConfiguration.httpSecurity"})
#Scope("prototype")
ServerHttpSecurity httpSecurity() {
ServerHttpSecurityConfiguration.ContextAwareServerHttpSecurity http = new ServerHttpSecurityConfiguration.ContextAwareServerHttpSecurity();
return http.authenticationManager(this.authenticationManager()).headers().and().logout().and();
}

As Toerktumlare recommended in the comments (1, 2) I added #EnableWebFluxSecurity to my security config:
#Configuration
#EnableWebFluxSecurity
public class SecurityConfig {
But I also added the following to my exclude in the #SpringBootApplication annotation.
#ConfigurationPropertiesScan
#SpringBootApplication(exclude={DataSourceAutoConfiguration.class, SecurityAutoConfiguration.class, ManagementWebSecurityAutoConfiguration.class})
public class TestPlatformBackendApplication {
public static void main(String[] args) {
SpringApplication.run(TestPlatformBackendApplication.class, args);
}
}

Related

Spring interface injection from external jar

I have spring API based authentication classes in external library,
Below are some of the classes in external library,
package com.security;
import org.springframework.security.authentication.AuthenticationProvider;
#Component
public class ApiKeyAuthenticationProvider implements AuthenticationProvider {
private static final Logger LOGGER = LoggerFactory.getLogger(ApiKeyAuthenticationProvider.class);
private ApiAuthCredentialsConfig apiAuthCredentialsConfig;
public ApiKeyAuthenticationProvider(ApiAuthCredentialsConfig apiAuthCredentialsConfig) {
this.apiAuthCredentialsConfig = apiAuthCredentialsConfig;
}
}
ApiAuthCredentialsConfig:
package com.security;
public interface ApiAuthCredentialsConfig {
String getAuthToken();
String getAuthTokenHeaderName();
}
And in the repo I have added the above external library as a gradle dependency.
I have below changes in actual repo.
#Component
#Data
public class ApiAuthenticationConfig implements ApiAuthCredentialsConfig {
#Value("${auth-token}")
private String authToken;
#Value("${auth-token-header-name}")
private String authTokenHeaderName;
}
SecurityConfig:
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private ApiKeyAuthenticationProvider apiKeyAuthenticationProvider;
#Override
public void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.
antMatcher("/**").
csrf().disable().
sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).
and().addFilterBefore(new ApiKeyAuthenticationFilter(authenticationManager(), apiKeyAuthenticationProvider.getHeaderName()), AnonymousAuthenticationFilter.class)
.authorizeRequests().anyRequest().authenticated();
}
#Bean
public AuthenticationManager authenticationManager() {
return new ProviderManager(Collections.singletonList(apiKeyAuthenticationProvider));
}
}
Application:
#SpringBootApplication(scanBasePackages = {"com.security"})
#EnableSwagger2
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
When I run the application its failing with below error
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 0 of constructor in com.security.ApiKeyAuthenticationProvider required a bean of type 'com.security.ApiAuthCredentialsConfig' that could not be found.
How to resolve this issue?
After the above comment, I realized that ApiAuthenticationConfig is not in the same package as ApiAuthCredentialsConfig, after I moved ApiAuthenticationConfig to com.security package it started working.

How to pass parameters from custom annotation to WebSecurityConfigurer in library

Hi we are building custom spring security library
we need to pass {"/v1","/v2"} paths through #EnableMySpringSecurity(excludePaths = {"/v1","/v2"}) which is present in the main project to library websecurity so we can ignore those endpoints from security
#EnableMySpringSecurity(excludePaths = {"/v1","/v2"})
#EnableWebMvc
public class WebAppConfiguration extends BaseWebAppConfiguration {
Websecurity Configuration from custom JAR
#EnableWebSecurity(debug = true)
#Configuration
#EnableGlobalMethodSecurity(prePostEnabled = true)
public static class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
public void configure(WebSecurity web){
web.ignoring().antMatchers(excludePaths );
How to pass values that are passed from #EnableMYSpringSecurity to the webSecuirty web.ignoring.antMatchers
our annotation configuration
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.TYPE)
public #interface EnableMySpringSecurity {
String[] excludePaths() default {};
}
I have tried ApplicationStartupListener but problem with this is, it is initialized after websecuirty configuration
public class ApplicationStartupListener implements
ApplicationListener<ContextRefreshedEvent> {
private ApplicationContext context;
private EnableMySSAnnotationProcessor processor;
public ApplicationStartupListener(ApplicationContext context,
EnableMySSAnnotationProcessor processor) {
this.context = context;
this.processor = processor;
}
#Override
public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
Optional<EnableMySpringSecurity> annotation =
context.getBeansWithAnnotation(EnableMySpringSecurity.class).keySet().stream()
.map(key -> context.findAnnotationOnBean(key, EnableMySpringSecurity.class))
.findFirst();
annotation.ifPresent(enableMySpringSecurity-> processor.process(enableMySpringSecurity));
}
}
One way you can do this is with the #Import annotation:
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.TYPE)
#Import(MyWebSecurityConfiguration.class)
#EnableWebSecurity
public #interface EnableMyWebSecurity {
String[] paths() default [];
}
and then the ImportAware interface:
#Configuration
public class MyWebSecurityConfiguration implements ImportAware {
private String[] paths;
#Bean
WebSecurityCustomizer paths() {
return (web) -> web.ignoring().antMatchers(paths);
}
#Override
public void setImportMetadata(AnnotationMetadata importMetadata) {
EnableMyWebSecurity annotation = importMetadata
.getAnnotations().get(EnableMyWebSecurity.class).synthesize();
this.paths = annotations.paths();
}
}
Note, by the way, that when you exclude paths, Spring Security cannot add security headers as part of the response. If you want those endpoints to be protected by Spring Security, but public, then consider instead:
#Configuration
public class MyWebSecurityConfiguration implements ImportAware {
private String[] paths;
#Bean
#Order(1)
SecurityFilterChain paths(HttpSecurity http) {
http
.requestMatchers((requests) -> requests.antMatchers(paths))
.authorizeRequests((authorize) -> authorize
.anyRequest().permitAll()
);
return http.build();
}
#Override
public void setImportMetadata(AnnotationMetadata importMetadata) {
EnableMyWebSecurity annotation = importMetadata
.getAnnotations().get(EnableMyWebSecurity.class).synthesize();
this.paths = annotations.paths();
}
}
The benefit of the second approach is that Spring Security won't require authentication, but will add secure response headers.
The solution provided #jzheaux works
There is one more solution - is to use application context getBeansWithAnnoation
#EnableWebSecurity(debug = true)
#Configuration
#Order(2147483640)
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private ApplicationContext appContext;
#Override
public void configure(WebSecurity web){
Map<String,Object> beanMap = this.appContext.getBeansWithAnnotation(EnableMYSpringSecurity.class);
if(!beanMap.isEmpty()){
EnableMYSpringSecurityanno = (EnableMYSpringSecurity) this.appContext.findAnnotationOnBean(beanMap.keySet()
.iterator()
.next(),EnableMYSpringSecurity.class);
String[] permitPaths = anno.excludePaths();
Arrays.stream(permitPaths).forEach(System.out::println);
}

Spring boot: Log file has get requests to static files

I have configured my app using
#Configuration
#EnableWebSecurity
#Slf4j
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {...}
Inside configure method, allowed the static content.
http .httpBasic().and()
.csrf().disable()
.authorizeRequests()
.antMatchers("/**/*.js", "/resources/static/**", "/static/**", "/**/*.jpg", "/**/*.svg", "/**/*.ico", "/**/*.gif", "/**/*.css", "/register")
.permitAll()
application.properties :
logging.level.web=debug
logging.level.org.springframework.web=debug
The problem i am having is that my log file is crowded by get requests to the static resources
I am just interested in logging access to controllers and not static files.
Is there something i need to configure to exclude the logging of access to static resources?
I have also tried
#Configuration
public class StaticConfig implements WebMvcConfigurer {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
if (!registry.hasMappingForPattern("/static/**")) {
registry.addResourceHandler("/static/**")
.addResourceLocations("/static/");
}
}
}
Issue
You have enabled debug level logging for org.springframework.web package, so it will log everything
Try this solution
Remove the debug level logging for org.springframework.web
Create a subclass of CommonsRequestLoggingFilter
public class CustomRequestLoggingFilter extends CommonsRequestLoggingFilter {
#Override
protected boolean shouldLog(HttpServletRequest request) {
return logger.isDebugEnabled() &&
!request.getRequestURL().toString().contains("/static")
}
}
Create that filter as a bean
#Configuration
public class RequestLoggingFilterConfig {
#Bean
public CustomRequestLoggingFilter logFilter() {
CustomRequestLoggingFilter filter
= new CustomRequestLoggingFilter();
filter.setIncludeQueryString(true);
filter.setIncludePayload(false);
filter.setMaxPayloadLength(10000);
filter.setIncludeHeaders(false);
filter.setAfterMessagePrefix("REQUEST DATA : ");
return filter;
}
}
Add the following to application.properties
logging.level.<package of your filter>.CustomRequestLoggingFilter=DEBUG

Spring Boot app requires a bean annotated with #Primary to start

I'm seeing the following message on a Spring Boot app startup:
> *************************** APPLICATION FAILED TO START
> ***************************
>
> Description:
>
> Field oauthProps in com.example.authservice.AuthorizationServerConfig
> required a single bean, but 2 were found:
> - OAuthProperties: defined in file [/Users/simeonleyzerzon/abc/spring-security/spring-security-5-oauth-client/auth-service/target/classes/com/example/authservice/config/OAuthProperties.class]
> - kai-com.example.authservice.config.OAuthProperties: defined in null
>
>
> Action:
>
> Consider marking one of the beans as #Primary, updating the consumer
> to accept multiple beans, or using #Qualifier to identify the bean
> that should be consumed
I'm wondering what's causing the duplication of that bean and how one can remove it without the necessity of using the #Primary annotation? Not sure where the kai-com package(?) from the above is coming from.
Here's the bean in question:
package com.example.authservice.config;
//#Primary
#Component
#ConfigurationProperties(prefix="kai")
#Setter #Getter
public class OAuthProperties {
private String[] redirectUris;
private String clientId;
private String clientSecret;
private final Token token = new Token();
#Setter #Getter
public static class Token{
private String value;
private String type="";
}
}
and the app/config, etc.:
package com.example.authservice;
import ...
#SpringBootApplication
public class AuthServiceApplication {
public static void main(String[] args) {
SpringApplication.run(AuthServiceApplication.class, args);
}
}
#Controller
class MainController {
#GetMapping("/")
String index() {
return "index";
}
}
#RestController
class ProfileRestController {
#GetMapping("/resources/userinfo")
Map<String, String> profile(Principal principal) {
return Collections.singletonMap("name", principal.getName());
}
}
#Configuration
#EnableResourceServer
class ResourceServerConfig extends ResourceServerConfigurerAdapter {
#Override
public void configure(HttpSecurity http) throws Exception {
http
.antMatcher("/resources/**")
.authorizeRequests()
.mvcMatchers("/resources/userinfo").access("#oauth2.hasScope('profile')");
}
}
#Configuration
#EnableAuthorizationServer
#EnableConfigurationProperties(OAuthProperties.class)
class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
#Autowired private OAuthProperties oauthProps;
private final AuthenticationManager authenticationManager;
AuthorizationServerConfig(AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
#Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients
.inMemory()
.withClient(oauthProps.getClientId())
.secret(oauthProps.getClientSecret())
.authorizedGrantTypes("authorization_code")
.scopes("profile")
.redirectUris(oauthProps.getRedirectUris());
}
#Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(this.authenticationManager);
if (oauthProps.getToken().getType().equals("jwt")) {
endpoints.tokenStore(this.tokenStore()).accessTokenConverter(jwtAccessTokenConverter());
}else {
endpoints.tokenEnhancer(eapiTokenEnhancer());
}
}
TokenEnhancer eapiTokenEnhancer() {
return new TokenEnhancer() {
#Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
DefaultOAuth2AccessToken result = new DefaultOAuth2AccessToken(accessToken);
result.setValue(oauthProps.getToken().getValue());
return result;
}
};
}
#Bean
JwtAccessTokenConverter jwtAccessTokenConverter() {
KeyStoreKeyFactory factory = new KeyStoreKeyFactory(new ClassPathResource(".keystore-oauth2-demo"), //keystore
"admin1234".toCharArray()); //storepass
JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
jwtAccessTokenConverter.setKeyPair(factory.getKeyPair("oauth2-demo-key")); //alias
return jwtAccessTokenConverter;
}
#Bean
TokenStore tokenStore() {
return new JwtTokenStore(this.jwtAccessTokenConverter());
}
}
#Service
class SimpleUserDetailsService implements UserDetailsService {
private final Map<String, UserDetails> users = new ConcurrentHashMap<>();
SimpleUserDetailsService() {
Arrays.asList("josh", "rob", "joe")
.forEach(username -> this.users.putIfAbsent(
username, new User(username, "pw", true, true, true, true, AuthorityUtils.createAuthorityList("USER","ACTUATOR"))));
}
#Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
return this.users.get(username);
}
}
#Configuration
#EnableWebSecurity
class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin();
}
}
Eclipse too seems to be only aware of a single instance of the bean:
When using #EnableConfigurationProperties with #ConfigurationProperties you will get a bean named <prefix>-<fqn>, the kai-com.example.authservice.config.OAuthProperties. (See also the reference guide).
When the #ConfigurationProperties bean is registered that way, the bean has a conventional name: <prefix>-<fqn>, where <prefix> is the environment key prefix specified in the #ConfigurationProperties annotation and <fqn> is the fully qualified name of the bean. If the annotation does not provide any prefix, only the fully qualified name of the bean is used.
The bean name in the example above is acme-com.example.AcmeProperties. (From the Reference Guide).
The #Component will lead to another registration of the bean with the regular name of the classname with a lowercase character. The other instance of your properties.
the #EnableConfigurationProperties annotation is also automatically applied to your project so that any existing bean annotated with #ConfigurationProperties is configured from the Environment. You could shortcut MyConfiguration by making sure AcmeProperties is already a bean, as shown in the following example: (From the Reference Guide).
The key here is that #EnableConfigurationProperties is already globally applied and processes any bean annotated with #ConfigurationProperties.
So basically you where mixing the 2 ways of using #ConfigurationProperties and Spring Boot 2 now prevents that misuse. This way you write better code (and reduce the memory footprint and performance slightly).
So either remove the #Component or remove the #EnableConfigurationProperties, either way will work.
The following change (removing of #EnableConfigurationProperties) seems to help relieving the need for the #Primary annotation:
#Configuration
#EnableAuthorizationServer
//#EnableConfigurationProperties(OAuthProperties.class)
class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
#Autowired private OAuthProperties oauthProps;
Perhaps someone can describe the internal Spring mechanics of secondary bean creation (and its namespace/package assignment) by that annotation which seemingly causes the collision with the #Autowired one, or point me to the appropriate documentation of this behavior.

#Autowired does not work with #Configurable

I am trying to do an image upload API. I have a ImageUpload task as follows,
#Component
#Configurable(preConstruction = true)
#Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class ImageUploadTask implements Callable<JSONObject> {
#Autowired
private ImageUploadService imageUploadService;
#Override
public JSONObject call() throws Exception {
....
//Upload image via `imageUploadService`
imageUploadService.getService().path('...').post('...'); // Getting null pointer here for imageUploadService which is a WebTarget
}
}
The ImageUploadService looks like the below,
#Component
public class ImageUploadService {
#Inject
#EndPoint(name="imageservice") //Custom annotation, battle tested and works well for all other services
private WebTarget imageservice;
public WebTarget getService() {
return imageservice;
}
}
Here is the spring boot application class,
#ComponentScan
#EnableSpringConfigured
#EnableLoadTimeWeaving(aspectjWeaving=EnableLoadTimeWeaving.AspectJWeaving.ENABLED)
#EnableAutoConfiguration
public class ImageApplication extends SpringBootServletInitializer {
#Bean
public InstrumentationLoadTimeWeaver loadTimeWeaver() throws Throwable {
InstrumentationLoadTimeWeaver loadTimeWeaver = new InstrumentationLoadTimeWeaver();
return loadTimeWeaver;
}
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
super.onStartup(servletContext);
servletContext.addListener(new RequestContextListener());
}
public static void main(String[] args) throws IOException {
SpringApplication.run(ImageApplication.class);
}
}
Additional information :
Spring version of dependencies are at 4.2.5.RELEASE
pom.xml has dependencies added for spring-aspects and
spring-instrument
I am getting a NullPointerException in ImageUploadTask. My suspicion is that #Autowired doesn't work as expected.
Why wouldn't work and how do I fix this?
Is it mandatory to use #Autowired only when I use #Conigurable, why not use #Inject? (though I tried it and getting same NPE)
By default the autowiring for the #Configurable is off i.e. Autowire.NO beacuse of which the imageUploadService is null
Thus update the code to explicity enable it either as BY_NAME or BY_TYPE as below.
#Component
#Configurable(preConstruction = true, autowire = Autowire.BY_NAME)
#Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class ImageUploadTask implements Callable<JSONObject> { .... }
Rest of the configuration viz. enabling load time weaving seems fine.
Also regarding #Inject annotation have a look here which pretty much explains the difference (or similarity perhaps)

Resources