Why i cannot install this package :WebSecurityConfigurerAdapter in java? - java

I have a SecurityConfig class that im am trying to implement after a tutorial but i got stopped by this error in this class:
package com.example.demo.security;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
#Configuration #EnableWebSecurity #RequiredArgsConstructor
public class SecurityConfig extends WebSecurityConfigurerAdapter{
}
I get this error :Cannot resolve symbol 'WebSecurityConfigurerAdapter'

Related

Spring Security FilterChain Not getting executed in Order

Requirements:
user will be able to login to the system through two different login urls
admin users will login -> /admin_login
guest users will login -> /guset_login
different authentication source for both the users
question:
when login through admin user, able to see all the admin pages and everything working fine
but trying to access guest user pages giving 404(not found) error, it should redirect to guest user login page
same when login through guest user , able to see all the pages accessible to guest user, but while accessing admin user pages it giving 404 error. it should redirect to admin login page
SecurityConfigone Class:
package com.securityexample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import com.securityexample.providers.GuestAuthenticationProvider;
import com.securityexample.providers.MyCustomAuthenticationProvider;
#Configuration
#EnableWebSecurity
#Order(1)
public class SecurityConfigOrder1 {
#Autowired
MyCustomAuthenticationProvider myCustomeAuthenticationProvider;
#Bean
public SecurityFilterChain filterChainApp1(HttpSecurity http) throws Exception {
http.authenticationProvider(myCustomeAuthenticationProvider);
http.antMatcher("/admin/**").authorizeRequests().anyRequest().hasAuthority("ADMIN").and().formLogin()
.loginPage("/admin_login").loginProcessingUrl("/admin/process-login")
.failureUrl("/admin_login?error=error").defaultSuccessUrl("/admin/page1").usernameParameter("username")
.passwordParameter("password").and().logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/admin/logout"))
.logoutSuccessUrl("/admin_login?logout=true").deleteCookies("JSESSIONID").and().exceptionHandling()
.accessDeniedPage("/access-denied").and().csrf().disable();
return http.build();
}
}
SecurityConfigClass2
package com.securityexample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import com.securityexample.providers.GuestAuthenticationProvider;
#Configuration
#EnableWebSecurity
#Order(2)
public class SecurityConfigOrder2 {
#Autowired
GuestAuthenticationProvider guestAuthenticationProvider;
#Bean
public SecurityFilterChain filterChaninApp2(HttpSecurity http) throws Exception {
http.authenticationProvider(guestAuthenticationProvider);
http.antMatcher("/guest/**").authorizeRequests().anyRequest().hasAuthority("GUEST_USER").and().formLogin()
.loginPage("/guest_login").loginProcessingUrl("/guest/process-login")
.failureUrl("/guest_login?error=error").defaultSuccessUrl("/guest/page1").usernameParameter("username")
.passwordParameter("otp").and().logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/guest/logout"))
.logoutSuccessUrl("/guest_login?logout=true").deleteCookies("JSESSIONID").and().exceptionHandling()
.accessDeniedPage("/access-denied").and().csrf().disable();
return http.build();
}
}
please need help, if anybody could help ?
getting error while accessing guest user pages if login as admin user
and vice versa.
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Tue Dec 27 22:26:41 IST 2022
There was an unexpected error (type=Not Found, status=404).
No message available

Keep getting 404 in spring boot endpoint

I am learning spring boot, I made a simple GET endpoint but whenever I request on that endpoint I keep getting 404.
Below is my code:
Student.Controller.java
package student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.time.LocalDate;
import java.time.Month;
import java.util.List;
#RestController
public class StudentController {
#GetMapping("/home")
public String home(){
return "This is String";
}
}
Project Structure:
If you add #ComponentScan({"student"}) annotation on DemoApplication class it should work. You can also create your packages such as controller, service, repository ... under com.example.demo, then you don't have to add additional annotations for component scanning.
Follow this project structuring advice: https://docs.spring.io/spring-boot/docs/2.0.x/reference/html/using-boot-structuring-your-code.html

Field memberRepo in (...) required a bean of type that could not be found

I'm working on a Spring Boot project. Implementing Back-End code with the data, I've got an error.
Before working on the security, that is, when I've just done with the MemberRepository, MemberService, and MemberController, it worked well. After I worked on the security, that kind of error occurs.
I'm using IntelliJ as the IDE, and the methods were MySQL, Java, Spring Boot, Spring Security, and Maven. The OS is Mac.
This is a part of MemberRepository.java code:
package com.springboot.reserving.member;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.context.annotation.Bean;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Map;
#Repository
public interface MemberRepository extends CrudRepository<Member, Long> { ... }
This is a part of MemberService.java code:
package com.springboot.reserving.member;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
#Service
public class MemberService {
#Autowired
MemberRepository memberRepository;
...
}
This is CustomUserDetailService.java code:
package com.springboot.reserving.member;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.util.Optional;
#Service
public class CustomUserDetailsService implements UserDetailsService {
#Autowired
MemberRepository memberRepo;
#Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
return Optional.ofNullable(memberRepo.read(username))
.filter(m -> m != null)
.map(m -> new SecurityMember(m)).get();
}
}
The error message was:
Description:
Field memberRepo in com.springboot.reserving.member.CustomUserDetailsService required a bean of type 'com.springboot.reserving.member.MemberRepository' that could not be found.
The injection point has the following annotations:
- #org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'com.springboot.reserving.member.MemberRepository' in your configuration.
What should I do to fix this error?
One possible reason is that spring doesn't create Spring Data Repository out of the interface.
In a nutshell, spring data project generates a "proxy" in runtime - an implementation of the interface that will contain all the required methods for working with the database.
In order to make is possible you should enable this proxy generation for you DAOs:
This can be done with:
#EnableJpaRepositories(basePackages = "com.springboot.reserving.member")
So make sure you have this annotation on spring boot application class.

Spring Server Issue with Bean Creation

I am having an issue in which a defined repository is not being correctly interpreted as a bean on server startup. The class with #SpringBootApplication is in a higher directory than the defined repository, so I cannot find why it does not configure.
#SpringBootApplication:
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import java.util.Properties;
#SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
System.out.println("http://localhost:8080");
}
}
Repository
package lab14.panoslab.Repositories;
import lab14.panoslab.Models.Account;
import org.apache.catalina.User;
import org.hibernate.annotations.NotFound;
import org.hibernate.annotations.NotFoundAction;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
#Repository
public interface UserRepository extends JpaRepository<Account,Long> {
#NotFound(action = NotFoundAction.IGNORE)
List<User> findByUsername(String username);
}
Error code:
*************************** APPLICATION FAILED TO START***************************
Description:
Field userRepository in lab14.panoslab.Controllers.RegisterController
required a bean of type 'lab14.panoslab.Repositories.UserRepository'
that could not be found.
Action:
Consider defining a bean of type
'lab14.panoslab.Repositories.UserRepository' in your configuration.
Process finished with exit code 1
Are you sure that your class Account implements the interface User?
And try to remove the annotation #Repository and add annotations #EntityScan and #EnableJpaRepositories in your DemoApplication class:
#SpringBootApplication
#EntityScan({"lab14.panoslab.Models"})
#EnableJpaRepositories({"lab14.panoslab.Repositories"})
public class DemoApplication {...}
Also, I would advise you to rename all your packages into lowercase and return a value of List<Account>, not List<User>.
I did face similar issue. What I have done the mistake is, I have placed my controller/repository and other component packages outside the Main Class package. So, Spring boot not able to identify my components,
For Ex: main class package is package com.example.demo;
Controller package like, package com.example.controller;
Repository package like, package com.example.repository;
Below are the two different ways to solve this problem,
Explicitly defining my component packages in #ComponentScan, like #ComponentScan(basePackages="com.example.controller,com.example.repository") with base packages of required components.
Otherwise, You can create Controller/repository packages inside the main package. So, you no need to define #ComponentScan and all.
For ex,
main class package is package com.example.demo;
Controller package like, package com.example.demo.controller;
Repository package like, package com.example.demo.repository;

Why We use WebMvcAutoConfigurationAdapter class

package com.ge.hc.gsit.sbom.configuration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
#Configuration
#EnableAutoConfiguration
#EnableWebMvc
#ComponentScan(basePackages = {"com.abc.xy.gsit.sbom.controller","com.abc.xy.gsit.sbom.exception"})
public class MvcConfig extends WebMvcAutoConfigurationAdapter{
}
Hi,
I want to know how WebMvcAutoConfigurationAdapter class is working.
If any documents is present please let me know, It will be helpful.
Thanks in Advance.
Comment in the WebMvcAutoConfigurationAdapter states that:
// Defined as a nested config to ensure WebMvcConfigurerAdapter is not read when not
// on the classpath
WebMvcAutoConfigurationAdapter class extends WebMvcConfigurerAdapter and provides default implementation of WebMvcConfigurer interfaces methods that are callbacks to customize the Java-based configuration for Spring MVC enabled via #EnableWebMvc.
So, if you want to changes some behavior you should extends WebMvcConfigurerAdapter.
More details about EnableAutoConfiguration and Spring Boot in general: Understanding Spring Boot

Categories