spring-security - 未调用 WebSecurityConfigurerAdapter
问题描述
我正在通过几个教程在我的项目中实现我自己的安全性。
问题是,正如配置的system.out.println
类中的调用,扩展WebSecurityConfigurerAdapter
没有被击中。这意味着根本没有调用安全类。没有错误消息,我还能够导航到站点内的任何页面,而无需重定向到登录页面的授权。此外,登录页面只是发布一个帖子并将我带到该站点的主页。
这是自定义 Web 安全配置器适配器:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
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.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
ShopmeUserDetailsService shopmeUserDetailsService;
@Bean
public UserDetailsService userDetailsService() {
return new ShopmeUserDetailsService();
}
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
public DaoAuthenticationProvider authenicationProvider() {
System.out.println("In Dao auth security");
DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
authProvider.setUserDetailsService(userDetailsService());
authProvider.setPasswordEncoder(passwordEncoder());
return authProvider;
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
System.out.println("In configure security");
//auth.authenticationProvider(authenicationProvider());
//auth.userDetailsService(shopmeUserDetailsService);
auth
.inMemoryAuthentication()
.withUser("user1")
.password(passwordEncoder().encode("user1Pass"))
.roles("USER")
.and()
.withUser("user2")
.password(passwordEncoder().encode("user2Pass"))
.roles("USER")
.and()
.withUser("admin")
.password(passwordEncoder().encode("adminPass"))
.roles("ADMIN");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
System.out.println("In configure security auth");
http
.authorizeRequests()
.anyRequest().authenticated() //all URLs are allowed by any authenticated user, no role restrictions.
.and()
.formLogin() //enable form based authentication
.loginPage("/login") //use a custom login URI
.usernameParameter("email")
.permitAll(true) //login URI can be accessed by anyone
.and()
.logout() //default logout handling
.permitAll(); //allow all as it will be accessed when user is not logged in anymore
}
@Override
public void configure(WebSecurity web) throws Exception{
System.out.println("In configure ignorings");
web.ignoring().antMatchers("/images/**", "/js/**", "/webjars/**" );
}
}
这是主要的应用程序类:
@SpringBootApplication(exclude = { SecurityAutoConfiguration.class })
@EntityScan({"com.shopme.common.entity", "com.shopme.admin.user"})
public class ShopmeBackendApplication {
public static void main(String[] args) {
SpringApplication.run(ShopmeBackendApplication.class, args);
}
}
我的主控制器:
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
@Controller
public class MainController {
@GetMapping("")
public String viewHomePage() {
return "index";
}
@GetMapping("/login")
public String viewLoginPage() {
System.out.println("In viewLoginPage method - MainController");
return "login";
}
@PostMapping("/login")
public String login() {
System.out.println("login attempt");
return "index";
}
}
最后是我的管理页面的另一个控制器:
import java.io.IOException;
import java.util.List;
import java.util.Optional;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.shopme.admin.FileUploadUtil;
import com.shopme.common.entity.Role;
import com.shopme.common.entity.User;
@Controller
public class UserController {
@Autowired
private UserService userService;
//private final java.nio.file.Path root = Paths.get("user_photos");
//Updated method to list the first page of users
@GetMapping("/users")
public String listFirstPage(Model model) {
return listUsersByPage(1, model, null);
}
@GetMapping("/users/new")
public String newUser(Model model) throws IOException {
System.out.println("new User method");
List<Role> roles = userService.listRoles();
//System.out.println(multiPartFile.getOriginalFilename());
//String fileName =
StringUtils.cleanPath(multiPartFile.getOriginalFilename());
//String uploadDir = "user_photos";
//FileUploadUtil.saveFile(uploadDir, fileName, multiPartFile);
//Files.copy(multiPartFile.getInputStream(), ((java.nio.file.Path)
this.root).resolve(multiPartFile.getOriginalFilename()));
User user = new User();
user.setEnabled(true);
model.addAttribute("user", user);
model.addAttribute("roles", roles);
model.addAttribute("pageTitle", "Create New User");
return "user_form";
}
@PostMapping("/users/save")
public String saveUser(User user, RedirectAttributes redirect, @RequestParam("image") MultipartFile multiPartFile) throws IOException {
System.out.println(user);
System.out.println(multiPartFile.getOriginalFilename());
String fileName = StringUtils.cleanPath(multiPartFile.getOriginalFilename());
String uploadDir = "user_photos";
FileUploadUtil.saveFile(uploadDir, fileName, multiPartFile);
//Files.copy(multiPartFile.getInputStream(), ((java.nio.file.Path) this.root).resolve(multiPartFile.getOriginalFilename()));
userService.save(user);
redirect.addFlashAttribute("message", "User has been saved successfully!");
return "redirect:/users/page/1?keyword=" + user.getId();
}
@GetMapping("/users/edit/{id}")
public String editUser(@PathVariable(name = "id") Integer id, Model model, RedirectAttributes redirect){
try {
Optional<User> user = userService.getUserById(id);
List<Role> roles = userService.listRoles();
model.addAttribute("user", user);
model.addAttribute("roles", roles);
model.addAttribute("pageTitle", "Edit User (ID: " + id + ")");
return "user_form";
} catch (UserNotFoundException ex) {
redirect.addFlashAttribute("message", ex.getMessage());
return "redirect:/users";
}
}
@GetMapping("users/delete/{id}")
public String deleteUser(@PathVariable(name="id") Integer id, Model model, RedirectAttributes redirect) {
userService.deleteUserById(id);
redirect.addFlashAttribute("message", "User has been deleted successfully!");
return "redirect:/users";
}
@GetMapping("/users/{id}/enabled/{status}")
public String updateUserEnabledStatus(@PathVariable("id") Integer id, @PathVariable("status") boolean enabled, RedirectAttributes redirect) {
userService.updateUserEdabledStatus(id, enabled);
String status = enabled ? "enabled" : "disabled";
String message = "THe user Id " + id + " has been " + status;
redirect.addFlashAttribute("message", message);
return "redirect:/users";
}
@GetMapping("/users/page/{pageNumber}")
public String listUsersByPage(@PathVariable(name = "pageNumber") int pageNumber, Model model, @Param("keyword") String keyword) {
Page<User> page = userService.listByPage(pageNumber, keyword);
List<User> userPagedList = page.getContent();
System.out.println("Pagenumber: " + pageNumber);
System.out.println("Total Elements: " + page.getTotalElements());
System.out.println("Totals Pages: " + page.getTotalPages());
long startCount = (pageNumber - 1) * UserService.USERS_PER_PAGE +1;
long endCount = startCount + UserService.USERS_PER_PAGE -1;
if(endCount > page.getTotalElements()){
endCount = page.getTotalElements();
}
model.addAttribute("totalPages", page.getTotalPages());
model.addAttribute("currentPage", pageNumber);
model.addAttribute("startCount", startCount);
model.addAttribute("endCount", endCount);
model.addAttribute("totalItems", page.getTotalElements());
model.addAttribute("users", userPagedList);
model.addAttribute("keyword", keyword);
return "users";
} //end listUserByPage
@GetMapping("/users/export/csv")
public void exportToCSV(HttpServletResponse response) throws IOException {
List<User> userList = userService.listAll();
UserCsvExporter exporter = new UserCsvExporter();
exporter.export(userList, response);
} //end exportToCsv
@GetMapping("/users/export/excel")
public void exportToExcel(HttpServletResponse response) throws IOException {
List<User> userList = userService.listAll();
UserExcelExporter exporter = new UserExcelExporter();
exporter.export(userList, response);
} //end exportToExcel
@GetMapping("/users/export/pdf")
public void exportToPdf(HttpServletResponse response) throws IOException {
List<User> userList = userService.listAll();
UserPdfExporter exporter = new UserPdfExporter();
exporter.export(userList, response);
} //end exportToPdf
} //end of class
我花了两天时间对此进行调查,但没有任何结果……任何帮助将不胜感激。
解决方案
我弄清楚了为什么这不起作用,至少我可以使用此解决方案。
我在项目的启动类中包含了WebSecurityConfig.class,如下所示:
@SpringBootApplication
@EntityScan({"com.shopme.common.entity", "com.shopme.admin.user"})
public class ShopmeBackendApplication {
public static void main(String[] args) {
SpringApplication.run(new Class[]
{ShopmeBackendApplication.class,
WebSecurityConfig.class}, args);
}
}
推荐阅读
- ssl - 如何在 TCP 模式下使用 haproxy 传递自定义 SNI
- javascript - Nodemon 显示正在重新启动,但实际上没有
- java - CSV阅读器丢失转义字符
- google-apps-script - Google Apps 脚本使用 Jdbc.getConnection() 连接到 Cloud MySQL 数据库
- docker - 如何在 alpine Docker 映像中安装 docker-compose 发布二进制文件?
- split - 如何查找拆分函数生成的列表的长度
- excel - 将 Excel 连接到 CouchDB
- python - Python Dataframe 从多列中填充 nan
- graphql - graphql - 如何过滤嵌套列表
- matrix - Fortran - 将矩阵插入其他矩阵