Spring security and keyclock - ServerHttpSecurity error - spring

I'm trying to add Spring Security to my Spring Boot application. I've created new SecurityConfig class and I've added the code below:
#Configuration
#EnableWebSecurity
public class SecurityConfig {
#Bean
public SecurityWebFilterChain configSecurity(ServerHttpSecurity http) {
return http
.authorizeExchange(exchange -> exchange.matchers(EndpointRequest.toAnyEndpoint()).permitAll().anyExchange().authenticated())
.oauth2ResourceServer(ServerHttpSecurity.OAuth2ResourceServerSpec::jwt)
.build();
}
}
When I try to start the application I get the error:
2021-04-08 08:58:47.828 INFO 3040 --- [ main]
o.s.s.web.DefaultSecurityFilterChain : Will secure any request
with
[org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter#6089c1e3,
org.springframework.security.web.context.SecurityContextPersistenceFilter#4bba628,
org.springframework.security.web.header.HeaderWriterFilter#47b4fcd5,
org.springframework.security.web.csrf.CsrfFilter#439acac0,
org.springframework.security.web.authentication.logout.LogoutFilter#6af447b6,
org.springframework.security.oauth2.server.resource.web.BearerTokenAuthenticationFilter#5679e464,
org.springframework.security.web.savedrequest.RequestCacheAwareFilter#4420f4d4,
org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter#517594dd,
org.springframework.security.web.authentication.AnonymousAuthenticationFilter#67231d8d,
org.springframework.security.web.session.SessionManagementFilter#59b5251d,
org.springframework.security.web.access.ExceptionTranslationFilter#7d6b0636,
org.springframework.security.web.access.intercept.FilterSecurityInterceptor#4b50ebea]
2021-04-08 08:58:47.883 WARN 3040 --- [ main]
ConfigServletWebServerApplicationContext : Exception encountered
during context initialization - cancelling refresh attempt:
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'configSecurity' defined in class path
resource [it/config/SecurityConfig.class]:
Unsatisfied dependency expressed through method 'configSecurity'
parameter 0; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type
'org.springframework.security.config.web.server.ServerHttpSecurity'
available: expected at least 1 bean which qualifies as autowire
candidate. Dependency annotations: {}
And:
APPLICATION FAILED TO START
Description: Parameter 0 of method configSecurity in
it.config.SecurityConfig required a bean of type
'org.springframework.security.config.web.server.ServerHttpSecurity'
that could not be found.
Action: Consider defining a bean of type
'org.springframework.security.config.web.server.ServerHttpSecurity' in
your configuration.
Do you know how to solve?
Below my dependecy:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>

Try annotating the class that bean is in with the following:
#Configuration
#EnableWebSecurity
Also, make sure that bean is public - see if all of those fix it? If not - could you provide a Full Stack-Trace of the exception.
Thanks, Ben

try adding all of these annotations at the top.
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(securedEnabled = true, jsr250Enabled = true, prePostEnabled = true)
Sometimes the #EnableGlobalMethodSecurity helps

I've solved using HttpSecurity instead of ServerHttpSecurity. Below my new code:
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests(authorizeRequests -> authorizeRequests.anyRequest().authenticated()).oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt);
}
}

Related

Start Springboot without any Undertow Configuration

I have a project which mixes 2 dependencies:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>1.4.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-installed-adapter</artifactId>
<version>11.0.2</version>
</dependency>
I'm getting a transitiv dependency for Undertow, which comes from
keycloak-installed-adapter
As far as I understood, Undertow is used internally within the KeyCloak libraries.
I don't want my Springboot Application to start with Undertow, nor I want that anything related with Undertow gets configured at Springboot level.
I can't find to completely exclude any Undertow configuration for Springboot. Does anyone have an idea?
Update
I now have the following:
#SpringBootApplication
#EnableAutoConfiguration(exclude = {EmbeddedUndertow.class})
public class SpringbootTest {
public static void main(String[] args) {
SpringApplication.run(SpringbootTest.class, args);
}
}
But i'm getting following exception when starting my service:
org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'undertowEmbeddedServletContainerFactory' defined in class path resource [org/springframework/boot/autoconfigure/web/EmbeddedServletContainerAutoConfiguration$EmbeddedUndertow.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.context.embedded.undertow.UndertowEmbeddedServletContainerFactory]: Factory method 'undertowEmbeddedServletContainerFactory' threw exception; nested exception is java.lang.NoClassDefFoundError: io/undertow/servlet/api/SessionPersistenceManager
Knowing that the EmbeddedUndertow Class lokks like:
#Configuration
#ConditionalOnClass({ Servlet.class, Undertow.class, SslClientAuthMode.class })
#ConditionalOnMissingBean(value = EmbeddedServletContainerFactory.class, search = SearchStrategy.CURRENT)
public static class EmbeddedUndertow {
#Bean
public UndertowEmbeddedServletContainerFactory undertowEmbeddedServletContainerFactory() {
return new UndertowEmbeddedServletContainerFactory();
}
}
How would you ignore this calss from the scanning?

Spring project with aws cognito

I'm trying to use aws Cognito`s user authentication with my spring project. I configured Cognito and got a jwt token from it. When I pass the token to my api endpoint I'm getting error 401 (unauthorized).
I'm working on a ms that working in my localhost.
I saw a few examples and I feel like my application.properties is missing something but I'm not sure what.
My application properties :
spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://cognito-idp.eu-west-2.amazonaws.com/eu-west-2_somecode
spring.security.oauth2.client.registration.app1.client-id=my_app_id_in_cognito
My pom has the following security dependencies :
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-oauth2-resource-server</artifactId>
<version>5.3.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-oauth2-jose</artifactId>
<version>5.3.3.RELEASE</version>
</dependency>
My configuration class :
#Configuration
public class MySecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.authorizeRequests()
.anyRequest().authenticated().and()
.oauth2ResourceServer().jwt();
}
Tried also to change the application properties according to some spring examples :
spring.security.oauth2.client.registration.cognito.client-id=my_app_id_in_cognito
spring.security.oauth2.client.registration.cognito.client-name=app1
spring.security.oauth2.client.provider.cognito.issuer-uri=https://cognito-idp.eu-west-2.amazonaws.com/eu-west-1_somecode
but then I got the following exception because I was missing the spring.security.oauth2.resourceserver.jwt.jwk-set-uri settings in application.properties :
Method springSecurityFilterChain in org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration required a bean of type 'org.springframework.security.oauth2.jwt.JwtDecoder' that could not be found.
The following candidates were found but could not be injected:
- Bean method 'jwtDecoderByIssuerUri' in 'OAuth2ResourceServerJwtConfiguration.JwtDecoderConfiguration' not loaded because OpenID Connect Issuer URI Condition did not find issuer-uri property
- Bean method 'jwtDecoderByJwkKeySetUri' in 'OAuth2ResourceServerJwtConfiguration.JwtDecoderConfiguration' not loaded because #ConditionalOnProperty (spring.security.oauth2.resourceserver.jwt.jwk-set-uri) did not find property 'spring.security.oauth2.resourceserver.jwt.jwk-set-uri'
- Bean method 'jwtDecoderByPublicKeyValue' in 'OAuth2ResourceServerJwtConfiguration.JwtDecoderConfiguration' not loaded because Public Key Value Condition did not find public-key-location property
Action:
Consider revisiting the entries above or defining a bean of type 'org.springframework.security.oauth2.jwt.JwtDecoder' in your configuration.
What am I missing ?
I found this article and tried to use the same setting in the application.properties :
spring.security.oauth2.resourceserver.jwt.issuer-uri=https://cognito-idp.{REGION}.amazonaws.com/{POOL_ID}

Parameter 0 of method websocketRoutingFilter in org.springframework.cloud.gateway.config.GatewayAutoConfiguration required a bean of type

I am developing code by taking reference from : https://piotrminkowski.wordpress.com/2018/04/26/quick-guide-to-microservices-with-spring-boot-2-0-eureka-and-spring-cloud/. In this example, I'm using Spring Boot V 2.1.1.RELEASE and spring-cloud-dependencies as Finchley.RELEASE.
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Finchley.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
I am getting below error while starting the gateway-service:
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2018-12-21 19:59:47 ERROR [gateway-service,,,]
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 0 of method websocketRoutingFilter in org.springframework.cloud.gateway.config.GatewayAutoConfiguration required a bean of type 'org.springframework.web.reactive.socket.client.WebSocketClient' that could not be found.
The following candidates were found but could not be injected:
- Bean method 'reactorNettyWebSocketClient' in 'GatewayAutoConfiguration.NettyConfiguration' not loaded because #ConditionalOnClass did not find required class 'reactor.ipc.netty.http.client.HttpClient'
Action:
Consider revisiting the entries above or defining a bean of type 'org.springframework.web.reactive.socket.client.WebSocketClient' in your configuration.
And also getting below error while starting proxy-service. How can I resolve this?
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2018-12-21 20:02:19 ERROR [proxy-service,,,]
***************************
APPLICATION FAILED TO START
***************************
Description:
The bean 'proxyRequestHelper', defined in class path resource [org/springframework/cloud/netflix/zuul/ZuulProxyAutoConfiguration$NoActuatorConfiguration.class], could not be registered. A bean with that name has already been defined in class path resource [org/springframework/cloud/netflix/zuul/ZuulProxyAutoConfiguration$EndpointConfiguration.class] and overriding is disabled.
Action:
Consider renaming one of the beans or enabling overriding by setting spring.main.allow-bean-definition-overriding=true
GatewayApplication.java
#SpringBootApplication
#EnableDiscoveryClient
public class GatewayApplication {
public static void main(String[] args) {
SpringApplication.run(GatewayApplication.class, args);
}
}
bootstrap.yml
spring:
application:
name: gateway-service
cloud:
config:
uri: http://localhost:8088
ProxyApplication.java
#SpringBootApplication
#EnableZuulProxy
#EnableSwagger2
public class ProxyApplication {
public static void main(String[] args) {
SpringApplication.run(ProxyApplication.class, args);
}
}
ProxyApi.java
#Configuration
public class ProxyApi {
#Autowired
ZuulProperties properties;
#Primary
#Bean
public SwaggerResourcesProvider swaggerResourcesProvider() {
return () -> {
List<SwaggerResource> resources = new ArrayList<>();
properties.getRoutes().values().stream()
.forEach(route -> resources.add(createResource(route.getServiceId(), route.getId(), "2.0")));
return resources;
};
}
private SwaggerResource createResource(String name, String location, String version) {
SwaggerResource swaggerResource = new SwaggerResource();
swaggerResource.setName(name);
swaggerResource.setLocation("/" + location + "/v2/api-docs");
swaggerResource.setSwaggerVersion(version);
return swaggerResource;
}
}
I've seen https://github.com/spring-cloud/spring-cloud-gateway/issues/319, but I still want to use the Spring Boot V2.1.1.RELEASE.

Error creating bean with name 'batchConfigurer' in Spring Boot

I have a spring batch written using Spring boot. My batch only reads from MongoDB and prints the record.
I'm not using any SQL DB nor have any dependencies declared in project but While running it I'm getting below exception:
s.c.a.AnnotationConfigApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'batchConfigurer' defined in class path resource [org/springframework/boot/autoconfigure/batch/BatchConfigurerConfiguration$JdbcBatchConfiguration.class]: Unsatisfied dependency expressed through method 'batchConfigurer' parameter 1; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'javax.sql.DataSource' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
o.s.j.e.a.AnnotationMBeanExporter : Unregistering JMX-exposed beans on shutdown
ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2018-06-01 10:43:39.485 ERROR 15104 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 1 of method batchConfigurer in org.springframework.boot.autoconfigure.batch.BatchConfigurerConfiguration$JdbcBatchConfiguration required a bean of type 'javax.sql.DataSource' that could not be found.
- Bean method 'dataSource' not loaded because #ConditionalOnProperty (spring.datasource.jndi-name) did not find property 'jndi-name'
- Bean method 'dataSource' not loaded because #ConditionalOnClass did not find required class 'javax.transaction.TransactionManager'
Action:
Consider revisiting the conditions above or defining a bean of type 'javax.sql.DataSource' in your configuration.
In my pom.xml I've added below dependancies:
spring-boot-starter-batch
spring-boot-starter-data-mongodb
spring-boot-starter-test
spring-batch-test
Here's my batch configuration class:
#Configuration
#EnableBatchProcessing
public class BatchConfig {
#Autowired
private JobBuilderFactory jobBuilderFactory;
#Autowired
private StepBuilderFactory stepBuilderFactory;
#Autowired
private MongoTemplate mongoTemplate;
#Bean
public Job job() throws Exception {
return jobBuilderFactory.get("job1").flow(step1()).end().build();
}
#Bean
public Step step1() throws Exception {
return stepBuilderFactory.get("step1").<BasicDBObject, BasicDBObject>chunk(10).reader(reader())
.writer(writer()).build();
}
#Bean
public ItemReader<BasicDBObject> reader() {
MongoItemReader<BasicDBObject> reader = new MongoItemReader<BasicDBObject>();
reader.setTemplate(mongoTemplate);
reader.setCollection("test");
reader.setQuery("{'status':1}");
reader.setSort(new HashMap<String, Sort.Direction>() {
{
put("_id", Direction.ASC);
}
});
reader.setTargetType((Class<? extends BasicDBObject>) BasicDBObject.class);
return reader;
}
public ItemWriter<BasicDBObject> writer() {
MongoItemWriter<BasicDBObject> writer = new MongoItemWriter<BasicDBObject>();
return writer;
}
}
Here's is my launcher class:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
#SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
public class MyBatchApplication {
...
}
Spring Batch requires the use of a relational data store for the job repository. Spring Boot enforces that fact. In order to fix this, you'll need to add an in memory database or create your own BatchConfigurer that uses the Map based repository. For the record, the recommended approach is to add an in memory database (HSQLDB/H2/etc).

FilterChainProxy does not autowire in a Spring Boot application

I'm trying to autowire FilterChainProxy instance as follows:
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private FilterChainProxy filterChainProxy;
#Override
protected void configure(HttpSecurity http) throws Exception {
http.addFilterAfter( new CustomSecurityFilter(), BasicAuthenticationFilter.class);
}
}
I am getting the following exception:
Sep 22 20:08:16 xxxxxx java[21355]: 2017-09-22 20:08:16.953 WARN 21355 --- [ main] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'securityConfig': Unsatisfied dependency expressed through field 'filterChainProxy'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.security.web.FilterChainProxy' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
It does not matter in which class I put the FilterChainProxy instance.
I don't use XML to configure my app, all Spring configuration is annotation-based.
How to fix that problem?

Resources