SpringBoot 401 UnAuthorized even with out security - java

I did not use Spring Security but it is asking me to authenticate.
Exception for URL(http://localhost:8080/SpringJob/ExecuteJob):
{
"timestamp": 1500622875056,
"status": 401,
"error": "Unauthorized",
"message": "Bad credentials",
"path": "/SPPA/ExecuteSPPAJob"
}
----below log details
2017-07-21 13:15:35.210 INFO 19828 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/SpringJob] : Initializing Spring FrameworkServlet 'dispatcherServlet'
2017-07-21 13:15:35.210 [http-nio-8080-exec-1] INFO
o.a.c.c.C.[.[localhost].[/SpringJob]-Initializing Spring FrameworkServlet 'dispatcherServlet'
2017-07-21 13:15:35.211 INFO 19828 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization started
2017-07-21 13:15:35.211 [http-nio-8080-exec-1] INFO
o.s.web.servlet.DispatcherServlet-FrameworkServlet 'dispatcherServlet': initialization started
2017-07-21 13:15:35.494 INFO 19828 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization completed in 282 ms
2017-07-21 13:15:35.494 [http-nio-8080-exec-1] INFO
o.s.web.servlet.DispatcherServlet-FrameworkServlet 'dispatcherServlet': initialization completed in 282 ms
application-dev.xml
#Spring Boot based configurations
management.security.enabled: "false"
spring.autoconfigure.exclude: "org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration"
spring.batch.job.enabled: false
server.contextPath: /SpringJob
build.gradle snippet
plugins {
id 'jacoco'
id 'org.sonarqube' version '2.5'
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'org.springframework.boot'
apply plugin: "no.nils.wsdl2java"
apply plugin: 'jacoco'
apply plugin: "org.sonarqube"
dependencies {
compile("org.springframework.boot:spring-boot-starter-web")
compile("org.springframework.boot:spring-boot-starter-batch")
compile("org.springframework.boot:spring-boot-starter-mail")
//compile("org.springframework.boot:spring-boot-devtools")
compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.5'
compile group: 'org.apache.cxf', name: 'cxf-spring-boot-starter-jaxws', version: '3.1.10'
compile group: 'org.apache.cxf', name: 'cxf-rt-ws-security', version: '3.1.10'
compile("org.springframework.boot:spring-boot-starter-actuator")
testCompile('org.springframework.boot:spring-boot-starter-test')
}
Controller
#Controller
#EnableAutoConfiguration
#EnableBatchProcessing
public class MyController {
#Autowired
JobLauncher jobLauncher;
#RequestMapping("/ExecuteJob")
#ResponseBody
public String callPrelegalJob(#RequestParam("user") String userName, #RequestParam("password") String password) {
log.info("Job is to be launched from controller...");
}
}

In the current version of Spring Boot (v2.1.0.RELEASE), the easiest way to get rid of the security issues is to add "WebSecurityConfig.java" to your project as follows:
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
#EnableWebSecurity
#Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
}
}
Note of course that this removes protection against cross-site request forgery, so this is really only appropriate for simple read-only endpoints.

Try to add below lines in your application.properties file
security.basic.enable: false
security.ignored=/**
According to spring doc, use security.ignored=
Comma-separated list of paths to exclude from the default secured
paths

Just remove the the spring security dependency from pom.xml file.
Worked for me :)..

if we use CXF security & Spring boot security it gives this issues.
Comment out dependency i.e disable the spring boot security then it allows.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
To enable this we have to write custom security or add below config
#Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().permitAll();
}
}

Exact way to disable authentication could not be found by me.But by removing actuator dependency which is working.
compile("org.springframework.boot:spring-boot-starter-actuator")

You can configure the springSecurityFilterChain to ignore all requests and thus allow unauthenticated access to all your endpoints with the following:
#Configuration
#EnableWebSecurity
public class WebConfiguration extends WebSecurityConfigurerAdapter {
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/**");
}
}

#harshit-sharma 's solution worked for me; I added exclusion in my main Application class:
#SpringBootApplication(exclude = { SecurityAutoConfiguration.class })

Spring Security may still be in the project libs via transitive dependencies. What should still work in Spring Boot is the following:
#Override
public void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/**")
.permitAll();
}
Note: the http is a org.springframework.security.config.annotation.web.builders.HttpSecurity and this is in a #Component that may already be injected into and called by some org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter implementation in your application's framework. This should override any built-in catch-all clause, i.e. http.authorizeRequests().anyRequest().denyAll() for testing purposes etc..

I solved by removed this dependency from pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>

Related

Spring springdoc-openapi : swagger-ui/index.html cannot be found status=404

I've a spring boot application (2.5.6) with a dependency on springdoc-openapi.
However, launching swagger-ui (http://localhost:8080/v1/swagger-ui/index.html) doesn't work.
The debug logs are indicating that index.html is not present.
What could be the reason that index.html is not found ?
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>1.6.8</version>
</dependency>
application.yaml
springdoc:
swagger-ui:
tagsSorter: alpha
operations-sorter: alpha
doc-expansion: none
disable-swagger-default-url: true
logging:
level:
root: DEBUG
server:
port: 8080
spring:
application:
name: fe-applic-app
api-version: "v1"
I found the cause of the problem. The context-path was not set in application.yaml.
http://localhost:8080/v1/swagger-ui/index.html
After adding servlet : context-path, swagger-ui is rendered
server:
port: 8080
servlet:
context-path: "/${spring.application.api-version}"
Try swagger-ui.html instead of swagger-ui/index.html. In 60% of the cases swagger-ui.html redirects to its real location.
http://localhost:8080/v1/swagger-ui.html
http://localhost:8080/v3/swagger-ui.html
add this to your configs:
#Configuration
public class WebAppConfig extends WebMvcConfigurationSupport
{
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry)
{
registry.addResourceHandler("/swagger-ui/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/swagger-ui/4.14.3/");
}
see source
and static-resources

RestTemplate could not be found when run a jar [duplicate]

This question already has answers here:
How to add a dependency to a Spring Boot Jar in another project?
(12 answers)
Closed 2 years ago.
My Project structure:
demo
common
demo-consumer
demo has two modules, common provided as a jar package to other modules, demo is a empty project
demo build.gradle
plugins {
id 'org.springframework.boot' version '2.3.8.RELEASE'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
id 'java'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'
allprojects {
apply plugin: 'java'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
mavenLocal()
mavenCentral()
}
ext {
set('springCloudVersion', "Hoxton.SR9")
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-web-services'
compileOnly 'org.projectlombok:lombok'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
runtimeOnly 'mysql:mysql-connector-java'
annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor'
annotationProcessor 'org.projectlombok:lombok'
testImplementation('org.springframework.boot:spring-boot-starter-test') {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}
}
dependencyManagement {
imports {
mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
}
}
test {
useJUnitPlatform()
}
}
demo settings.gradke
rootProject.name = 'demo'
include 'common'
include 'demo-consumer'
Module Common Project structure:
src
main
java
com.example.common
config
RestTemplateConfig.class
App.class
My RestTemplateConfig.class:
package com.example.common.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
#Configuration
public class RestTemplateConfig {
#Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
My App.class:
package com.example.common;
public class App {
public static void main(String[] args) {
}
}
Module demo-consumer Project structure, a simple spring boot application:
src
main
java
com.example.democonsumer
controller
TestController.class
DemoConsumerApplication.class
My TestController.class:
package com.example.democonsumer.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
#RestController
public class TestController {
#Autowired
private RestTemplate restTemplate;
#GetMapping("/test0")
public String test0(){
return "Success";
}
#GetMapping("/test1")
public String test1(){
return restTemplate.getForObject("http://localhost:9999/test0", String.class);
}
}
My DemoConsumerApplication.class:
package com.example.democonsumer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
#SpringBootApplication(exclude = {DataSourceAutoConfiguration.class}, scanBasePackages = {"com.example"})
public class DemoConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(DemoConsumerApplication.class, args);
}
}
demo-consumer's build.gradle:
dependencies {
implementation project(":common")
}
I build common first and build the demo-consumer by gradle, put the demo-consumer.jar on the server;
run the jar package, it failed
2021-01-20 11:24:17.463 INFO 4007 --- [ main] c.e.d.DemoConsumerApplication : Starting DemoConsumerApplication on iZ2ze9tlmbs6w25xr1jp92Z with PID 4007 (/home/spring-cloud-template/demo-consumer.jar started by root in /home/spring-cloud-template)
2021-01-20 11:24:17.467 INFO 4007 --- [ main] c.e.d.DemoConsumerApplication : No active profile set, falling back to default profiles: default
2021-01-20 11:24:19.555 INFO 4007 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.ws.config.annotation.DelegatingWsConfiguration' of type [org.springframework.ws.config.annotation.DelegatingWsConfiguration$$EnhancerBySpringCGLIB$$4d8ad8fc] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2021-01-20 11:24:19.740 INFO 4007 --- [ main] .w.s.a.s.AnnotationActionEndpointMapping : Supporting [WS-Addressing August 2004, WS-Addressing 1.0]
2021-01-20 11:24:20.545 INFO 4007 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 9990 (http)
2021-01-20 11:24:20.578 INFO 4007 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2021-01-20 11:24:20.579 INFO 4007 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.41]
2021-01-20 11:24:20.746 INFO 4007 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2021-01-20 11:24:20.750 INFO 4007 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 3169 ms
2021-01-20 11:24:21.410 WARN 4007 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'testController': Unsatisfied dependency expressed through field 'restTemplate'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.web.client.RestTemplate' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
2021-01-20 11:24:21.417 INFO 4007 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2021-01-20 11:24:21.468 INFO 4007 --- [ main] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2021-01-20 11:24:21.806 ERROR 4007 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Field restTemplate in com.example.democonsumer.controller.TestController required a bean of type 'org.springframework.web.client.RestTemplate' that could not be found.
The injection point has the following annotations:
- #org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'org.springframework.web.client.RestTemplate' in your configuration.
Idea is running normally, jar package failed,how to fix it?
Try to inject RestTemplate in this way:
RestTemplateConfig
#Bean
public ClientHttpRequestFactory clientHttpRequestFactory() {
SimpleClientHttpRequestFactory simpleClientHttpRequestFactory = new SimpleClientHttpRequestFactory();
ClientHttpRequestFactory clientHttpRequestFactory = new BufferingClientHttpRequestFactory(simpleClientHttpRequestFactory);
return clientHttpRequestFactory ;
}
#Bean
public RestTemplate restTemplate(ClientHttpRequestFactory clientHttpRequestFactory) {
RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory);
return restTemplate;
}
OR
#Autowired
private RestTemplateBuilder builder;
// Use RestTemplateBuilder to instantiate the RestTemplate object, spring has injected the RestTemplateBuilder instance by default
#Bean
public RestTemplate restTemplate() {
return builder.build();
}

How to configure 2-level of hibernate entity cache via annotations properly

I want to configure 2nd level hibernate cache at Spring Boot microservice.
And I don't want to use xml at all.
Next is my example.
UserEntity.java
#Entity
#Table(name = "users")
#Cacheable
#Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "users")
public class UserEntity {
#Id
private long id;
#Column
private String name;
public UserEntity(long id, String name) {
this.id = id;
this.name = name;
}
// ... geters&setters
}
CacheConfig.java
import net.sf.ehcache.config.CacheConfiguration;
import net.sf.ehcache.store.MemoryStoreEvictionPolicy;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
#Configuration
#EnableCaching
public class CacheConfig {
#Bean
public org.springframework.cache.CacheManager cacheManager() {
return new EhCacheCacheManager(ehCacheManager());
}
private net.sf.ehcache.CacheManager ehCacheManager() {
CacheConfiguration usersCacheConfiguration = new CacheConfiguration();
usersCacheConfiguration.setName("users");
usersCacheConfiguration.eternal(false);
usersCacheConfiguration.setMaxEntriesInCache(1000);
usersCacheConfiguration.setMaxEntriesLocalDisk(0);
usersCacheConfiguration.memoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.LRU);
net.sf.ehcache.config.Configuration config = new net.sf.ehcache.config.Configuration();
config.addCache(usersCacheConfiguration);
return net.sf.ehcache.CacheManager.create(config);
}
}
App.java
#SpringBootApplication
public class App {
public static void main(String[] args) {
new SpringApplicationBuilder(App.class)
.sources(CacheConfig.class)
.run(args);
}
}
application.properties
spring:
datasource:
url: jdbc:postgresql://localhost:5432/test
username: postgres
password: postgres
type: com.zaxxer.hikari.HikariDataSource
driverClassName: org.postgresql.Driver
jpa.hibernate.ddl-auto: update
jpa.open-in-view: false
jpa.properties.javax.persistence.sharedCache.mode: ALL
jpa.properties.hibernate:
dialect: org.hibernate.dialect.PostgreSQL9Dialect
jdbc.batch_size: 100
temp.use_jdbc_metadata_defaults: false
order_inserts: true
cache:
region.factory_class: org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory
#region.factory_class: org.hibernate.cache.ehcache.EhCacheRegionFactory
#region_prefix: ""
use_second_level_cache: true
cache.use_query_cache: true
provider_class: org.hibernate.cache.EhCacheProvider
build.gradle
group 'com.hibernate.cache'
version '1.0-SNAPSHOT'
apply plugin: 'java'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
compile group: 'org.springframework.boot', name: 'spring-boot-starter-data-jpa', version: '2.0.0.RELEASE'
compile group: 'org.springframework', name: 'spring-context-support', version: '5.0.4.RELEASE'
compile group: 'org.hibernate', name: 'hibernate-ehcache', version: '5.2.14.Final'
compile group: 'org.postgresql', name: 'postgresql', version: '42.1.4'
}
When I run the program I see a couple of warnings indicating that entity cache configuration is not applied:
2018-03-04 23:29:48.723 WARN 8516 --- [ main] n.s.ehcache.config.ConfigurationFactory : No configuration found. Configuring ehcache from ehcache-failsafe.xml found in the classpath: jar:file:/home/vitaly/.gradle/caches/modules-2/files-2.1/net.sf.ehcache/ehcache/2.10.3/cf74f9a4a049f181833b147a1d9aa62159c9d01d/ehcache-2.10.3.jar!/ehcache-failsafe.xml
2018-03-04 23:29:48.834 WARN 8516 --- [ main] o.h.c.e.AbstractEhcacheRegionFactory : HHH020003: Could not find a specific ehcache configuration for cache named [users]; using defaults.
Does anybody know what is wrong here?
The first warning:
2018-03-04 23:29:48.723 WARN 8516 --- [ main] n.s.ehcache.config.ConfigurationFactory : No configuration found. Configuring ehcache from ehcache-failsafe.xml found in the classpath: jar:file:/home/vitaly/.gradle/caches/modules-2/files-2.1/net.sf.ehcache/ehcache/2.10.3/cf74f9a4a049f181833b147a1d9aa62159c9d01d/ehcache-2.10.3.jar!/ehcache-failsafe.xml
means that no ehcache.xml configuration was found so a default, ehcache-failsafe.xml, is used.
The second warning:
2018-03-04 23:29:48.834 WARN 8516 --- [ main] o.h.c.e.AbstractEhcacheRegionFactory : HHH020003: Could not find a specific ehcache configuration for cache named [users]; using defaults.
means that there was no configuration found for the "users" region in the cache. It is, of course, not defined in ehcache-failsafe.xml and it doesn't look like the settings in CacheConfig are being picked up - at least not by the CacheManager used by Hibernate.
It should be possible to solve both by adding an ehcache.xml to the classpath (in src/main/resources), e.g.:
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://www.ehcache.org/ehcache.xsd"
updateCheck="true"
monitoring="autodetect"
dynamicConfig="true">
<cache name="users"
maxEntriesLocalHeap="500"
eternal="false"
timeToIdleSeconds="300"
timeToLiveSeconds="600"
diskExpiryThreadIntervalSeconds="1"
copyOnRead="true"
copyOnWrite="true">
<copyStrategy class="net.sf.ehcache.store.compound.ReadWriteSerializationCopyStrategy" />
</cache>
</ehcache>
(see this ehcache.xml sample for more options)
And adding the following to application.yml:
spring:
cache:
ehcache:
config: classpath:ehcache.xml
A year late but the answer to your question might require you to implement your own RegionFactory class (by extending SingletonEhCacheRegionFactory) And then set your newly created class as the factory that hibernate should use: spring.jpa.properties.hibernate.cache.region.factory_class=com.my.class
https://stackoverflow.com/a/28594371/708854

Springboot swagger url shows WhiteLabel Error page

Here is my code: I am getting all the values from application.properties file
SwaggerConfig.java
#Configuration
#EnableSwagger2
#Profile("!prod")
#PropertySource(value = { "classpath:application.properties" })
public class SwaggerConfig {
#Value("${swagger.api.title}")
private String title;
#Value("${swagger.api.description}")
private String description;
#Value("${swagger.api.termsOfServiceUrl}")
private String termsOfServiceUrl;
#Value("${swagger.api.version}")
private String version;
#Value("${swagger.api.controller.basepackage}")
private String basePackage;
#Bean
public Docket postMatchApi() {
return new Docket(DocumentationType.SWAGGER_2).select().apis(RequestHandlerSelectors.basePackage(basePackage))
.paths(PathSelectors.ant("/**")).build().apiInfo(metaData());
}
private ApiInfo metaData() {
return new ApiInfoBuilder().title(title).description(description).termsOfServiceUrl(termsOfServiceUrl)
.version(version).build();
}
Here is my springboot initializer:
#SpringBootApplication
#ComponentScan(basePackages = { "com.example.demo" })
#ComponentScan(basePackageClasses = {AppInitializer.class, SwaggerConfig.class})
#EnableAsync
#EnableRetry
public class AppInitializer{
public static void main(String[] args) {
SpringApplication.run(AppInitializer.class, args);
}
}
ServletInitializer.java
public class ServletInitializer extends SpringBootServletInitializer implements WebApplicationInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(PostMatchAppInitializer.class);
}
}
The log says it is mapped:
[INFO ] 2018-01-17 16:46:37.055 [restartedMain] o.s.w.s.m.m.a.RequestMappingHandlerMapping - Mapped "{[],methods=[POST],consumes=[application/json],produces=[application/json]}" onto public <T> org.springframework.http.ResponseEntity<?> com.,org.springframework.validation.BindingResult) throws java.lang.Exception
[INFO ] 2018-01-17 16:46:37.055 [restartedMain] o.s.w.s.m.m.a.RequestMappingHandlerMapping - Mapped "{[/v2/api-docs],methods=[GET],produces=[application/json || application/hal+json]}" onto public org.springframework.http.ResponseEntity<springfox.documentation.spring.web.json.Json> springfox.documentation.swagger2.web.Swagger2Controller.getDocumentation(java.lang.String,javax.servlet.http.HttpServletRequest)
[INFO ] 2018-01-17 16:46:37.055 [restartedMain] o.s.w.s.m.m.a.RequestMappingHandlerMapping - Mapped "{[/swagger-resources/configuration/ui]}" onto org.springframework.http.ResponseEntity<springfox.documentation.swagger.web.UiConfiguration> springfox.documentation.swagger.web.ApiResourceController.uiConfiguration()
[INFO ] 2018-01-17 16:46:37.055 [restartedMain] o.s.w.s.m.m.a.RequestMappingHandlerMapping - Mapped "{[/swagger-resources]}" onto org.springframework.http.ResponseEntity<java.util.List<springfox.documentation.swagger.web.SwaggerResource>> springfox.documentation.swagger.web.ApiResourceController.swaggerResources()
[INFO ] 2018-01-17 16:46:37.055 [restartedMain] o.s.w.s.m.m.a.RequestMappingHandlerMapping - Mapped "{[/swagger-resources/configuration/security]}" onto org.springframework.http.ResponseEntity<springfox.documentation.swagger.web.SecurityConfiguration> springfox.documentation.swagger.web.ApiResourceController.securityConfiguration()
[INFO ] 2018-01-17 16:46:37.055 [restartedMain] o.s.w.s.m.m.a.RequestMappingHandlerMapping - Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
[INFO ] 2018-01-17 16:46:37.071 [restartedMain] o.s.w.s.m.m.a.RequestMappingHandlerMapping - Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
[INFO ] 2018-01-17 16:46:37.227 [restartedMain] o.s.w.s.m.m.a.RequestMappingHandlerAdapter - Looking for #ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#5e89f6: startup date [Wed Jan 17 16:46:34 CST 2018]; root of context hierarchy
This is the error that i get:
[WARN ] 2018-01-17 16:46:42.217 [http-nio-8082-exec-1] o.s.w.s.PageNotFound - No mapping found for HTTP request with URI [/example/swagger-ui.html] in DispatcherServlet with name 'dispatcherServlet'
For the new Springfox version(3.0.0) you need to do something different
In pom.xml add the following dependency
*
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
instead of two for
<artifactId>springfox-swagger2</artifactId> and
<artifactId>springfox-swagger-ui</artifactId>
and access ../swagger-ui/ instead of ../swagger-ui.html
For Swagger 3.0, the URL is changed
http://localhost:8080/swagger-ui/index.html
I found what the issue was, in one of the config files i somehow had #EnableMvc annotation due to which the dispatcherservlet was looking for the mapping /example/swagger-ui.html and since it could not find one it was complaining "No Mapping found".
After removing #EnableMvc it is working perfectly fine.
For others like me that is still getting the "Whitelabel" page error, check if you have:
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.8.0</version>
</dependency>
in your pom.xml file, it's not only the "springfox-swagger2" dependency required as the official doc page shows, you need "springfox-swagger-ui" too.
I faced the same issue. So Basically if you are using spring 3 or more then to open the swagger page , you have to do 3 things only.
Add 3 dependencies in pom.xml
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2 </artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>3.0.0</version>
</dependency>
Create a config file.
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
#Configuration
#EnableSwagger2
public class SwaggerConfig {
#Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2);
}
}
Open this link to access the API.
http://localhost:8080/swagger-ui/
Now just match which step you missed. Do ask if you get stuck somewhere.
I'm bad at English, that's why GoogleTranslate.
That version and way of doing it is already a bit outdated, if you want the documentation to be generated automatically, SpringDoc simplifies the generation and maintenance of API documents, based on the OpenAPI 3 specification, for Spring Boot 1.x and 2.x. applications.
For magic to happen we simply add the dependency to our pom:
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>1.2.32</version>
</dependency>
then access the description that already has it http://localhost:8080/v3/api-docs/
and for swagger: http://localhost:8080/swagger-ui.html
that's all there is to it.
for more detail
if you want to customize the api information you can include java style annotations:
#OpenAPIDefinition(
info = #Info(
title = "API personas",
description = "Este es un ejemplo de servidor Personas-Server."
+ "Usted puyede encontrar mas acerca de Swagger " ++"[http://swagger.io](http://swagger.io) o en "
+ "[irc.freenode.net, #swagger](http://swagger.io/irc/).",
termsOfService = "http://swagger.io/terms/",
license = #License(
name = "Apache 2.0",
url = "http://springdoc.org"),
version = "otra"
))
#Tag(name = "persona", description = "API para personas")
#RestController
#RequestMapping("persona")
public class PersonaRest extends GeneralRest {}
can also be generated for special methods:
#Operation(
summary = "traer todas las personas",
description = "api para traer todas las personas, aqui no se tienen en cuenta paginaciones, ni filtros, trae todos los registros",
tags = { "persona" }
)
#ApiResponses(
value = {
#ApiResponse(
responseCode = "200",
description = "Operación exitosa",
content = #Content(
mediaType = "application/json",
array = #ArraySchema(
schema = #Schema(
implementation = PersonaTO.class
)))),
#ApiResponse(
responseCode = "401",
description = "Sin autorización",
content = #Content(
mediaType = "application/json",
schema = #Schema(
implementation = Object.class
))),
})
#GetMapping
public List personas() {
return personaServicio.obtenerTodo();
}
it is always good practice to use the most recent libraries and inclusions.
For me it is swagger dependency version.
Issue with
spring boot - 2.3.4
java - 8
swagger - 3.0.0
No issue with
spring boot - 2.3.4
java - 8
swagger - 2.9.2
Move swagger configuration to your SpringBootApplication class. That will solve the whitable page error.
If your facing the issue even after adding appropriate dependencies
Then follow the below steps
1.Go to C:\Users\User.m2
2.Delete the repository folder (Complete folder delete i.e Shift+Delete button windows)
This folder bascially contains all the jars that your project requires
So when you again open your project it will automatically download the dependencies
first, add below dependencies in spring boot pom file, then add #EnableSwagger annotation on the application class and then add webappconfig class
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.1</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.1</version>
</dependency>
#Configuration
#EnableWebMvc
public class ApplicationWebMvcConfig implements WebMvcConfigurer {.
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}.
For SpringBoot Ver: 2.4.0-M4 I recommend the following setup.
Make sure you use SpringFox ver: 3.0.0
//build.gradle file
def springFoxVer = '3.0.0'
def log4jVer = '2.13.3'
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-data-rest'
implementation 'org.springframework.boot:spring-boot-starter-hateoas'
implementation 'org.springframework.boot:spring-boot-starter-validation'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.data:spring-data-rest-hal-explorer'
implementation "io.springfox:springfox-swagger2:$springFoxVer"
implementation "io.springfox:springfox-boot-starter:$springFoxVer"
implementation "io.springfox:springfox-swagger-ui:$springFoxVer"
implementation "io.springfox:springfox-data-rest:$springFoxVer"
implementation "org.apache.logging.log4j:log4j-core:$log4jVer"
implementation "org.apache.logging.log4j:log4j-api:$log4jVer"
implementation 'org.springframework.boot:spring-boot-starter-actuator'
compileOnly 'org.projectlombok:lombok'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
runtimeOnly 'com.h2database:h2'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
In the configuration class:
#Configuration
public class SwaggerDocumentationConfig {
ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Sample Indentity in Project")
.description("The identity API provides standardized mechanism for identity management such as creation, update, retrieval, deletion. Party can be an individual or an organization that has any kind of relation with the enterprise. ### Resources - Individual Party API performs the following operations : - Retrieve an individual - Retrieve a collection of individuals according to given criteria - Create a new individual - Update an existing individual - Delete an existing individual")
.license("")
.licenseUrl("http://unlicense.org")
.termsOfServiceUrl("")
.version("1.0.0")
.contact(new Contact("Sean Huni", "https://sean-huni.xyz", "sean2kay#gmail.com"))
.build();
}
#Bean
public Docket customImplementation() {
return new Docket(DocumentationType.SWAGGER_2)
.tags(new Tag("Person Entity", "Repository for People's entities"))
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build()
.apiInfo(apiInfo());
}
}
In the application-runner/executor class:
#SpringBootApplication
#EnableSwagger2
#EnableJpaRepositories
#Import(SpringDataRestConfiguration.class)
public class SpringSwaggerApplication {
public static void main(String[] args) {
SpringApplication.run(SpringSwaggerApplication.class, args);
}
}
As instructed here. Most cases just taking the time to read the requirements & the setup process means everything in terms of saving yourself a day of getting stuck.
In my case, I upgraded from swagger 2.7.0 to 3.0.0 and these were the steps to reach the honeypot:
add one dependency
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>${swagger.version}</version>
</dependency>
remove two dependencies (but they do not harm, if you forget this step)
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${swagger.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger.version}</version>
</dependency>
The Server-Class now looks like this (unchanged compared to swagger v2.7.0)
#SpringBootApplication(scanBasePackages = {"com.acme.product.server"})
#RestController
#EnableScheduling
#EnableSwagger2
public class AcmeProductServer {
// [...]
// --- swagger integration
#Bean
public Docket productApi() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.acme.product.server"))
.build();
}
}
Then I really had to delete and refresh my local maven repository at 'C:\Users\Zaphod.m2\repository'
Last issue was to use a different URL: http://localhost:8080/iam/swagger-ui/ (without the trailing slash or '/index.html' at the end it does not work)
Ensure following things along with versions:
dependency is added
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
#Bean Dokcet is defined in #SpringBootApplication class
swagger ui endpoint http://localhost:<port-number>/swagger-ui
P.S: tested in spring boot (v2.5.0)
To include Swagger in our project, let's add the following annotation to our application void method.
#SpringBootApplication
#EnableSwagger2
public class PostApplication {
public static void main(String[] args) {
SpringApplication.run(PostApplication.class, args);
}
}
Simple install the Spring Fox boot starter and remove the springfox-swagger-ui and springfox-swagger2 from your project.
Gradle:-
implementation group: 'io.springfox', name: 'springfox-boot-starter', version: '3.0.0'
Maven:-
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
Also, create a file named SwaggerCondig.java with the below configurations
#Configuration
#EnableSwagger2
public class SwaggerConfig {
#Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2).select()
.apis(RequestHandlerSelectors.basePackage("com.xxx.xxx.controller"))
.paths(PathSelectors.any()).build();
}
}
Access the swagger at http://localhost:9005/service-name/swagger-ui/
In my case I used mvn dependencies
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>3.0.0</version>
</dependency>
calling http://localhost:8088/swagger-ui/ instead of http://localhost:8088/swagger-ui.html works for me. Also check basePackage is correct if you have swagger config file.
If anyone wants to work with Swagger UI then do these 3 simple steps
Step 1 -> Add Dependencies
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>3.0.0</version>
</dependency>
Step 2 -> Goto main class and give annotation #EnableSwagger2
#SpringBootApplication
#EnableSwagger2
class PracticeApplication {
Step 3 -> Restart server & Just hit http://localhost:8080/swagger-ui/
Note - After doing this if anyone getting - "Failed to start bean 'documentationPluginsBootstrapper"
Then add the below line to application.properties -
spring.mvc.pathmatch.matching-strategy = ANT_PATH_MATCHER
if you use spring 3 like me, make sure to use these dependencies:
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>2.0.2</version>
</dependency>
make sure to remove the annotation #EnableSwagger2 because it's not necessary in spring 3 as mentioned here https://github.com/springfox/springfox

How do I get Spring Boot Security and JBoss 7.1 to play nicely with each other?

Versions:
JBoss: 7.1
Spring Boot: 1.4.1.RELEASE
Starting a project from scratch and following the directions for securing a spring-boot app from here: https://spring.io/guides/gs/securing-web/, I get an application quick and easy that runs from gradle clean bootRun.
But, when I build with gradle clean war and deploy to a JBoss 7.1 server, during startup it fails with the following:
2016-09-24 18:01:37,783 ERROR [org.apache.catalina.core.ContainerBase.[jboss.web].[default-host].[/]] (MSC service thread 1-10) | Exception starting filter springSecurityFilterChain: java.lang.InstantiationException: org.springframework.boot.web.servlet.DelegatingFilterProxyRegistrationBean$1
at java.lang.Class.newInstance(Class.java:427) [rt.jar:1.8.0_101]
at org.jboss.as.web.deployment.WebInjectionContainer.newInstance(WebInjectionContainer.java:80) [jboss-as-web-7.1.2.Final.jar:7.1.2.Final]
at org.jboss.as.web.deployment.WebInjectionContainer.newInstance(WebInjectionContainer.java:72) [jboss-as-web-7.1.2.Final.jar:7.1.2.Final]
at org.apache.catalina.core.ApplicationFilterConfig.getFilter(ApplicationFilterConfig.java:441) [jbossweb-fas.jar:fas-4]
at org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:3269) [jbossweb-fas.jar:fas-4]
at org.apache.catalina.core.StandardContext.start(StandardContext.java:3873) [jbossweb-fas.jar:fas-4]
at org.jboss.as.web.deployment.WebDeploymentService.start(WebDeploymentService.java:91) [jboss-as-web-7.1.2.Final.jar:7.1.2.Final]
at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1811)
at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1746)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [rt.jar:1.8.0_101]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [rt.jar:1.8.0_101]
at java.lang.Thread.run(Thread.java:745) [rt.jar:1.8.0_101]
Caused by: java.lang.NoSuchMethodException: org.springframework.boot.web.servlet.DelegatingFilterProxyRegistrationBean$1.<init>()
at java.lang.Class.getConstructor0(Class.java:3082) [rt.jar:1.8.0_101]
at java.lang.Class.newInstance(Class.java:412) [rt.jar:1.8.0_101]
... 11 more
I've been digging on this thing for a couple weeks and trying to attack it from a number of angles. I get a similar error when I skip the WebSecurity class together and instead do a #ImportResource("classpath:security-context.xml) (from another working project). With a bit of tinkering I get it to behave again for gradle bootRun but deploying it to JBoss results in the same error.
TIA.
Significant code sections:
build.gradle:
buildscript {
ext {
springBootVersion = '1.4.1.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'eclipse-wtp'
apply plugin: 'spring-boot'
apply plugin: 'war'
war {
baseName = 'demo'
version = '0.0.1-SNAPSHOT'
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
...
dependencies {
compile('org.springframework.boot:spring-boot-devtools')
compile('org.springframework.boot:spring-boot-starter-security')
compile('org.springframework.boot:spring-boot-starter-thymeleaf')
compile('org.springframework.boot:spring-boot-starter-web')
compile('org.slf4j:slf4j-api:1.7.5')
providedRuntime('org.springframework.boot:spring-boot-starter-tomcat')
testCompile('org.springframework.boot:spring-boot-starter-test')
}
DemoApplication:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
#Configuration
#ComponentScan
#EnableAutoConfiguration
public class DemoApplication extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(final SpringApplicationBuilder application) {
return application.sources(SnapshotApiDemoApplication.class);
}
public static void main(final String[] args) {
SpringApplication.run(SnapshotApiDemoApplication.class, args);
}
}
WebSecurityConfig:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(final HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/", "/home").permitAll().anyRequest().authenticated().and().formLogin()
.loginPage("/login").permitAll().and().logout().permitAll();
}
#Autowired
public void configureGlobal(final AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("user").password("password").roles("USER");
}
}
application.yml:
spring:
main:
banner-mode: off
application:
name: snapshot
debug: true
server:
version: UNKNOWN
context-path: /
application.properties:
logger.level=DEBUG
logger.handlers=FILE,CONSOLE
handler.CONSOLE=org.jboss.logmanager.handlers.ConsoleHandler
handler.CONSOLE.properties=autoFlush
handler.CONSOLE.level=INFO
handler.CONSOLE.autoFlush=true
handler.CONSOLE.formatter=PATTERN
handler.FILE=org.jboss.logmanager.handlers.FileHandler
handler.FILE.level=INFO
handler.FILE.properties=autoFlush,fileName
handler.FILE.autoFlush=true
handler.FILE.fileName=demo.log
handler.FILE.formatter=PATTERN
formatter.PATTERN=org.jboss.logmanager.formatters.PatternFormatter
formatter.PATTERN.properties=pattern
formatter.PATTERN.pattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %-5p [%c] (%t) %s%E%n
Seems like you are using JDK 1.8 for your SpringBoot app.
JBoss AS 7 doesn't work on JDK8.
See Unable to start jboss-as-7.1.1.Final on Windows 8.1 command prompt

Categories