Login failure using Spring Security - spring-boot

This is my first time using Spring-security and I am struggling a lot with it trying to learn along with implementation. I am trying to implement Login and registration functionality using Spring-security where my registration functionality is seems to be working fine, whereas for login one I am getting stuck:
2021-07-14 08:30:51.911 INFO 17152 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2021-07-14 08:30:51.915 INFO 17152 --- [ restartedMain] o.s.b.a.h2.H2ConsoleAutoConfiguration : H2 console available at '/h2-console'. Database available at 'jdbc:mysql://localhost:3306/journeyfood?useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC'
2021-07-14 08:30:52.044 DEBUG 17152 --- [ restartedMain] o.s.w.s.r.ResourceUrlEncodingFilter : Filter 'resourceUrlEncodingFilter' configured for use
2021-07-14 08:30:52.481 INFO 17152 --- [ restartedMain] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2021-07-14 08:30:52.774 INFO 17152 --- [ restartedMain] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.4.30.Final
2021-07-14 08:30:53.348 INFO 17152 --- [ restartedMain] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2021-07-14 08:30:53.719 INFO 17152 --- [ restartedMain] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL8Dialect
2021-07-14 08:30:54.979 INFO 17152 --- [ restartedMain] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2021-07-14 08:30:55.005 INFO 17152 --- [ restartedMain] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2021-07-14 08:30:55.671 WARN 17152 --- [ restartedMain] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2021-07-14 08:30:56.069 INFO 17152 --- [ restartedMain] o.s.s.web.DefaultSecurityFilterChain : Will secure Ant [pattern='/resources/**'] with []
2021-07-14 08:30:56.069 INFO 17152 --- [ restartedMain] o.s.s.web.DefaultSecurityFilterChain : Will secure Ant [pattern='/static/**'] with []
2021-07-14 08:30:56.095 INFO 17152 --- [ restartedMain] o.s.s.web.DefaultSecurityFilterChain : Will secure any request with [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter#44e06dde, org.springframework.security.web.context.SecurityContextPersistenceFilter#5e3ab505, org.springframework.security.web.header.HeaderWriterFilter#77868cf5, org.springframework.security.web.authentication.logout.LogoutFilter#6aead47, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#4419107, org.springframework.security.web.savedrequest.RequestCacheAwareFilter#6df74d9c, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter#99c0cbf, org.springframework.security.web.authentication.AnonymousAuthenticationFilter#2636db06, org.springframework.security.web.session.SessionManagementFilter#6b0130ed, org.springframework.security.web.access.ExceptionTranslationFilter#7af2b0cb, org.springframework.security.web.access.intercept.FilterSecurityInterceptor#53fb5de]
2021-07-14 08:30:56.278 INFO 17152 --- [ restartedMain] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2021-07-14 08:30:56.287 DEBUG 17152 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerAdapter : ControllerAdvice beans: 0 #ModelAttribute, 0 #InitBinder, 1 RequestBodyAdvice, 1 ResponseBodyAdvice
2021-07-14 08:30:56.366 DEBUG 17152 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : 7 mappings in 'requestMappingHandlerMapping'
2021-07-14 08:30:56.371 INFO 17152 --- [ restartedMain] o.s.b.a.w.s.WelcomePageHandlerMapping : Adding welcome page template: index
2021-07-14 08:30:56.935 DEBUG 17152 --- [ restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping : Patterns [/webjars/**, /**] in 'resourceHandlerMapping'
2021-07-14 08:30:56.944 DEBUG 17152 --- [ restartedMain] .m.m.a.ExceptionHandlerExceptionResolver : ControllerAdvice beans: 0 #ExceptionHandler, 1 ResponseBodyAdvice
2021-07-14 08:30:57.217 INFO 17152 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729
2021-07-14 08:30:57.352 INFO 17152 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path '/JourneyFood'
2021-07-14 08:30:57.365 INFO 17152 --- [ restartedMain] o.b.journeyfood.JourneyFoodApplication : Started JourneyFoodApplication in 13.587 seconds (JVM running for 17.039)
2021-07-14 08:31:12.439 INFO 17152 --- [nio-8080-exec-1] o.a.c.c.C.[.[localhost].[/JourneyFood] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2021-07-14 08:31:12.440 INFO 17152 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2021-07-14 08:31:12.440 DEBUG 17152 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Detected StandardServletMultipartResolver
2021-07-14 08:31:12.440 DEBUG 17152 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Detected AcceptHeaderLocaleResolver
2021-07-14 08:31:12.440 DEBUG 17152 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Detected FixedThemeResolver
2021-07-14 08:31:12.441 DEBUG 17152 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Detected org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator#2bed12c2
2021-07-14 08:31:12.441 DEBUG 17152 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Detected org.springframework.web.servlet.support.SessionFlashMapManager#58fa7aae
2021-07-14 08:31:12.441 DEBUG 17152 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : enableLoggingRequestDetails='false': request parameters and headers will be masked to prevent unsafe logging of potentially sensitive data
2021-07-14 08:31:12.441 INFO 17152 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 1 ms
2021-07-14 08:31:12.450 DEBUG 17152 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy : Securing GET /login
2021-07-14 08:31:12.473 DEBUG 17152 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy : Secured GET /login
2021-07-14 08:31:12.477 DEBUG 17152 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : GET "/JourneyFood/login", parameters={}
2021-07-14 08:31:12.483 DEBUG 17152 --- [nio-8080-exec-1] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to org.brahmakumaris.journeyfood.controller.HomeController#login(Model)
2021-07-14 08:31:12.529 DEBUG 17152 --- [nio-8080-exec-1] o.s.w.s.v.ContentNegotiatingViewResolver : Selected 'text/html' given [text/html, application/xhtml+xml, image/webp, application/xml;q=0.9, */*;q=0.8]
2021-07-14 08:31:13.021 DEBUG 17152 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed 200 OK
2021-07-14 08:31:13.042 DEBUG 17152 --- [nio-8080-exec-2] o.s.security.web.FilterChainProxy : Securing GET /webjars/bootstrap/4.0.0-2/css/bootstrap.min.css
2021-07-14 08:31:13.042 DEBUG 17152 --- [nio-8080-exec-3] o.s.security.web.FilterChainProxy : Securing GET /webjars/bootstrap/4.0.0-2/js/bootstrap.min.js
2021-07-14 08:31:13.042 DEBUG 17152 --- [nio-8080-exec-3] o.s.security.web.FilterChainProxy : Secured GET /webjars/bootstrap/4.0.0-2/js/bootstrap.min.js
2021-07-14 08:31:13.042 DEBUG 17152 --- [nio-8080-exec-2] o.s.security.web.FilterChainProxy : Secured GET /webjars/bootstrap/4.0.0-2/css/bootstrap.min.css
2021-07-14 08:31:13.043 DEBUG 17152 --- [nio-8080-exec-3] o.s.web.servlet.DispatcherServlet : GET "/JourneyFood/webjars/bootstrap/4.0.0-2/js/bootstrap.min.js", parameters={}
2021-07-14 08:31:13.043 DEBUG 17152 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : GET "/JourneyFood/webjars/bootstrap/4.0.0-2/css/bootstrap.min.css", parameters={}
2021-07-14 08:31:13.046 DEBUG 17152 --- [nio-8080-exec-3] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler [Classpath [META-INF/resources/webjars/]]
2021-07-14 08:31:13.046 DEBUG 17152 --- [nio-8080-exec-2] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler [Classpath [META-INF/resources/webjars/]]
2021-07-14 08:31:13.166 DEBUG 17152 --- [nio-8080-exec-3] o.s.web.servlet.DispatcherServlet : Completed 200 OK
2021-07-14 08:31:13.168 DEBUG 17152 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : Completed 200 OK
2021-07-14 08:31:30.939 DEBUG 17152 --- [nio-8080-exec-5] o.s.security.web.FilterChainProxy : Securing POST /login
Email:
2021-07-14 08:31:31.325 DEBUG 17152 --- [nio-8080-exec-6] o.s.security.web.FilterChainProxy : Securing GET /login?error=true
2021-07-14 08:31:31.326 DEBUG 17152 --- [nio-8080-exec-6] o.s.security.web.FilterChainProxy : Secured GET /login?error=true
2021-07-14 08:31:31.327 DEBUG 17152 --- [nio-8080-exec-6] o.s.web.servlet.DispatcherServlet : GET "/JourneyFood/login?error=true", parameters={masked}
2021-07-14 08:31:31.328 DEBUG 17152 --- [nio-8080-exec-6] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to org.brahmakumaris.journeyfood.controller.HomeController#login(Model)
2021-07-14 08:31:31.329 DEBUG 17152 --- [nio-8080-exec-6] o.s.w.s.v.ContentNegotiatingViewResolver : Selected 'text/html' given [text/html, application/xhtml+xml, image/webp, application/xml;q=0.9, */*;q=0.8]
2021-07-14 08:31:31.361 DEBUG 17152 --- [nio-8080-exec-6] o.s.web.servlet.DispatcherServlet : Completed 200 OK
2021-07-14 08:31:31.383 DEBUG 17152 --- [nio-8080-exec-8] o.s.security.web.FilterChainProxy : Securing GET /webjars/bootstrap/4.0.0-2/js/bootstrap.min.js
2021-07-14 08:31:31.384 DEBUG 17152 --- [nio-8080-exec-8] o.s.security.web.FilterChainProxy : Secured GET /webjars/bootstrap/4.0.0-2/js/bootstrap.min.js
2021-07-14 08:31:31.384 DEBUG 17152 --- [nio-8080-exec-8] o.s.web.servlet.DispatcherServlet : GET "/JourneyFood/webjars/bootstrap/4.0.0-2/js/bootstrap.min.js", parameters={}
2021-07-14 08:31:31.384 DEBUG 17152 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy : Securing GET /webjars/bootstrap/4.0.0-2/css/bootstrap.min.css
2021-07-14 08:31:31.384 DEBUG 17152 --- [nio-8080-exec-8] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler [Classpath [META-INF/resources/webjars/]]
2021-07-14 08:31:31.385 DEBUG 17152 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy : Secured GET /webjars/bootstrap/4.0.0-2/css/bootstrap.min.css
2021-07-14 08:31:31.385 DEBUG 17152 --- [nio-8080-exec-7] o.s.web.servlet.DispatcherServlet : GET "/JourneyFood/webjars/bootstrap/4.0.0-2/css/bootstrap.min.css", parameters={}
2021-07-14 08:31:31.385 DEBUG 17152 --- [nio-8080-exec-7] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler [Classpath [META-INF/resources/webjars/]]
2021-07-14 08:31:31.391 DEBUG 17152 --- [nio-8080-exec-8] o.s.web.servlet.DispatcherServlet : Completed 200 OK
2021-07-14 08:31:31.395 DEBUG 17152 --- [nio-8080-exec-7] o.s.web.servlet.DispatcherServlet : Completed 200 OK
When I debugged through I found that username String in loadUserByUserName(String username) is empty(""). Please do let me know what I am doing wrong here. Please find source code here for same.
public class CustomUserDetailsService implements UserDetailsService {
#Autowired
private UserRepository userRepo;
#Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {//username is coming null
// TODO Auto-generated method stub
UserEntity user = userRepo.findByEmail(username);
System.out.println("Email: "+username);
if(user==null) {
throw new UsernameNotFoundException(user.getEmail()+" is not registered, please register before logging in.");
}
return new CustomUserDetails(user);
}
}
This is how my UserDetails class looks like -
CustomUserDetails
public class CustomUserDetails implements UserDetails {
private UserEntity user;
#Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return null;
}
public CustomUserDetails(UserEntity user) {
super();
this.user = user;
}
#Override
public String getPassword() {
// TODO Auto-generated method stub
return user.getPassword();
}
#Override
public String getUsername() {
// TODO Auto-generated method stub
return user.getEmail();
}
#Override
public boolean isAccountNonExpired() {
// TODO Auto-generated method stub
return true;
}
#Override
public boolean isAccountNonLocked() {
// TODO Auto-generated method stub
return true;
}
#Override
public boolean isCredentialsNonExpired() {
// TODO Auto-generated method stub
return true;
}
#Override
public boolean isEnabled() {
// TODO Auto-generated method stub
return user.isEnabled();
}
public String getNameOfGuide() {
return user.getNameOfGuide() ;
}
}
This is main UserEntity class getting used for database connectivity
UserEntity
#Entity
#Table(name="users")
public class UserEntity {
#Id
#Column(name = "user_id")
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#Column(nullable = false, length = 100)
private String nameOfCenter;
#Column(nullable = false, length = 100)
private String nameOfGuide;
#Column(nullable = false, unique = true, length = 18)
private String contactNoOfGuide;
#Column(nullable = false, unique = true, length = 70)
private String email;
#Column(nullable = false, length = 150)
private String password;
private boolean enabled;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getNameOfCenter() {
return nameOfCenter;
}
public void setNameOfCenter(String nameOfCenter) {
this.nameOfCenter = nameOfCenter;
}
public String getNameOfGuide() {
return nameOfGuide;
}
public void setNameOfGuide(String nameOfGuide) {
this.nameOfGuide = nameOfGuide;
}
public String getContactNoOfGuide() {
return contactNoOfGuide;
}
public void setContactNoOfGuide(String contactNoOfGuide) {
this.contactNoOfGuide = contactNoOfGuide;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
#Override
public String toString() {
return "UserEntity [id=" + id + ", nameOfCenter=" + nameOfCenter + ", nameOfGuide="
+ nameOfGuide + ", contactNoOfGuide=" + contactNoOfGuide + ", email=" + email + ", password=" + password
+ ", enabled=" + enabled + "]";
}
}
In WebSecurityConfig I have create login-success as on-success authentication landing page otherwise it should give 403 and ask to relogin with invalid credentials:
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Bean
public UserDetailsService userDetailsService() {
return new CustomUserDetailsService();
}
#Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder() ;
}
#Bean
public DaoAuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
authProvider.setUserDetailsService(userDetailsService());
authProvider.setPasswordEncoder(passwordEncoder());
return authProvider;
}
#Override
protected void configure(AuthenticationManagerBuilder auth) {
auth.authenticationProvider(authenticationProvider());
}
#Override
protected void configure(HttpSecurity http)throws Exception{
http.authorizeRequests()
.antMatchers("/users").authenticated()
.antMatchers("/addJourneyFoodOrder").authenticated()
.antMatchers("/edit/**").authenticated()
.antMatchers("/delete/**").authenticated()
.antMatchers("/h2-console/**","/login","/register").permitAll()
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/login-success")
.failureUrl("/login?error=true")
.and()
.logout().logoutSuccessUrl("/login").permitAll()
.and()
.exceptionHandling().accessDeniedPage("/403");
http.csrf().disable();
http.headers().frameOptions().disable();
}
#Override
public void configure(WebSecurity web) {
web.ignoring()
.antMatchers("/resources/**", "/static/**");
}
}
HomeController
#Controller
public class HomeController {
#Autowired
private JourneyFoodService journeyFoodServiceImpl;
#Autowired
private UserService userService;
#GetMapping("/register")
public String register(final Model model) {
model.addAttribute("user", new UserSignUpFormData());
return "register";
}
#PostMapping("/register")//Post operation
public ModelAndView register(#Valid #ModelAttribute("user")UserSignUpFormData user, BindingResult result,HttpServletRequest request) {
ModelAndView mav = new ModelAndView("register", "user", user);
if (result.hasErrors()) {
return mav;
}
else {
try {
userService.register(user);System.out.println(user);
}catch (UserAlreadyExistException e){
mav.addObject("message", "An account with this email already exists.");
return mav;
}
return new ModelAndView("signup-success", "user", user);
}
}
#GetMapping("/login")//to fetch form
public String login(Model model) {
model.addAttribute("user", new UserEntity());
return "login";
}
}
login.html
<html xmlns:th="http://www.thymeleaf.org" xmlns:tiles="http://www.thymeleaf.org">
<head>
<title tiles:fragment="title">Messages : Create</title>
<link th:rel="stylesheet" th:href="#{/webjars/bootstrap/4.0.0-2/css/bootstrap.min.css} "/>
<script th:src="#{/webjars/bootstrap/js/bootstrap.min.js}"></script>
</head>
<body>
<div class="container">
<form th:action="#{/login}" th:object="${user}" method="post" class="form-signin">
<div>
<div th:if="${param.error}" class="alert alert-danger" role="alert" ><h3>Mandatory field validation Errors:</h3>
<p class="error"> Invalid credentials</p>
</div>
</div>
<h2 class="mb-5">Login</h2>
<div class="form-group">
<label for="nameOfCenter">Email:</label>
<input type="email" th:field="*{email}" class="form-control" placeholder="Enter email">
</div>
<div class="form-group">
<label for="password">Password: </label>
<input type="password" th:field="*{password}" class="form-control" placeholder="Enter password">
</div>
<button class="btn btn-primary" type="submit">Login</button>
</form>
</div>
</body>
</html>
Please help me out with this issue as I am unable to figure out what is going wrong with code and what needs to be changed.

The email field does not have a name associated with it.
By default the "/login" endpoint expects a parameter named "username".
To send the email as the username parameter, you need to add a name to the email field.
<input name="username" type="email" th:field="*{email}" class="form-control" placeholder="Enter email">
You will probably face the same issue with the password field.
To see what parameters are being sent, you can view the "/login" request in the browser Network tab.

Related

Postman - 401 unauthorized status | Spring Boot

I prepared very simple REST APi.
I am trying to do requests with postman but i get 401 Unauthorized. No matter what kind request it is. I have Windows 11 system, Java 11, Postman Version 9.8.2
Postman:
application.properties file:
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost:3306/students
spring.datasource.username=
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.show-sql=true
Spring Application:
#SpringBootApplication(exclude = {UserDetailsServiceAutoConfiguration.class})
public class StudentsmanagerApplication {
public static void main(String[] args) {
SpringApplication.run(StudentsmanagerApplication.class, args);
}
Controller class:
#RestController
#RequestMapping("/student")
public class StudentController {
private StudentService studentService;
#GetMapping
public ResponseEntity<List<Student>> getAllStudents() {
List<Student> students = studentService.findAllStudent();
return new ResponseEntity<>(students, HttpStatus.OK);
}
#GetMapping("find/{id}")
public ResponseEntity<Student> getAllStudentsById(#PathVariable Long id) {
Student student = studentService.findStudentById(id);
return new ResponseEntity<>(student, HttpStatus.OK);
}
#PostMapping
public ResponseEntity<Student> addEmployee(#RequestBody Student student) {
Student newStudent = studentService.addStudent(student);
return new ResponseEntity<>(newStudent, HttpStatus.CREATED);
}
#PutMapping("/{id}")
public ResponseEntity<Student> updateStudent(#PathVariable Long id, #RequestBody Student
student) {
Student updatedStudent = studentService.updateStudent(id, student);
return new ResponseEntity<>(updatedStudent, HttpStatus.UPGRADE_REQUIRED);
}
#DeleteMapping("/{id}")
public ResponseEntity<?> deleteStudent(#PathVariable Long id) {
studentService.deleteStudent(id);
return new ResponseEntity<>(HttpStatus.OK);
}
Service class:
#Service
public class StudentService {
private StudentRepository studentRepository;
public Student addStudent(Student student) {
student.setStudentCode(UUID.randomUUID().toString());
return studentRepository.save(student);
}
public List<Student> findAllStudent() {
return studentRepository.findAll();
}
public Student updateStudent(Long id, Student student) {
Student studentById = studentRepository
.findById(id).orElseThrow(() -> new StudentNotFoundException("Student by id
" + " doesn't Exist"));
studentById.setName(student.getName());
studentById.setLastName(student.getLastName());
studentById.setEmail(student.getEmail());
studentById.setPhone(student.getPhone());
return studentRepository.save(studentById);
}
public Student findStudentById(Long id) {
return studentRepository
.findById(id).orElseThrow(() -> new StudentNotFoundException("Student
doesn't exist "));
}
public void deleteStudent(Long id) {
studentRepository.deleteById(id);
}
Spring logs:
2022-01-08 10:53:19.661 INFO 20120 --- [ main] p.s.s.StudentsmanagerApplication : Starting StudentsmanagerApplication using Java 11.0.13 on LAPTOP-9F9MO24J with PID 20120 (C:\Users\mkord\IdeaProjects\studentsmanager\target\classes started by mkord in C:\Users\mkord\IdeaProjects\studentsmanager)
2022-01-08 10:53:19.661 INFO 20120 --- [ main] p.s.s.StudentsmanagerApplication : No active profile set, falling back to default profiles: default
2022-01-08 10:53:20.539 INFO 20120 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2022-01-08 10:53:20.596 INFO 20120 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 50 ms. Found 1 JPA repository interfaces.
2022-01-08 10:53:21.262 INFO 20120 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2022-01-08 10:53:21.278 INFO 20120 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2022-01-08 10:53:21.278 INFO 20120 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.56]
2022-01-08 10:53:21.422 INFO 20120 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2022-01-08 10:53:21.422 INFO 20120 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1684 ms
2022-01-08 10:53:21.662 INFO 20120 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2022-01-08 10:53:21.703 INFO 20120 --- [ main] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.6.3.Final
2022-01-08 10:53:21.856 INFO 20120 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2022-01-08 10:53:21.976 INFO 20120 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2022-01-08 10:53:22.336 INFO 20120 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2022-01-08 10:53:22.352 INFO 20120 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL8Dialect
2022-01-08 10:53:22.968 INFO 20120 --- [ main] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2022-01-08 10:53:22.984 INFO 20120 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2022-01-08 10:53:23.032 WARN 20120 --- [ main] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2022-01-08 10:53:23.824 INFO 20120 --- [ main] o.s.s.web.DefaultSecurityFilterChain : Will secure any request with [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter#36931450, org.springframework.security.web.context.SecurityContextPersistenceFilter#451a4187, org.springframework.security.web.header.HeaderWriterFilter#6db04a6, org.springframework.security.web.csrf.CsrfFilter#630c3af3, org.springframework.security.web.authentication.logout.LogoutFilter#4866e0a7, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#66d44581, org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter#4ac0d49, org.springframework.security.web.authentication.ui.DefaultLogoutPageGeneratingFilter#74919649, org.springframework.security.web.authentication.www.BasicAuthenticationFilter#2ea4e762, org.springframework.security.web.savedrequest.RequestCacheAwareFilter#5c215642, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter#1317ac2c, org.springframework.security.web.authentication.AnonymousAuthenticationFilter#7d07e04e, org.springframework.security.web.session.SessionManagementFilter#426913c4, org.springframework.security.web.access.ExceptionTranslationFilter#38197e82, org.springframework.security.web.access.intercept.FilterSecurityInterceptor#5a07ae2f]
2022-01-08 10:53:23.914 INFO 20120 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2022-01-08 10:53:23.930 INFO 20120 --- [ main] p.s.s.StudentsmanagerApplication : Started StudentsmanagerApplication in 4.851 seconds (JVM running for 6.309)
2022-01-08 10:59:13.709 INFO 20120 --- [nio-8080-exec-2] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2022-01-08 10:59:13.709 INFO 20120 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2022-01-08 10:59:13.709 INFO 20120 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : Completed initialization in 0 ms
2022-01-08 10:59:13.941 WARN 20120 --- [nio-8080-exec-2] o.a.c.util.SessionIdGeneratorBase : Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took [184] milliseconds.
Thank You in advance for any suggestion

Spring Security ignoring roles

I have this controller:
#RestController
public class NumbersController {
#PreAuthorize("hasRole('ROLE_ONE')")
#GetMapping("/one")
private String one(){
return "This is one.";
}
#PreAuthorize("hasRole('ROLE_TWO')")
#GetMapping("/two")
private String two(){
return "This is two.";
}
}
And this security configuration:
#Configuration
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends GlobalMethodSecurityConfiguration {
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
auth
.inMemoryAuthentication()
.withUser("user").password(encoder.encode("password")).roles("ONE");
auth
.inMemoryAuthentication()
.withUser("user2").password(encoder.encode("password2")).roles("TWO");
}
}
And while running both of my users can access both of the resources. What I want is only for user to be able to access /one and only for user2 to access /two.
I also tried using #Secured("ONE") with the same result.
Console output:
2021-01-14 16:10:20.026 INFO 4376 --- [ main] security.security.SecurityApplication : Starting SecurityApplication on Ivan-PC with PID 4376 (D:\Z\security\target\classes started by Ivan in D:\Z\security)
2021-01-14 16:10:20.041 INFO 4376 --- [ main] security.security.SecurityApplication : No active profile set, falling back to default profiles: default
2021-01-14 16:10:24.363 INFO 4376 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2021-01-14 16:10:24.378 INFO 4376 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2021-01-14 16:10:24.378 INFO 4376 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.41]
2021-01-14 16:10:24.565 INFO 4376 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2021-01-14 16:10:24.565 INFO 4376 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 4321 ms
2021-01-14 16:10:25.221 INFO 4376 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2021-01-14 16:10:25.860 INFO 4376 --- [ main] o.s.s.web.DefaultSecurityFilterChain : Creating filter chain: any request, [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter#57a48985, org.springframework.security.web.context.SecurityContextPersistenceFilter#17740dae, org.springframework.security.web.header.HeaderWriterFilter#14bf57b2, org.springframework.security.web.csrf.CsrfFilter#48535004, org.springframework.security.web.authentication.logout.LogoutFilter#3cee53dc, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#67440de6, org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter#35835e65, org.springframework.security.web.authentication.ui.DefaultLogoutPageGeneratingFilter#1ab6718, org.springframework.security.web.authentication.www.BasicAuthenticationFilter#7ce7e83c, org.springframework.security.web.savedrequest.RequestCacheAwareFilter#345cf395, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter#7144655b, org.springframework.security.web.authentication.AnonymousAuthenticationFilter#3910fe11, org.springframework.security.web.session.SessionManagementFilter#14379273, org.springframework.security.web.access.ExceptionTranslationFilter#cfbc8e8, org.springframework.security.web.access.intercept.FilterSecurityInterceptor#49293b43]
2021-01-14 16:10:25.969 INFO 4376 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2021-01-14 16:10:25.985 INFO 4376 --- [ main] security.security.SecurityApplication : Started SecurityApplication in 6.771 seconds (JVM running for 8.031)
2021-01-14 16:10:29.847 INFO 4376 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2021-01-14 16:10:29.848 INFO 4376 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2021-01-14 16:10:29.870 INFO 4376 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 22 ms
The requests are made with Postman to http://localhost:8080/two and using the authorization fields.
Check this if it helps,
We can configure multiple HttpSecurity instances just as we can have multiple blocks. The key is to extend the WebSecurityConfigurerAdapter multiple times. For example, the following is an example of having a different configuration for URL’s that start with /api/.
#EnableWebSecurity
public class MultiHttpSecurityConfig {
#Bean
public UserDetailsService userDetailsService() throws Exception {
// ensure the passwords are encoded properly
UserBuilder users = User.withDefaultPasswordEncoder();
InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
manager.createUser(users.username("user").password("password").roles("USER").build());
manager.createUser(users.username("admin").password("password").roles("USER","ADMIN").build());
return manager;
}
#Configuration
#Order(1)
public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception {
http
.antMatcher("/api/**")
.authorizeRequests(authorize -> authorize
.anyRequest().hasRole("ADMIN")
)
.httpBasic(withDefaults());
}
}
#Configuration
public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests(authorize -> authorize
.anyRequest().authenticated()
)
.formLogin(withDefaults());
}
}
}
Configure Authentication as normal
Create an instance of WebSecurityConfigurerAdapter that contains #Order to specify which WebSecurityConfigurerAdapter should be considered first.
The http.antMatcher states that this HttpSecurity will only be applicable to URLs that start with /api/
Create another instance of WebSecurityConfigurerAdapter.
If the URL does not start with /api/ this configuration will be used.
This configuration is considered after ApiWebSecurityConfigurationAdapter since it has an #Order value after 1 (no #Order defaults to last).
Try out this in your SecurityConfig class
#EnableGlobalMethodSecurity(
prePostEnabled = true,
jsr250Enabled = true)
The prePostEnabled property enables Spring Security pre/post annotations
The jsr250Enabled property allows us to use the #RoleAllowed annotation

Spring boot returning error 404 html page not found

I'm trying to return index.html which is placed under src/main/resources/templates but it seems that it is not loading.
StackTrace
2020-07-24 00:09:11.881 DEBUG 17204 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : GET "/", parameters={}
2020-07-24 00:09:11.884 DEBUG 17204 --- [nio-8080-exec-1] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to com.Alex.Flights.FlightsController#getIndexForm(ModelMap)
2020-07-24 00:09:11.885 DEBUG 17204 --- [nio-8080-exec-1] o.j.s.OpenEntityManagerInViewInterceptor : Opening JPA EntityManager in OpenEntityManagerInViewInterceptor
2020-07-24 00:09:11.902 DEBUG 17204 --- [nio-8080-exec-1] o.s.w.s.v.ContentNegotiatingViewResolver : Selected 'text/html' given [text/html, application/xhtml+xml, image/webp, application/xml;q=0.9, */*;q=0.8]
2020-07-24 00:09:11.902 DEBUG 17204 --- [nio-8080-exec-1] o.s.w.servlet.view.InternalResourceView : View name 'index', model {userForm=Flights [flightNumber=dummy, origin=dummy, destination=dummy, takeOffTime=dummy, landingTime=dummy, flightDuration=dummy, takeOffDate=Fri Jul 24 00:09:11 SGT 2020, landingDate=Fri Jul 24 00:09:11 SGT 2020, flightReturn=false], org.springframework.validation.BindingResult.userForm=org.springframework.validation.BeanPropertyBindingResult: 0 errors}
2020-07-24 00:09:11.903 DEBUG 17204 --- [nio-8080-exec-1] o.s.w.servlet.view.InternalResourceView : Forwarding to [index]
2020-07-24 00:09:11.905 DEBUG 17204 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : "FORWARD" dispatch for GET "/index", parameters={}
2020-07-24 00:09:11.907 DEBUG 17204 --- [nio-8080-exec-1] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/", "/"]
2020-07-24 00:09:11.908 DEBUG 17204 --- [nio-8080-exec-1] o.s.w.s.r.ResourceHttpRequestHandler : Resource not found
Method in controller
package com.Alex.Flights;
#RequestMapping(value = "/", method = RequestMethod.GET)
public String getIndexForm(ModelMap model) {
model.addAttribute("userForm", new Flights("dummy", "dummy", "dummy", "dummy", "dummy","dummy", new Date(), new Date(), false));
return "index";
}
Main
package com.Alex.Mains;
#SpringBootApplication
#ComponentScan(basePackages = {
"com.Alex.JPA", "com.Alex.UserPackage", "com.Alex.Flights"
})
#EntityScan( basePackages = {"com.Alex.UserPackage", "com.Alex.Flights"})
#EnableJpaRepositories({"com.Alex.UserPackage", "com.Alex.Flights"})
public class JpaApplication {
public static void main(String[] args) {
SpringApplication.run(JpaApplication.class, args);
}
}
it seems like it is only looking in folders like /resources but doesn't go to look in /templates.
Solution is to define you own ViewResolver bean and set it up
https://www.baeldung.com/spring-mvc-view-resolver-tutorial

Wrong Header of the API versioning of the Post Request does not come to handleNoHandlerFoundException?

I am using Spring Boot v2.1.7 + HATEOAS + Spring Rest + Spring Security. When consumer doesn't pass the correct Custom Header in the request, say passes X-Accept-Version=v5, it gives me below error.
Error:
2020-03-26 15:44:48.201 DEBUG [employee-service,14c23adbe2664530,14c23adbe2664530,false] 3608 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : POST "/employee-catalog-api/reference-types", parameters={}
2020-03-26 15:44:48.216 DEBUG [employee-service,14c23adbe2664530,14c23adbe2664530,false] 3608 --- [nio-8080-exec-1] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler ["classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/", "/"]
2020-03-26 15:44:48.217 DEBUG [employee-service,14c23adbe2664530,14c23adbe2664530,false] 3608 --- [nio-8080-exec-1] .m.c.d.m.p.s.SAMLUserIdentityServiceImpl : Trying to get UserId from Security Context
2020-03-26 15:44:48.224 DEBUG [employee-service,14c23adbe2664530,14c23adbe2664530,false] 3608 --- [nio-8080-exec-1] o.j.s.OpenEntityManagerInViewInterceptor : Opening JPA EntityManager in OpenEntityManagerInViewInterceptor
2020-03-26 15:44:48.234 DEBUG [employee-service,14c23adbe2664530,14c23adbe2664530,false] 3608 --- [nio-8080-exec-1] o.s.w.s.r.ResourceHttpRequestHandler : Resource not found
2020-03-26 15:44:48.234 DEBUG [employee-service,14c23adbe2664530,14c23adbe2664530,false] 3608 --- [nio-8080-exec-1] o.s.s.w.header.writers.HstsHeaderWriter : Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher#5c85f23b
2020-03-26 15:44:48.234 DEBUG [employee-service,14c23adbe2664530,14c23adbe2664530,false] 3608 --- [nio-8080-exec-1] w.c.HttpSessionSecurityContextRepository : SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.
2020-03-26 15:44:48.254 DEBUG [employee-service,14c23adbe2664530,14c23adbe2664530,false] 3608 --- [nio-8080-exec-1] o.j.s.OpenEntityManagerInViewInterceptor : Closing JPA EntityManager in OpenEntityManagerInViewInterceptor
2020-03-26 15:44:48.254 DEBUG [employee-service,14c23adbe2664530,14c23adbe2664530,false] 3608 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed 404 NOT_FOUND
2020-03-26 15:44:48.258 DEBUG [employee-service,14c23adbe2664530,14c23adbe2664530,false] 3608 --- [nio-8080-exec-1] o.s.s.w.a.ExceptionTranslationFilter : Chain processed normally
2020-03-26 15:44:48.258 DEBUG [employee-service,14c23adbe2664530,14c23adbe2664530,false] 3608 --- [nio-8080-exec-1] s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed
Code:
#PostMapping(path = "/employee-types", headers = {X-Accept-Version=v1})
public ResponseEntity<Integer> saveEmployeeType(#Valid #RequestBody EmployeeDto employeeDto) {
.....
......
......
return new ResponseEntity<>(HttpStatus.OK);
}
Why its not coming to handleNoHandlerFoundException of the #ControllerAdvice ?
#Override
protected ResponseEntity<Object> handleNoHandlerFoundException(NoHandlerFoundException ex, HttpHeaders headers,
HttpStatus status, WebRequest request) {
...................
return handleExceptionInternal(ex, error, getHeaders(), HttpStatus.BAD_REQUEST, request);
}
I was able to solve this issue by taking a reference from : How to set default value of exported as false in rest resource spring data rest.
By adding below logic, it works greatly.
#Component
public class SpringRestConfiguration extends RepositoryRestConfigurerAdapter {
#Override
public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
config.setRepositoryDetectionStrategy(RepositoryDetectionStrategy.RepositoryDetectionStrategies.ANNOTATED);
config.setExposeRepositoryMethodsByDefault(false);
}
}

UTF-8 decoding in Spring Boot GET request to static resource

I have this #Bean redirecting requests to my Spring Boot backend.
#Bean
WebMvcConfigurer configurer () {
return new WebMvcConfigurerAdapter() {
#Override
public void addResourceHandlers (ResourceHandlerRegistry registry) {
registry.addResourceHandler("/data/static/images/**")
.addResourceLocations("file:" + System.getProperty("user.dir") + "/static/img/");
}
};
}
It works perfectly for URLs such as:
http://localhost:4200/data/static/images/champion/tiles/Ahri_0.jpg
But not for URLs such as:
http://localhost:4200/data/static/images/champion/tiles/Tahm%20Kench_0.jpg
The image is correctly shown in my Angular2 front end if the champion name does not contain any of: space, ampersand or single quote characters.
I ran a trace level logging debug and made both types of requests -- one with and without a "bad" character. Currently, it seems as if the backend searches for the correct file. However, it turns out that it claims it can't find it. I quintuple checked the file in my insanity, I know it is there and that the path printed is correct.
Here is an example log message:
2018-11-18 05:07:14.496 TRACE 9897 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Testing handler map [org.springframework.web.servlet.handler.SimpleUrlHandlerMapping#4d0bdef0] in DispatcherServlet with name 'dispatcherServlet'
2018-11-18 05:07:14.497 DEBUG 9897 --- [nio-8080-exec-1] o.s.w.s.handler.SimpleUrlHandlerMapping : Matching patterns for request [/data/static/images/champion/tiles/Tahm Kench_0.jpg] are [/data/static/images/**, /**]
2018-11-18 05:07:14.497 DEBUG 9897 --- [nio-8080-exec-1] o.s.w.s.handler.SimpleUrlHandlerMapping : URI Template variables for request [/data/static/images/champion/tiles/Tahm Kench_0.jpg] are {}
2018-11-18 05:07:14.497 DEBUG 9897 --- [nio-8080-exec-1] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapping [/data/static/images/champion/tiles/Tahm Kench_0.jpg] to HandlerExecutionChain with handler [ResourceHttpRequestHandler [locations=[URL [file:/home/nuradin/Development/Java/riot-api-interface/static/img/]], resolvers=[org.springframework.web.servlet.resource.PathResourceResolver#5b5b59]]] and 1 interceptor
2018-11-18 05:07:14.497 TRACE 9897 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Testing handler adapter [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter#132f4851]
2018-11-18 05:07:14.497 TRACE 9897 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Testing handler adapter [org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter#5b8d72dc]
2018-11-18 05:07:14.498 DEBUG 9897 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Last-Modified value for [/data/static/images/champion/tiles/Tahm%20Kench_0.jpg] is: -1
2018-11-18 05:07:14.498 DEBUG 9897 --- [on(7)-127.0.0.1] sun.rmi.transport.tcp : RMI TCP Connection(7)-127.0.0.1: (port 34127) op = 82
2018-11-18 05:07:14.498 TRACE 9897 --- [nio-8080-exec-1] o.s.w.s.resource.PathResourceResolver : Resolving resource for request path "champion/tiles/Tahm Kench_0.jpg"
2018-11-18 05:07:14.498 TRACE 9897 --- [nio-8080-exec-1] o.s.w.s.resource.PathResourceResolver : Checking location: URL [file:/home/nuradin/Development/Java/riot-api-interface/static/img/]
EDIT: I've implemented the class in the accepted answer, and it's definitely working because I printed the resource name (after encoding the characters I had trouble with.) However, the result is still a 404 error.
Log is below. The champion/Aatrox2Epng bit is due to a println statement in the method #slimane posted below.
2018-11-18 05:56:40.509 TRACE 12951 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Testing handler adapter [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter#465ac973]
2018-11-18 05:56:40.509 TRACE 12951 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Testing handler adapter [org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter#37df7ae5]
2018-11-18 05:56:40.509 DEBUG 12951 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Last-Modified value for [/data/static/images/champion/Aatrox.png] is: -1
2018-11-18 05:56:40.509 TRACE 12951 --- [nio-8080-exec-1] o.s.w.s.r.CachingResourceResolver : Resolving resource for request path "champion/Aatrox.png"
2018-11-18 05:56:40.510 TRACE 12951 --- [nio-8080-exec-1] o.e.r.c.EncodedPathResourceResolver : Resolving resource for request path "champion/Aatrox.png"
2018-11-18 05:56:40.510 TRACE 12951 --- [nio-8080-exec-1] o.e.r.c.EncodedPathResourceResolver : Checking location: URL [file:/home/nuradin/Development/Java/riot-api-interface/static/8.23.1/img]
champion/Aatrox2Epng
2018-11-18 05:56:40.511 TRACE 12951 --- [nio-8080-exec-1] o.e.r.c.EncodedPathResourceResolver : No match for location: URL [file:/home/nuradin/Development/Java/riot-api-interface/static/8.23.1/img]
2018-11-18 05:56:40.511 TRACE 12951 --- [nio-8080-exec-1] o.s.w.s.r.ResourceHttpRequestHandler : No matching resource found - returning 404
2018-11-18 05:56:40.511 DEBUG 12951 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Null ModelAndView returned to DispatcherServlet with name 'dispatcherServlet': assuming HandlerAdapter completed request handling
another EDIT -- sorry for the confusion, I changed the path because I thought paths with periods would work now.
#Bean
WebMvcConfigurer configurer () {
return new WebMvcConfigurerAdapter() {
#Override
public void addResourceHandlers (ResourceHandlerRegistry registry) {
registry.addResourceHandler("/data/static/images/**")
.addResourceLocations("file:" + System.getProperty("user.dir") + "/static/8.23.1/img")
.resourceChain(true)
.addResolver(encodedPathResourceResolver());
}
};
}
define your own PathResourceResolver as below:
import org.springframework.core.io.Resource;
import org.springframework.web.servlet.resource.PathResourceResolver;
import org.springframework.web.servlet.resource.ResourceResolver;
import java.io.IOException;
public class CustomPathResourceResolver extends PathResourceResolver implements ResourceResolver {
#Override
protected Resource getResource(String resourcePath, Resource location) throws IOException {
//fixes problems with whitespaces in url
resourcePath = resourcePath.replace(" ","%20");
return super.getResource(resourcePath, location);
}
}
and then register it in your configuration:
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/data/static/images/**")
.addResourceLocations("file:" + System.getProperty("user.dir") + "/static/img/")
.resourceChain(true)
.addResolver(new CustomPathResourceResolver())
;
}
This fixed the Problem for me. Somehow the path was encoded 2 times.
This removes all URI encoding not just whitespaces.
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("/resources/**")
.addResourceLocations("file:/Q:/Technik/")
.resourceChain(true)
.addResolver(new CustomPathResourceResolver());
}
public class CustomPathResourceResolver extends PathResourceResolver implements ResourceResolver {
#Override
protected Resource getResource(String resourcePath, Resource location) throws IOException {
//fixes problems with special chars in url
log.debug(resourcePath);
resourcePath = UriUtils.decode(resourcePath, "UTF-8");
log.debug(resourcePath);
resourcePath = UriUtils.decode(resourcePath, "UTF-8");
log.debug(resourcePath);
return super.getResource(resourcePath, location);
}
}

Resources