Spring producing 404 for valid URL - java

I'm building a simple Spring application with the goal of returning "Hello world" as a foundation to build upon. I set up a clean project last night following this guide which worked and now I'm trying to bring an already existing project to the same functionality.
I have two files called ApplicationConfig.java and Controller.java tasked with returning a string when a certain URL is hit. When I visit localhost:8080 it renders my index.html with a link to the URL I wish to return a string at. When I visit the URL localhost:8080/home/greet it returns a 404.
My ApplicationConfig.java:
package application;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class ApplicationConfig {
public static void main(String[] args) {
SpringApplication.run (ApplicationConfig.class, args);
}
}
and my Controller.java
package controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
#RequestMapping("/home")
public class Controller {
#RequestMapping("/greet")
public String greeting() {
return "Hello";
}
}
As far as I see /home/greet/ should produce a page that just reads "Hello" but this isn't the case. What is the issue?
Here is my pom.xml and what my project structure looks like, should they be relevant.
<?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>org.springframework</groupId>
<artifactId>gs-rest-service</artifactId>
<version>0.1.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.0.RELEASE</version>
</parent>
<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>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<java.version>1.8</java.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-releases</id>
<url>https://repo.spring.io/libs-release</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-releases</id>
<url>https://repo.spring.io/libs-release</url>
</pluginRepository>
</pluginRepositories>
</project>

Your entrypoint class ApplicationConfig.java is in application package and Controller.java is in controller package.
SpringBoot scans for Spring components in the package( and sub-packages) where EntryPoint class is.
So move your controller to application or any nested package under application.

Step 1 : Add your ApplicationConfig.java in package abc.app;
Step 2 : Add your Controller.java in package abc.app.controller;.
Step 3 : add #ComponentScan("abc.app") in ApplicationConfig.java.
For Example :
ApplicationConfig.java:
package abc.app;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
#ComponentScan("abc.app")
public class ApplicationConfig {
public static void main(String[] args) {
SpringApplication.run (ApplicationConfig.class, args);
}
}
Controller.java :
package abc.app.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class Controller {
#RequestMapping("/greet")
public String greeting() {
return "Hello";
}
}
I Hope you Find your Right Solution here.

Related

SpringBootServletInitializer causes whitelabel error

I'm going through this online course about Spring MVC.
During the course the instructor is adding a simple controller, and a simple jsp page.
In addition the application class is extending SpringBootServletInitializer.
my index.html file is found in src/main/webapp and my jsp file is found in src/main/webapp/WEB-INF/jsp
I've also added spring.mvc.view.prefix/suffix accordingly.
for some reason when i get to this point at the course, extending the SpringBootServletInitializer is causing whitelabel error to my main view (index.html) but the path to jsp file is working just fine.
I've tried some suggestions as changing #Controller to #RestController or removing the SpringBootServletInitializer but it didn't work (removing the SpringBootServletInitializer caused 404 when looking for the jsp page).
here is my code:
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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.pluralSight</groupId>
<artifactId>conference</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>conference</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>11</java.version>
</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-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
controller:
package com.pluralSight.conference.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import java.util.Map;
#Controller
public class GreetingController {
#GetMapping("greeting")
public String greeting(Map<String, Object> model){
model.put("message","Hello Daniel");
return "greeting";
}
}
application class:
package com.pluralSight.conference;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
#SpringBootApplication
public class ConferenceApplication extends SpringBootServletInitializer{
public static void main(String[] args) {
SpringApplication.run(ConferenceApplication.class, args);
}
}
application.properties:
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp

Tomcat Deployment of Spring Boot is giving 404

I'm trying to deploy a Spring Boot Rest Controller on Tomcat 8. When I run it directly from Eclipse, it works fine. But when deploying it to Tomcat 8, I get a 404 error.
I've followed these instructions (https://www.baeldung.com/spring-boot-war-tomcat-deploy) and searched everywhere, but nothing seems to work.
Here is my Controller:
import java.util.Collection;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class TomcatController {
#GetMapping("/hello")
public Collection<String> sayHello() {
return IntStream.range(0, 10)
.mapToObj(i -> "Hello number " + i)
.collect(Collectors.toList());
}
}
Here is my Application:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
#SpringBootApplication
public class SsoApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(SsoApplication.class, args);
}
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(SsoApplication.class);
}
}
And here is my pom.xml:
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.test</groupId>
<artifactId>sso</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>SSOServices</name>
<description>SSO Services</description>
<packaging>war</packaging>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.0</version>
<relativePath/>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
<finalName>${artifactId}</finalName>
</build>
</project>
Any help would be greatly appreciated.
To summarize, when I test through eclipse with "localhost:8080/hello", it works.
When I deploy to tomcat 8 and test with "localhost:8080/sso/hello", I get a 404.
From M. Deinum (above)
For Spring Boot 2.4 to work you would need to use Tomcat 8.5 as minimum (not just 8) or even better tomcat 9.

this application has no explicit mapping for /error white label error

this application has no explicit mapping for /error
still displaying after making sure the main application is in the right package
made sure the application and service and controller are in right package tried using component scan as well as check dependancies
https://ibb.co/n7vhZLD : file/package order
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
#SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
Dependacies
<?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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</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.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<packaging>war</packaging>
Controller
import java.util.ArrayList;
import java.util.Hashtable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import model.Car;
import service.CarService;
#CrossOrigin
#RestController
#RequestMapping("/car")
public class CarController {
#Autowired
CarService cs;
#RequestMapping("/all")
public ArrayList<Car> getAll() {
return cs.getAll();
}
#RequestMapping("{id}")
public Car getCar(#PathVariable("id") String id) {
return cs.getCar(id);
}
}
Take a look at you package structure Main class DemoApplication is in com.example.demo package
package com.example.demo;
#SpringBootApplication
public class DemoApplication {
And CarService is in package service.CarService
import service.CarService;
#Autowired
CarService cs;
In the same way CarController might be in different package which are not in organised structure.
By default #SpringBootApplication perform component scan scanning from the package of the class that declares this annotation. Since your service and controller classes are not in sub packages of base package you need to explicitly add#ComponentScan
#SpringBootApplication
#ComponentScan({"service","controller"})
public class DemoApplication {

SpringBoot - HelloWorld

I want to create a simple hello world app with SpringBoot where localhost:8080/welcome.html will show us Hello World.
I think I did all good but I can't see HelloWorld, just Whitelabel error page.
This is the link to my repo. If someone could check what is wrong I will be very happy!
https://github.com/BElluu/ElenXHello
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.springbelluu</groupId>
<artifactId>springboot-helloworld</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>springboot-helloworld</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.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>10</java.version>
</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.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</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>
SpringbootHelloworldApplication.java
package com.springbelluu.springboothelloworld;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class SpringbootHelloworldApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootHelloworldApplication.class, args);
}
}
TestController.java
package com.javainuse.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class TestController {
#RequestMapping("/welcome.html")
public ModelAndView firstPage() {
return new ModelAndView("welcome");
}
}
application.properties
spring.mvc.view.prefix:/WEB-INF/jsp/
spring.mvc.view.suffix:.jsp
For starters if you want to get starter with Spring Boot I strongly suggest NOT to use JSP. There are quite some limitations when using JSP, one of them is it doesn't work with jar packaging. Secondly it is a dated technology and doesn't receive much attention/updates anymore apart from keeping if functional in newer JEE versions. It is better to use something like Thymeleaf.
Next you are using snapshots versions for a version of Spring Boot that already is at 2.1.3.RELEASE (at the moment of writing).
That being said change your pom.xml to the following (fix version, remove JSP stuff and replace with Thymeleaf).
<?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.springbelluu</groupId>
<artifactId>springboot-helloworld</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>springboot-helloworld</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<java.version>10</java.version>
</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-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
NOTE: Because you now use a final version you don't need all the repositories in your pom.xml anymore!.
Now delete your JSP and create a welcome.html in src/main/resources/templates/. (You can actually remove your webapp directory in full.
<html>
<body>
<h1>Welcome! Spring Boot for ElenX</h1>
</body>
</html>
The setup you now have is more modern and easier to work with then JSP.
In your application.properties remove the spring.mvc.view properties as Spring Boot will automatically configure Thymeleaf with correct settings.
#BElluu ... your main application and Controller class are in different packages so componentscan is not working ...just check package level
package com.springbelluu.springboothelloworld;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class SpringbootHelloworldApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootHelloworldApplication.class, args);
}
}
package com.javainuse.controllers;
// use this package package com.springbelluu.springboothelloworld;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class TestController {
#RequestMapping("/welcome.html")
public ModelAndView firstPage() {
return new ModelAndView("welcome");
}
}
Go to below link by Spring Framework to create brand new Springboot Project:
https://start.spring.io/
or
1.Create a simple web application
Now you can create a web controller for a simple web application.
src/main/java/hello/HelloController.java
package hello;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
#RestController
public class HelloController {
#RequestMapping("/")
public String index() {
return "Greetings from Spring Boot!";
}
}
Create an Application class
Here you create an Application class with the components:
src/main/java/hello/Application.java
package hello;
import java.util.Arrays;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
#Bean
public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
return args -> {
System.out.println("Let's inspect the beans provided by Spring Boot:");
String[] beanNames = ctx.getBeanDefinitionNames();
Arrays.sort(beanNames);
for (String beanName : beanNames) {
System.out.println(beanName);
}
};
}
}
Here is SpringBoot Main class file Noting Changed Here.
-----------------------------------------
package com.Encee.SpringBoot_HelloWorld;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class SpringBootHelloWorldApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootHelloWorldApplication.class, args);
}
}
Here is controller package class
-----------------------------------------
package com.Encee.SpringBoot_HelloWorld.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class Controller {
#RequestMapping("/hello.html")
public String hello() {
return "Hello World";
}
}
-----------------------------------------
Now Main file run as Java Application will get your output.
SCREEN SHOT
Your issue has been fixed you can view the changes at my commit.
https://github.com/farooqrahu/ElenXHello/commits/master

Unable to override spring security default basic authentication of rest API

I am new to spring environment and was trying my hand at spring security, but I am unable to achieve basic authentication.
When I add spring security starter to maven dependencies I get default basic authentication by spring with user = user & password generated when you run the app. So far this works fine.
But now even though I have added SecurityConfiguration the default behaviour doesn't go away. If I try to access the resource through my new credentials I get Bad credentials message.
I am stuck here as for why spring still uses the default configuration, as with all the tutorials I have followed this works fine.
Referenced Tutorials
https://www.youtube.com/watch?v=rOnoKiH97Nc
https://www.youtube.com/watch?v=kiIMCzEN3c0
https://www.youtube.com/watch?v=3s2lSD50-JI
pom.xml
<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.worldline.in</groupId>
<artifactId>maven_springboot_rest</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>maven_springboot_rest</name>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.1.RELEASE</version>
</parent>
<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>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
</dependencies>
<properties>
<java.version>1.8</java.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-releases</id>
<url>https://repo.spring.io/libs-release</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-releases</id>
<url>https://repo.spring.io/libs-release</url>
</pluginRepository>
</pluginRepositories>
</project>
Application.java
package com.worldline.rest;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
// Tried component scan too -----
// https://stackoverflow.com/questions/38072517/unable-to-override-spring-boots-default-security-configuration
//#ComponentScan({"com.worldline.config"})
//some stackoverflow links suggest to exclude it for default behavior to go away
//#SpringBootApplication (exclude = {SecurityAutoConfiguration.class })
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Rest Controller
package com.worldline.rest;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.worldline.pojo.Greeting;
#RestController
public class GreetingController {
private final AtomicLong counter = new AtomicLong();
#RequestMapping("/greeting")
public Greeting greeting(#RequestParam(value="name", defaultValue = "world") String name )
{
return new Greeting(counter.incrementAndGet(), name);
}
}
Security Configuration
package com.worldline.config;
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;
import org.springframework.security.config.http.SessionCreationPolicy;
#Configuration
#EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
/*http.authorizeRequests()
.anyRequest()
.fullyAuthenticated()
.and().httpBasic();
http.csrf().disable();*/
http.authorizeRequests()
.antMatchers("/greeting").hasRole("ADMIN");
}
/*#Override
protected void configure(AuthenticationManagerBuilder auth)
throws Exception {
auth.inMemoryAuthentication().withUser("sunny").password("admin").roles("admin");
}
*/
#Autowired
protected void configureGlobal(AuthenticationManagerBuilder auth) throws Exception
{
auth.inMemoryAuthentication().withUser("sunny").password("admin").roles("ADMIN");
}
}

Categories