SpringSecurity SecurityContext getPrinicple() 返回 anonymousUser

SpringSecurity SecurityContext getPrinicple() returning anonymousUser

提问人:kawlorridor 提问时间:10/24/2023 最后编辑:durkawlorridor 更新时间:10/25/2023 访问量:20

问:

嘿,所以我正在尝试为我的 Web 应用程序进行登录身份验证,但在 SecurityContext 中设置用户后,我得到了匿名用户。以下是我的配置:

@Override
protected void configure(HttpSecurity http) throws Exception {
  http
    .csrf()
    .disable()
    .cors()
    .and()
    .authorizeRequests()
    .antMatchers(
      "/api/v*/registration/**",
      "**/oauth2/**",
      "/api/v*/ssologin",
      "/api/v1/uploadssoimg",
      "/api/v*/*"
    )
    .permitAll()
    .anyRequest()
    .authenticated()
    .and()
    .formLogin()
    .loginPage("/auth/login");

这是我用于登录和设置安全上下文的代码:

  public void setSecurityContextHolder(User user) {
    SecurityContext securityContext = SecurityContextHolder.getContext();

    // Get the Authentication object
    Authentication authentication = securityContext.getAuthentication();
    System.out.println("SETTING SECURITY CONTEXT: Email: "+ user.getEmail()  + ", pass: " + user.getPassword());
    // Update the name
    String newName = "New Name";
    authentication =
      new UsernamePasswordAuthenticationToken(
        user.getEmail(),
        authentication.getCredentials(),
        authentication.getAuthorities()
      );
    ((UsernamePasswordAuthenticationToken) authentication).setDetails(
        authentication.getDetails()
      );
    // Set the updated Authentication object back to the SecurityContext
    securityContext.setAuthentication(authentication);

    // Update the SecurityContextHolder with the modified SecurityContext
    SecurityContextHolder.setContext(securityContext);
    System.out.println("YARO" + SecurityContextHolder.getContext().getAuthentication().getName());
  }

  @Override
  public Boolean loginUser(String username, String password) {
    Optional<User> userOptional = getUserRepository().findByEmail(username);
        if (userOptional.isPresent()) {
            User user = userOptional.get();
            if (bCryptPasswordEncoder.matches(password, user.getPassword())) {
                setSecurityContextHolder(user);
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
  }

在这里,我试图获取安全上下文:

@Override
  public String getLoggedInUserEmail() {
    if (testMode) {
      return "[email protected]";
    } else {
      System.out.println("HERE MOFO" + SecurityContextHolder.getContext().getAuthentication().toString());
      return SecurityContextHolder.getContext().getAuthentication().getName();
    }
  }

调试输出如下:

SETTING SECURITY CONTEXT: Email: [email protected], pass: x
[email protected] [[email protected], Credentials=[PROTECTED], Authenticated=true, Details=null, Granted Authorities=[ROLE_ANONYMOUS]]
2023-10-24 01:32:42.255  INFO 368454 --- [nio-8080-exec-1] c.a.f.w.c.a        : LOGGED IN SUCCESSFULL
2023-10-24 01:32:42.333  INFO 368454 --- [nio-8080-exec-2] c.a.f.w.c.a       : WE GETTING WHO WE ARE
HERE MOFOAnonymousAuthenticationToken [Principal=anonymousUser, Credentials=[PROTECTED], Authenticated=true, Details=WebAuthenticationDetails [RemoteIpAddress=x, SessionId=null], Granted Authorities=[ROLE_ANONYMOUS]]
THIS IS THE EMAIL WE TRYNG TO LOG INanonymousUser
  }
Spring Security spring-security security-context

评论

0赞 dur 10/24/2023
你不必像 和 那样编写任何代码,Spring Security 通过 defauft 来完成。删除您的代码,它应该可以工作。loginUsersetSecurityContextHolder
0赞 kawlorridor 10/25/2023
@dur如果我删除所有内容,那么当我尝试登录时,我会得到 404 Not Found。我正在使用 OpenApi
0赞 dur 10/25/2023
您使用 更改了登录页面,但未提供自定义登录页面。因此,删除并使用默认 URL.loginPage("/auth/login");.loginPage("/auth/login");/login-

答: 暂无答案