java - 使用自定义登录页面登录后 Spring Security Thymeleaf 页面 403

标签 java spring-security thymeleaf

我正在使用 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/

相关文章:

java - BindingResult 和 bean 名称 'matrix[0][0]' 的普通目标对象都不能作为请求属性

java - 小工具中的Logback+Swing

java - java中的同步方法问题

java - gwt中的Remote Service被执行了两次

java - 在android studio中查询设置sql数据库列值

Grails Spring Security 自定义登录表单 - 错误消息在哪里?

java - 确保特定用户只能看到自己的用户详细信息 - 使用 Spring

javascript - jquery加载函数不调用Spring Boot Controller 来替换thymeleaf模板片段

spring-boot - Spring Boot x509 测试 - pcf

javascript - 使用 Thymeleaf 将值通过 AJAX 传递给 Controller ​​,无需任何用户输入