Spring Boot project shows the Login page - spring

I created a Spring boot project with the Spring initializer and only have the starter code so far.
The sample code
#SpringBootApplication
public class EcommerceApplication {
public static void main(String[] args) {
SpringApplication.run(EcommerceApplication.class, args);
}
}
#Controller
#RequestMapping(value = "/")
public class HomeController {
#GetMapping
public String index() {
return "index";
}
}
I expect it to return the index.html page from the templates folder. Instead, I'm redirected to the http://localhost:8080/login address and asked for the username/ password. In the application.properties file, I tried to use the configuration of,
server.port=8080
spring.application.name=Bootstrap Spring Boot
spring.thymeleaf.cache=false
spring.thymeleaf.enabled=true
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.url=jdbc:h2:mem:bootapp;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.username=testuser
spring.datasource.password=testpassword
server.error.path=/error
server.error.whitelabel.enabled=false
I tried to login with the username testuser and the password testpassword. This doesn't work out.
I use the following pom.xml in the project,
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.online.books</groupId>
<artifactId>Ecommerce</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>Ecommerce</name>
<description>Spring Boot Project</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.BUILD-SNAPSHOT</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-hateoas</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jersey</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web-services</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<!--<dependency>-->
<!--<groupId>com.h2database</groupId>-->
<!--<artifactId>h2</artifactId>-->
<!--<scope>runtime</scope>-->
<!--</dependency>-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.restdocs</groupId>
<artifactId>spring-restdocs-mockmvc</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
</project>
Whats the issue here?

If you don't want login page (from Spring-Security) remove the following dependency from your pom.xml and do maven update to refresh the dependencies on the class path.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
Or if you want to use the Spring-Security then on console it will display the default password like below :
Using default security password: ce6c3d39-8f20-4a41-8e01-803166bb99b6
the default username will be user

That is the default behavior. to change this, you have a few options:
You can remove the Spring Boot Security dependency:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
You can desable autoconfiguration. To do so; in your main class, to: #SpringBootApplication append: (exclude = { SecurityAutoConfiguration.class }) so that it looks like:
#SpringBootApplication(exclude = { SecurityAutoConfiguration.class })
public static void main(String[] args) {
SpringApplication.run(SpringBootSecurityApplication.class, args);
}
}
you can also do this from the application.properties file
For more information on desableing Auto-Configuration and setting up your own. Reference:
Spring Boot Security Auto-Configuration

When you include spring-boot-starter-security then the login page will automatically be shown.
To remove this login page-
If you use Maven then removing this dependency and rebuild the project. Already there are some answers for this. Just remove the block (pom.xml):
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
If anyone uses Gradle then, just remove the following block from dependencies block(build.gradle) and reload build.gradle:
dependencies {
//implementation 'org.springframework.boot:spring-boot-starter-security'
...
}
If you do not want to change the config file like pom.xml or build.gradle then source code level change will be the best suit for you. To do this, need to update the main class with, change #SpringBootApplication annotation with #SpringBootApplication(exclude = {SecurityAutoConfiguration.class}). This excludes parameter will remove Security configuration.
#SpringBootApplication(exclude = {SecurityAutoConfiguration.class})
public class SpringCacheApplication {
public static void main(String[] args) {
...
}
...
}
Moreover, if you want to keep the login page, then you can log in with generated security password. You can find it into console, looks like:
Using generated security password: d408ce6f-470d-4**4-950a-81**9651f321
{
"usename" : "user",
"password": "d408ce6f-470d-4**4-950a-81**9651f32"
}
For more information, you can read Spring Security.

You can add a class in your Project,
for Web Security configuration as follows:
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests().antMatchers("/*").permitAll()
.and()
.csrf().disable();
}
}

Check the console to find the password
Also as a username please use "user" as a credential.
If you want to disable that spring functionality, go to your pom xml and delete the dependency below;
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>

if you really want to disable this login page you may disable your class where is:
public class SecurityConfig extends WebSecurityConfigurerAdapter {
this class is not necessary
in my opinion you haven't create this class whose extends WebSecurityConfigurerAdapter

My code without the starter-security but still ask for login.
Here is the solution:
disable your autoconfiguration in main class,
#SpringBootApplication(exclude= {SecurityAutoConfiguration.class})

If you want the spring security and you've defined the WebSecurityConfig then make sure you have these two annotations on your WebSecurityConfig class:
#Configuration
#EnableWebSecurity

if you have login page displayed; it means that security is activated;
you comment or delete those dependencies from pom.xml:
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
or:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
or:
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
</dependency>

I had the same issue and in my case it was because of missing #Configuration and #EnableWebSecurity annotations in SecurityConfig file

Related

Spring boot Rest Api controller getting 404 error

I'm exposing my services by using Rest in Spring boot. I'm exposing my service with 2 different approach first by using cxf jaxrs dependency and other by spring rest dependency. In first approach i'm getting 404 error when i run my services in postman. But in second approach i'm getting my output. Please help me out.
First approach with cxf jaxrs
#Path("/locations")
public interface LocationRestController {
#GET
public List<Location> getLocations();
}
******************************************
#RestController
public class LocationRestControllerImpl implements LocationRestController {
#Autowired
LocationRepos repos;
#Override
public List<Location> getLocations() {
return repos.findAll();
}}
{
"timestamp": "2018-09-17T03:36:05.283+0000",
"status": 404,
"error": "Not Found",
"message": "No message available",
"path": "/locationweb/locations"
}
Second approach using spring inbuilt dependency
#RestController
#RequestMapping("/locations")
public class LocationRestControllerImpl {
#Autowired
LocationRepos repos;
#GetMapping
public List<Location> getLocations() {
return repos.findAll();
}}
Pom file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.project.abhishek</groupId>
<artifactId>student</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>student</name>
<description>Student DAL</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
"pom.xml" <version>2.1.0.M2</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<version>9.0.12</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
<version>2.0.4.RELEASE</version>
</dependency>
<dependency>
<groupId>jfree</groupId>
<artifactId>jfreechart</artifactId>
<version>1.0.13</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-spring-boot-starter-jaxrs</artifactId>
<version>3.2.6</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
please refer below code for correct implementation
public interface LocationRestController {
public List<Location> getLocations();
}
******************************************
#RestController(value="/locationweb/locations")
public class LocationRestControllerImpl implements LocationRestController {
#Autowired
LocationRepos repos;
#Override
#GetMapping
public List<Location> getLocations() {
return repos.findAll();
}}
{
This line might be the issue
#RestController
public class LocationRestControllerImpl implements LocationRestController {
remove #RestController from the class in 1st approach
Try this example,
https://dzone.com/articles/spring-boot-building-restful-web-services-with-jersey
Most probably you are missing Spring/Jersey integration or Jersey Configuration.
Do add Jersey Configuration for Spring boot to understand Jersey.
Below is the code for Jersey Configuration for convenience.
#Configuration
#ApplicationPath("rest")
public class Config extends ResourceConfig {
public Config() {
}
#PostConstruct
public void setUp() {
register(Controller.class);
}
}
Make sure you have CXF configuration and set as a service bean as if you use #RestController you are actually not implementing CXF so to order to handle requests by CXF, you need to configure CXF server.
#Configuration
public class CXFConfig {
#Autowired
private Bus bus;
#Bean
public Server rsServer() {
final JAXRSServerFactoryBean endpoint = new JAXRSServerFactoryBean();
endpoint.setBus(bus);
endpoint.setAddress("/");
endpoint.setServiceBeans(Arrays.asList(LocationRestController ()));
return endpoint.create();
}
#Bean
public LocationRestController locationController() {
return new LocationRestControllerImpl();
}
}
Note: No need to implement a controller, you can have directly controller.

Spring Boot WebFlux test not finding MockMvc

Problem
I'm trying to run a simple spring boot test and I'm getting errors that suggest it can't MockMvc at runtime. Documentation suggests I'm using the correct annotations and I created my pom.xml using start.spring.io. Not sure why its having issues.
Error:
No qualifying bean of type 'org.springframework.test.web.servlet.MockMvc'
TestCode
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
#RunWith(SpringRunner.class)
#SpringBootTest
#AutoConfigureMockMvc
public class MyWebApplicationTests {
#Autowired
MockMvc mockMvc;
#Test
public void Can_Do_Something() throws Exception {
mockMvc.perform(get("/hello-world")).andDo(print()).andExpect(status().isOk())
.andExpect(content().string(containsString("Hello World")));
}
}
Documentation:
I was using this doc as a reference ->
https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html#boot-features-testing-spring-boot-applications-testing-with-mock-environment
POM.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mywebapp</groupId>
<artifactId>webapp</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>my-webapp</name>
<description>Backend application</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.0.M1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>10</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>javax.el</artifactId>
<version>2.2.6</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
</project>
As this Question seems to appear at the top of search lists when people are trying to test their endpoints after they've switched to Spring WebFlux, I'll add what I was able to determine here. (It should be noted that in the past I was having an incredibly hard time getting the WebTestClient to function with RestController annotated endpoints. But this code works. I think I was missing a dependency and it wasn't clear.)
MyService.java
#Service
public class MyService {
public String doSomething(String input) {
return input + " implementation";
}
}
MyController.java
#RestController
#RequestMapping(value = "/api/v1/my")
public class MyController {
#Autowired
private MyService myService;
#RequestMapping(value = "", method = RequestMethod.POST, consumes = {APPLICATION_JSON_VALUE})
public ResponseEntity<Mono<String>> processPost(#RequestBody String input)
{
String response = myService.doSomething(input);
return ResponseEntity.ok(Mono.just(response));
}
TestMyController.java
#ExtendWith(SpringExtension.class)
#WebFluxTest(MyController.class)
public class TestMyController {
#Autowired
private WebTestClient webTestClient;
#MockBean
private MyService myService;
#Test
public void testPost() throws Exception {
// Setup the Mock MyService. Note the 'mocked' vs 'implementation'
when(myService.doSomething(anyString())).thenAnswer((Answer<String>) invocation -> {
String input = invocation.getArgument(0);
return input + " mocked";
});
String response = webTestClient.post()
.uri("/api/v1/my")
.body(BodyInserters.fromObject("is"))
.accept(MediaType.APPLICATION_JSON)
.exchange()
.expectStatus().isOk()
.returnResult(String.class)
.getResponseBody()
.blockFirst();
assertThat(response).matches("is mocked");
}
}
The dependencies that can cause issues that are hard to diagnose appear to be from reactor-test. So if the WebTestClient is not working, make sure that dependency exists.
pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
<version>2.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>2.1.5.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<version>3.2.9.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<artifactId>jackson-module-kotlin</artifactId>
<groupId>com.fasterxml.jackson.module</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.4.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.truth</groupId>
<artifactId>truth</artifactId>
<version>0.45</version>
<scope>test</scope>
</dependency>
As pointed out by M. Deinum MockMvc isn't loaded for the WebFlux configuration in Spring Boot. You need to use WebTestClient instead. So replace AutoConfigureMockMvc with AutoConfigureWebTestClient and utilize the the webTestClient methods in its place.
One thing to note is that this is making actual web calls behind the scenes and will start the server. MockMVC does not start the server. What is the difference between MockMvc and WebTestClient?

extends WebSecurityConfigurerAdapter Cannot be resolved

I'm using SpringBoot I need use extends WebSecurityConfigurerAdapter for use "CORS".
But When I put "extends WebSecurityConfigurerAdapter" I have error
Description Resource Path Location Type
The type org.springframework.security.authentication.AuthenticationManager cannot be resolved. It is indirectly referenced from required .class files ServiciosConfig.java /tutorial/src/main/java/com/service/configure line 1 Java Problem
I updated pom.xml :
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
With version :
<version>1.5.14.RELEASE</version>
Code:
package com.service.configure;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.http.HttpMethod;
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.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
#Configuration
#EnableWebSecurity
#ComponentScan(basePackages = "com.service.services")
#PropertySource("file:${ruta_properties}")
public class ServiciosConfig extends WebSecurityConfigurerAdapter {
#Value("${usrRest}")
private String usrRest;
#Value("${passRest}")
private String passRest;
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.authorizeRequests().antMatchers("/").permitAll().anyRequest().authenticated().and().httpBasic().and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
// To allow Pre-flight [OPTIONS] request from browser
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers(HttpMethod.OPTIONS);
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser(usrRest).password(passRest).roles("USER");
}
}
The error begins in package com.service.configure; in p When I remove extends , package doesn't errors... But I can't use WebSecurityConfigurerAdapter obvius...
Edit pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com</groupId>
<artifactId>tutorial</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>tutorial</name>
<description>Project tutorial</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.14.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- Spring Boot -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- JPA Data -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- MySQL Connector-J -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<!-- Tomcat embedded container -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<!-- Data REST -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
</project>
change your dependency to use this
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
</dependency>
This will solve teh problem
Finally I found the solution
Add pom.xml
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>5.0.0.RELEASE</version>
</dependency>
But When I run the program I get other error...
PasswordEncoder mapped for the id “null”
I had the same issue.
I deleted my repo in .m2 folder and rebuild the application in cmd using command :
mvn clean install -U
It worked for me.
In Spring Security 5.7.0-M2 WebSecurityConfigurerAdapter was deprecated.
Refer the below link:
https://spring.io/blog/2022/02/21/spring-security-without-the-websecurityconfigureradapter

SpringBoot Application Startup Failed due to autowire JavaMailSender - version 2.0.0-snapshot

I m using Spring Boot 2.0.0.BUILD-SNAPSHOT.
I have a problem when autowiring JavaMailSender or JavaMailSenderImpl.
If i configure #Autowired for JavaMailSender, i m getting below error.
***************************
APPLICATION FAILED TO START
***************************
Description:
Field mailSender in com.hm.assetmanagment.service.MailService required a bean of type 'org.springframework.mail.javamail.JavaMailSenderImpl' that could not be found.
- Bean method 'mailSender' not loaded because #ConditionalOnClass did not find required class 'javax.mail.internet.MimeMessage'
Action:
Consider revisiting the conditions above or defining a bean of type 'org.springframework.mail.javamail.JavaMailSenderImpl' in your configuration.
Below are my pom.xml which has spring boot starter email.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.hm.assetmanagement</groupId>
<artifactId>AssetManagementSystem</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>AssetManagementSystem</name>
<description>AssetManagementSystem</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.BUILD-SNAPSHOT</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<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-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- <dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
<!-- <exclusions>
<exclusion>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
</exclusion>
</exclusions>-->
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
</project>
package com.hm.assetmanagment.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class MailService {
#Autowired
private JavaMailSenderImpl mailSender;
#RequestMapping("/assets/allocateemail/{name}/{email}/{assetid}")
private void sendAssetAllocationEmail(String name, String email, String assetid) {
/*SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
simpleMailMessage.setTo(email);
simpleMailMessage.setSubject("Asset Allocation Confirmation");
simpleMailMessage.setText("Hello " + name + "," + assetid + "\n" + " - Asset allocated to you");
mailSender.send(simpleMailMessage);*/
}
}
I tried by adding javax.mail jar/spring context support manually in dependency but it didnt work.
application.properties:
spring.mail.host=smtp.gmail.com
spring.mail.username=xxx#gmail.com
spring.mail.password=xxx
spring.mail.port=587
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console
spring.thymeleaf.cache=false
debug=true
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
Main Class:
package com.hm.assetmanagment;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
#EnableJpaRepositories
#SpringBootApplication
public class AssetManagementSystemApplication {
public static void main(String[] args) {
SpringApplication.run(AssetManagementSystemApplication.class, "--debug");
//SpringApplication.run(AssetManagementSystemApplication.class, args);
}
}
Please guide.
Update from me Nov22:
If i create new class and enable auto configuration on that class, JavaMailSender and JavaMailSenderImpl are autowired properly and spring boot application starts successfully. Already i have enableautoconfiguration in application.class as well. Is it fine to have two classes configured with enableautoconfiguration? Is there any other way to autowire JavaMailSender?
#EnableAutoConfiguration
public class MailConfig {
#Autowired
private JavaMailSenderImpl mailSender;
}
well it looks like you have not configured the Mailer at all , thus Spring cannot find the bean in order to wire it. If it was a dependency issue , then you would get a ClassNotFoundException or NoClassDefException , which is not your case.
Anyway try to configure your Mailer like this :
#Configuration
public class MailConfig {
#Bean
public JavaMailSender javaMailService() {
JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
javaMailSender.setHost("myHost");
javaMailSender.setPort(25);
javaMailSender.setJavaMailProperties(getMailProperties());
return javaMailSender;
}
private Properties getMailProperties() {
Properties properties = new Properties();
properties.setProperty("mail.transport.protocol", "smtp");
properties.setProperty("mail.smtp.auth", "false");
properties.setProperty("mail.smtp.starttls.enable", "false");
properties.setProperty("mail.debug", "false");
return properties;
}
}
Original answer here
By seeing your code , you need to add below properties to work
Sample app.yml file
spring
mail:
default-encoding: UTF-8
host: localhost
port: 8025
protocol: smtp
test-connection: false
properties.mail.smtp:
starttls.enable: true
Here is the reference
https://docs.spring.io/spring-boot/docs/2.1.x/reference/html/boot-features-email.html
make sure you are reading app properties
Change
#Autowired
private JavaMailSenderImpl mailSender;
to
#Autowired
private JavaMailSender mailSender;
The reason for this is, that by default Spring creates JDK proxies, if a bean class implements an interface. The JDK proxy implements the same interfaces as the bean class, but does not extend the class.

Configure integration test or use Spring JDBC in Unit Test using Spring Boot?

Am using the latest versions of Spring Boot, Spring JDBC, and Spring Rest...
My project is setup as a typical Maven project containing the following filesystem structure:
myproject
|
--src/main/java/com/myapp
--src/main/resource/application.properties
|
--src/test/java/com/myapp
--src/test/resources/application.properties
|
pom.xml
My application.properties are as follows (connecting to a local MySQL 5 database):
spring.datasource.url=jdbc:mysql://localhost:3306/testdb
spring.datasource.username=root
spring.datasource.password=
spring.datasource.name=testdb
spring.datasource.initialize=true
spring.datasource.driverClassName=com.mysql.jdbc.Driver
MyDAO:
public interface MyDao {
public List<App> findAllApps();
}
MyDaoImpl:
#Repository("myDao")
public class MyDaoImpl implements MyDao {
#Autowired
JdbcTemplate jdbcTemplate;
public List<App> findAllApps() {
List<App> apps = this.jdbcTemplate.query(
"select app_name from app",
new RowMapper<App>() {
public App mapRow(ResultSet rs, int rowNum) throws SQLException {
App app = new App();
app.setAppName(rs.getString("app_name"));
return app;
}
});
return apps;
}
}
Its called in MyService class using Dependency Injection:
#RestController
public class MyService {
#Autowired
#Qualifier("myDao")
MyDao myDao;
#RequestMapping(value = "/apps", method = RequestMethod.GET, consumes = "text/plain", produces = "application/json")
public void process() throws JsonParseException, IOException {
List<App> apps = myDao.findAllApps();
System.out.println(apps.toString());
}
}
This totally works as stated in my RestController...
But however, in a typical JUnit test:
public class MyServiceTest {
#Autowired
#Qualifier("myDao")
MyDao myDao;
#Test
public void process() {
List<App> apps = myDao.findAllApps();
}
}
The call to myDao.findAllApps() returns a NullPointerException...
I even tried running my app (using the embedded tomcat) first by issuing the following from the command line:
mvn spring-boot:run
However a non-database specific JUnit test works inside Eclipse or when I do:
mvn clean install
Question(s):
How can I set it up so I can run an integration test and it actually hits my database (or a mock db for that matter) from MyServiceTest?
Why is the dependency injection failing when trying to inject in MyServiceTest for Spring JDBC?
Is there a way to setup my unit tests to test Rest calls?
Many thanks for everyone who took the time to read this and many many thanks for the people that respond!
Here's my pom.xml (per Eddu's request):
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework</groupId>
<artifactId>myproject</artifactId>
<version>0.1.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.2.RELEASE</version>
</parent>
<properties>
<java.version>1.7</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-rest-webmvc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-releases</id>
<name>Spring Releases</name>
<url>https://repo.spring.io/libs-release</url>
</repository>
<repository>
<id>org.jboss.repository.releases</id>
<name>JBoss Maven Release Repository</name>
<url>https://repository.jboss.org/nexus/content/repositories/releases</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-releases</id>
<name>Spring Releases</name>
<url>https://repo.spring.io/libs-release</url>
</pluginRepository>
</pluginRepositories>
</project>
It seems you aren't loading Spring's context in your test so the dependency injection isn't performed. You should do something like:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes=Application.class) //Application being your
// Spring boot base config class
public class MyServiceTest { ... }
#Autowired
#Qualifier("myDao")
MyDao myDao;
You can have a look at an example in my github
Thanks everyone!
Steve - you were correct!
After much trial & tribulation, the #SpringApplicationConfiguration worked:
#RunWith(SpringJUnit4ClassRunner.class)
#SpringApplicationConfiguration(classes=Application.class)
Eddu Melendez - I removed the spring-starter-data-jpa dependency with spring-boot-starter-jdbc and also removed the spring-jdbc dependency from my pom.xml file.
Thank you all for trying to help me solve this issue!

Resources