程序问答   发布时间:2022-06-01  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了如何在 Spring Boot Thymeleaf 中获取当前登录用户的数据?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决如何在 Spring Boot Thymeleaf 中获取当前登录用户的数据??

开发过程中遇到如何在 Spring Boot Thymeleaf 中获取当前登录用户的数据?的问题如何解决?下面主要结合日常开发的经验,给出你关于如何在 Spring Boot Thymeleaf 中获取当前登录用户的数据?的解决方法建议,希望对你解决如何在 Spring Boot Thymeleaf 中获取当前登录用户的数据?有所启发或帮助;

我希望我的登录用户能够查看他们自己的用户个人资料,甚至可以根据需要进行修改。

我的两个存储用户数据的实体:

@Entity
@table(name = "users")
public class User {

    @ID
    @GeneratedValue
    private Long ID;

    @column(unique = true,nullable = falsE)
    private String email;

    @column(nullable = falsE)
    private String password;

    private String fullname;

    private String activation;

    private Boolean enabled;

    @manyToMany(cascade = CascadeType.ALL,fetch = FetchType.EAGER)
    @Jointable(name = "users_roles",joincolumns = { @Joincolumn(name = "user_iD") },inverseJoincolumns = {
            @Joincolumn(name = "role_ID") })
    private Set<Role> roles = new HashSet<Role>();

    @OnetoOne(mappedBy = "user",cascade = CascadeType.ALL)
    private UserProfile userProfile;
//constructors,getters and setters

和:

@Entity
@table(name="profiles")
public class UserProfile {

    
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @ID
    private Long ID;

    @column(length = 20)
    private String activation;

    @column(length = 64)
    private String address;

    @column(length = 32)
    private String phonenumber;

    @column(length = 60)
    private String resetToken;

    @OnetoOne
    private User user;
    
//constructors,getters and setters

我在我的 UserController 中写了这个:

    @GetMapPing("/profile")
    public String showUserProfile (Model model){
        //Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        //String currentPrincipalname = authentication.getname();
        //User user = userRepository.findByEmail(authentication.getPrincipal());
        //model.addAttribute("currentUser",user);
        return "profile";
    }

我在 UserRepository 和 Userservice 中的 findByEmail 方法:

User findByEmail(String email);

STS 想将此方法修改为(对象主体)或类似的东西,但我无法更改它,因为该方法已被使用。

java.lang.Error: Unresolved compilation problem: 
    The method findByEmail(String) in the type UserRepository is not applicable for the arguments (Object)

对不起,我还是 Spring Boot 的新手。 如何获取当前用户的数据?我已经创建了一个用户 CRUD,我想对当前用户做同样的事情,而不是 deletE 和 CREATE。@H_489_36@

解决方法

为了使用 spring-security,你必须实现 UserDetails,如:

public class UserPrincipal implements UserDetails {

    private User user;
    private String name;
    private long uid;

    public long getUid() {
        return uid;
    }

    public void setUid(long uid) {
        thiS.Uid = uid;
    }

    public UserPrincipal(User user) {
        thiS.User = user;
        this.name = user.getName();
        thiS.Uid = user.getUid();
    }

    public String getName() {
        return name;
    }

    public void setName(String Name) {
        this.name = name;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<GrantedAuthority> authorities = new ArrayList<>();
        authorities.add(new GrantedAuthority() {
            @Override
            public String getAuthority() {
                return "ROLE_USER";
            }
        });
        return authorities;
    }

    @Override
    public String getpassword() {
        return user.getpassword();
    }

    @Override
    public String getUsername() {
        return user.getEmail();
    }

    @Override
    public Boolean isaccountnonExpired() {
        return true;
    }

    @Override
    public Boolean isaccountnonLocked() {
        return true;
    }

    @Override
    public Boolean isCredentialsnonExpired() {
        return true;
    }

    @Override
    public Boolean isEnabled() {
        return true;
    }
}

还有这样的服务:

@service
public class UserDetailsserviceImpl implements UserDetailsservice {

    @Autowired
    private UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
        User user = userRepository.findByEmail(email);
        if(user == null) {
            throw new UsernameNotFoundException("User Not found");
        }
        return new UserPrincipal(user);
    }
}

然后添加以获取当前登录的用户:

private UserPrincipal getLoggedInUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return (UserPrincipal)authentication.getPrincipal();
    }

内部 UserPricipal 对象存储配置文件并在 thymeleaf 中访问它。

,

要使用 Spring Security 和 Thymeleaf,您需要编写一个实现 UserDetails 的类。此类是您的应用程序和 Spring Security 之间的“桥梁”。它可能看起来像这样

public class ApplicationUserDetails implements UserDetails {
    
    public ApplicationUserDetails(User user) {
        this.username = user.getEmail();
        this.password = user.getpassword(); //<.>
        this.authorities = user.getRoles().stream()
                               .map(userRole -> new SimpleGrantedAuthority("ROLE_" + userRole.name()))
                               .collect(Collectors.toSet());
    }
}

接下来,您需要编写 UserDetailsservice 的实现。这个类将被 Spring Security 调用以了解什么用户对象对应于给定的用户名(或电子邮件,如果您使用电子邮件而不是用户名)。所以是这样的

@service
@transactional(readOnly = truE)
public class DatabaseUserDetailsservice implements UserDetailsservice {

    private final UserRepository userRepository;

    @Autowired
    public DatabaseUserDetailsservice(UserRepository userRepository) {
        thiS.UserRepository = userRepository;
    }

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        User user = userRepository.findByEmail(userName)
                                  .orElseThrow(() -> new UsernameNotFoundException(
                                          format("User with email %s could not be found",userName)));

        return new ApplicationUserDetails(user);
    }
}

您还需要通过 WebSecurityConfigurerAdapter 实现正确配置 Spring Security:

@Configuration
@EnableGlobalMethodSecurity(securedEnabled = truE)
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
    private final passwordEncoder passwordEncoder;
    private final UserDetailsservice userDetailsservice;

    public WebSecurityConfiguration(passwordEncoder passwordEncoder,UserDetailsservice userDetailsservicE) {
        this.passwordEncoder = passwordEncoder;
        thiS.UserDetailsservice = userDetailsservice;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsservice(userDetailsservicE)
            .passwordEncoder(passwordEncoder);
    }

    @Override
    protected void configure(httpSecurity http) throws Exception {
        http.authorizerequests()
            .requestMatchers(Pathrequest.toStaticresources().atCommonLOCATIOns()).permitAll()
            .antMatchers("/img/*").permitAll()
            .anyrequest().authenticated()
            .and()
            .formLogin()
            .loginPage("/login")
            .permitAll()
            .and()
            .logout().permitAll();
    }
    
}

您现在可以使用 Spring Security Thymeleaf 集成来显示有关登录用户的信息。

<span sec:authentication="name">Bob</span>

请参阅 https://www.thymeleaf.org/doc/articles/springsecurity.html 以获取文档,或参阅 https://github.com/wimdeblauwe/taming-thymeleaf-sources/tree/main/chapter14 以获取完整的 Spring Boot 项目,其中显示了所有这些操作。

,

我认为您的 findByEmail 方法是正确的。您只需要更新如何获取当前用户电子邮件。您可以通过修改如何从安全上下文中获取用户电子邮件来获得,如下所示

SecurityContextHolder.getContext().getAuthentication().getPrincipal.toString()

因为以这种方式,它将返回主体的字符串值,在您的情况下将是电子邮件。但是现在它返回 Principal Object,这就是 STS 抱怨将方法签名修改为 (object principal) 的原因,正如您所提到的。

大佬总结

以上是大佬教程为你收集整理的如何在 Spring Boot Thymeleaf 中获取当前登录用户的数据?全部内容,希望文章能够帮你解决如何在 Spring Boot Thymeleaf 中获取当前登录用户的数据?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签:如何在