我正在使用 thymeleaf 和 spring security 用户名和密码身份验证设置 Web 应用程序。登录成功后,我被重定向到一个网址,但在该页面上收到 403 错误码。下面是我的配置
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "index", "login", "/resource/**").permitAll()
.antMatchers("/userpage").hasRole("USER")
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/userpage")
.failureUrl("/login?error=true")
.permitAll()
.and()
.logout()
.logoutSuccessUrl("/login?logout=true")
.invalidateHttpSession(true)
.permitAll()
.and()
.csrf()
.disable();
}
我的用户服务
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userRepository.getUserByEmail(username);
if (user == null) {
throw new UsernameNotFoundException("User not found.");
}
log.info("loadUserByUsername() : {}", username);
return new org.springframework.security.core.userdetails.User(user.getId(),
user.getPassword(), getAuthority());
}
private List getAuthority() {
return Arrays.asList(new SimpleGrantedAuthority("USER")); // TODO
}
我的 Controller
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String login() {
return "login";
}
@RequestMapping(value = "/userpage", method = RequestMethod.GET)
public String userpage(Model model) {
model.addAttribute("user", new User());
return "user-page";
}
在调试loadUserByUsername()
时,我可以看到用户正在通过身份验证,但页面返回There was an Unexpected error (type=Forbidden, status=403).
一次我直接使用 defaultSuccessUrl("/userpage")
非常感谢任何帮助
最佳答案
上述代码片段中的一个可能的问题是,您没有提供loginProcessingUrl()
。这是Spring验证用户名和密码的地方
http.authorizeRequests()
.antMatchers("/", "index", "login", "/resource/**").permitAll()
.antMatchers("/userpage").hasRole("USER")
.and()
.formLogin()
.loginPage( "/myLoginPage" ) // Pointing to the controller method
.loginProcessingUrl( "/authenticateTheUser" ) // No coding is needed. Spring will automatically handle this.
.defaultSuccessUrl( "/myFirstPage", true )
.permitAll()
.and()
.logout()
.permitAll();
关于java - 使用自定义登录页面登录后 Spring Security Thymeleaf 页面 403,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61544716/