Java 登录后,用户变得匿名

Java 登录后,用户变得匿名,java,spring,spring-boot,jsp,spring-security,Java,Spring,Spring Boot,Jsp,Spring Security,我正在使用Spring boot创建一个应用程序,它需要首先登录。问题是,在登录后,我的用户变得“匿名”,我无法创建其他请求,因为如果用户未经身份验证,这些请求将被禁止。对于身份验证,我使用Spring安全性。您能告诉我如何保存用户并在登录后始终可用吗 以下是Spring配置类: @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Auto

我正在使用Spring boot创建一个应用程序,它需要首先登录。问题是,在登录后,我的用户变得“匿名”,我无法创建其他请求,因为如果用户未经身份验证,这些请求将被禁止。对于身份验证,我使用Spring安全性。您能告诉我如何保存用户并在登录后始终可用吗

以下是Spring配置类:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

  @Autowired
  private CustomerAuthenticationProvider authenticationProvider;

  @Override
  protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.authenticationProvider(authenticationProvider);
  }

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http
      .authorizeRequests()
      .antMatchers("/resources/**", "/register")
      .permitAll();
    http
      .authorizeRequests()
      .anyRequest()
      .authenticated();
    http
      .formLogin()
      .loginPage("/login")
      .loginProcessingUrl("/homeLogged")
      .permitAll();
    http
      .logout()
      .logoutSuccessUrl("/login")
      .permitAll();
  }
}
下面是将Http Get请求发送到后端的JSP。这里我已登录,但用户是匿名的

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>

<html>
<head>
  <title>Business manager</title>
</head>
<script src="../../resources/js/jquery-3.4.1.js"></script>
<body>
<div class="container">
  <div>
    <h1>Business Manager</h1>
  </div>
  <div class="row">
    <button id="goToNewSchedule">Create Schedule</button>
  </div>
</div>
<script>
    $("#goToNewSchedule").click(function(){
        $.get("http://localhost:8080/homeLogged/schedule", function(){
            console.log("Hello");
        });
    });
</script>
</body>
</html>
它是登录控制器

@Controller
@RequestMapping("/login")
@Log4j2
public class LoginController {
  @Autowired
  private CustomerAuthenticationProvider authenticationProvider;

  @PostMapping
  public ModelAndView login(@ModelAttribute("studio") Studio studio, HttpServletRequest request) {
    log.info(studio.getUsername() + " user is logging");
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if(!(authentication.getAuthorities().contains(CustomerAuthenticationProvider.AUTHORITY_USER))){
      Authentication auth = new UsernamePasswordAuthenticationToken(studio.getUsername(), studio.getPassword());
      authenticationProvider.authenticate(auth);
    }
    HttpSession session = request.getSession(true);
    session.setMaxInactiveInterval(30*60);
    return new ModelAndView("redirect:homeLogged");
  }

您并没有完全使用Spring安全性。也许有一种方法可以使用这种奇怪的登录方式使其工作,但我建议您只使用Spring方式:

使用于登录的实体(例如,
User.class
)实现Spring的接口(不要忘记向布尔方法添加逻辑,如
isEnabled()
,这样它们就不会总是返回false)。然后选择一个服务来实现Spring的接口,该接口强制您重写用于从数据库获取用户的方法
loadUserByUsername()
。最后在
SecurityConfig
开关
auth.authenticationProvider(authenticationProvider)中带有
auth.userDetailsService(userService).passwordEncoder(passwordEncoder)
其中
userService
是实现UserDetailsService的
@Component
类,而
passwordEncoder
只是一个
@Bean

  public BCryptPasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
  };

在我看来,LoginController是不必要的

spring安全配置已经定义了authenticationProvider来验证您的登录,您不需要另一个控制器来做同样的事情

试试这个:

  • 删除LoginController
  • 将登录成功URL更改为“/homeloged”
  • 如果您想使用自己的自定义登录页面,比如login.jsp,您可以在formLogin()之后添加它,如下所示:

    http
          .formLogin().loginPage("/login.jsp")
          .defaultSuccessUrl("/homeLogged", true)
          .permitAll();
    
    
    在login.jsp中,您应该有三个元素: 1.操作:“login”,它将请求发布到url:login 2.用户名字段 3.密码字段


    您的安全配置中定义的身份验证器将对用户名和密码进行身份验证,然后重定向到成功的URL。

    好的,但我想使用我的自定义登录页面。如何处理来自我的自定义登录页面的请求?可以。您可以这样调用自定义登录页面:
    http
    .formLogin().loginPage(“/login.jsp”)
    .defaultSuccessUrl(“/homeloged”,true)
    permitAll()和您的自定义登录页面将是login.jsp
    
    http
          .formLogin()
          .defaultSuccessUrl("/homeLogged", true)
          .permitAll();
    
    
    http
          .formLogin().loginPage("/login.jsp")
          .defaultSuccessUrl("/homeLogged", true)
          .permitAll();