如何使用 Spring Boot Thymeleaf 显示当前登录的用户?

2023-12-24

我正在尝试显示当前用户的详细信息,但是我不断收到错误。我尝试从模板访问经过身份验证的用户,但这不起作用,因为我收到此错误:

在 org.springframework.security.core.userdetails.User 类型上找不到方法 getFirstName()

我试图从控制器获取信息,然后将其保存在字符串中并将该字符串传递给模板,但这也不起作用。

这是我的 SecurityConfig 类:

    @Configuration
 public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private UserService userService;

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .authorizeRequests()
                .antMatchers(
                        "/registration",
                        "/js/**",
                        "/css/**",
                        "/img/**",
                        "/webjars/**").permitAll()
                .anyRequest().authenticated()
            .and()
                .formLogin()
                    .loginPage("/login")
                        .permitAll()
            .and()
                .logout()
                    .invalidateHttpSession(true)
                    .clearAuthentication(true)
                    .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
                    .logoutSuccessUrl("/login?logout")
            .permitAll();
}

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

@Bean
public DaoAuthenticationProvider authenticationProvider(){
    DaoAuthenticationProvider auth = new DaoAuthenticationProvider();
    auth.setUserDetailsService(userService);
    auth.setPasswordEncoder(passwordEncoder());
    return auth;
}

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

}

这是我的 UserService 类:

 public interface UserService extends UserDetailsService {

User findByEmailAddress(String emailAddress);
  //  User findByFirstName(String firstName);

User save(UserRegistrationDto registration);
}

这是我的 UserServiceImpl 类:

 @Service
public class UserServiceImpl implements UserService {

@Autowired
private UserRepository userRepository;

@Autowired
private BCryptPasswordEncoder passwordEncoder;

@Override
public UserDetails loadUserByUsername(String emailAddress) throws 
UsernameNotFoundException {
    User user = userRepository.findByEmailAddress(emailAddress);
    if (user == null){
        throw new UsernameNotFoundException("Invalid username or 
password.");
    }
    return new 
org.springframework.security.core.userdetails.User(user.getEmailAddress(),
            user.getPassword(),
            mapRolesToAuthorities(user.getRoles()));
}

public User findByEmailAddress(String emailAddress){
    return userRepository.findByEmailAddress(emailAddress);
}

public User save(UserRegistrationDto registration){
    User user = new User();
    user.setFirstName(registration.getFirstName());
    user.setSurname(registration.getSurname());
    user.setEmailAddress(registration.getEmailAddress());
    user.setPassword(passwordEncoder.encode(registration.getPassword()));
    user.setRoles(Arrays.asList(new Role("ROLE_USER")));
    return userRepository.save(user);
}

private Collection<? extends GrantedAuthority> 
mapRolesToAuthorities(Collection<Role> roles){
    return roles.stream()
            .map(role -> new SimpleGrantedAuthority(role.getName()))
            .collect(Collectors.toList());
}


}

这是模板类中的一些代码,我试图在其中获取信息:

th:text ="${#authentication.getPrincipal().getFirstName()}">

th:text ="${#authentication.getPrincipal().getUser().getFirstName()}">

这是登录控制器。我注释掉的部分是我试图获取当前用户详细信息的另一种方式:

@Controller
//@RequestMapping("/login")
public class MainController {

//    @GetMapping("/")
//    public String root() {
//        return "userProfile1";
//    }

@GetMapping("/login")
public String login(Model model) {
    return "login";

}

 //   @GetMapping
  //  public String displayUserAccount(@ModelAttribute("user") @Valid             
UserRegistrationDto userDto, BindingResult result, Model model) {
//    
// 
//      model.addAttribute("firstName", ((UserRegistrationDto)         
auth).getEmailAddress());
//      
//      model.addAttribute("emailAddress", userDto.getEmailAddress());
//        model.addAttribute("firstName", userDto.getFirstName());
//        model.addAttribute("surname", userDto.getSurname());
//        model.addAttribute("age", userDto.getAge());
//        model.addAttribute("gender", userDto.getGender());
//        model.addAttribute("dob", userDto.getDob());
//       // return "redirect:/registration?success";
  //  return "userProfile1";
//      
  //  }

@ResponseBody
public String currentUserName(Authentication auth) {
    ((UserRegistrationDto) auth).getEmailAddress();
    return  "userProfile1";


}


  } 

这都是我很抱歉的地方!非常感谢任何提供帮助的人:D


您可以使用 Thymeleaf extras 来显示经过身份验证的用户详细信息。

Thymeleaf 附加功能 Springsecurity4 https://mvnrepository.com/artifact/org.thymeleaf.extras/thymeleaf-extras-springsecurity4/2.1.2.RELEASE

    <div th:text="${#authentication.name} ></div>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 Spring Boot Thymeleaf 显示当前登录的用户? 的相关文章

随机推荐

  • LINQ 内连接

    我有两个收藏 List
  • magento 肥皂 api v2 目录产品信息不工作

    当我如下调用api函数时 我收到以下错误 我确信所有传递的变量都设置正确 因为其他 magento api 函数工作得很好 产品不存在 错误 发生内部错误 我假设这是调用语法的错误 我找不到正确的调用示例目录产品信息使用 sku 而不是产品
  • Sugar ORM Android 具有多个数据库

    我正在尝试为具有多个数据库的多个用户创建一个应用程序 每次用户登录时 应用程序都会选择特定用户的数据库并从中获取值 是否可以使用 Sugar ORM 来实现它 因为在 Sugar ORM 中 我们只能在清单中指定一个数据库
  • 如何垂直对齐段落中的文本?

    我想知道如何对齐文本p元素垂直居中 这是我的风格 p event desc font bold 12px Helvetica Neue Helvetica Arial sans serif line height 14px height 3
  • Pygame碰撞代码

    首先 我必须说我是法国人 这样你就明白为什么我会犯所有这些错误 哈哈 我正在使用 python pygame 和 pymunk 开发一个物理游戏 一个球 我称之为 X 必须到达 Y 点 这是一款平台游戏 2d 游戏 为了帮助球到达 Y 点
  • 服务器端 d3 - 将 SVG 编码为 Base64 图像

    我正在尝试将 D3 图表编码为 base64 图像以在 HTML 电子邮件中使用 到目前为止我有 var express require express var app express var jsdom require jsdom app
  • 教程中发现 TensorFlow 错误

    我还敢问吗 目前这是一项新技术 我找不到解决这个看似简单的错误的方法 我要学习的教程可以在这里找到 http www tensorflow org tutorials mnist pros index html deep mnist for
  • 删除沙盒

    我还有一个关于应用程序沙箱的问题 所以我需要访问用户的主目录 同时应用程序应该能够关闭 Mac 这要求不使用沙箱 我的问题是我不知道如何删除沙箱以及如何将应用程序提交到 Mac App Store 我认为档案是沙盒的 因为我曾经打开过它一次
  • pycurl 和 SSL 证书

    我正在尝试编写 pycurl 脚本来访问安全站点 HTTPS c pycurl Curl c setopt pycurl USERAGENT Mozilla 5 0 Windows NT 6 1 WOW64 rv 8 0 Gecko 201
  • 共享主机上 OpenWebConfiguration 的 ASP.NET 安全异常

    将我的网站从本地开发环境移动到共享主机后 我得到 Security Exception Description The application attempted to perform an operation not allowed by
  • 如何在 OCaml 编译器中遍历类型化抽象语法树

    我正在尝试转储 OCaml 项目中所有标识符的类型信息 基本上与遍历类型化抽象语法树相同 https github com ocaml ocaml blob trunk typing typedtree mli https github c
  • 当前迭代是否有 TFS 查询宏?

    VS2010 中的 TFS 是否有一种方法可以指定特定迭代是当前迭代 然后返回该迭代以在类似于以下方式的查询中使用 Project作品 如果没有 是否有办法在 TFS 工作项查询中执行子查询 看起来微软听了 CurrentIteration
  • 刷新一下桌面

    我想刷新一个可操作的网格 我有一些列 其中的下拉列表填充了数据库的数据 但在我的页面中 我有一个第一个网格 它在该数据库中插入数据 然后我在第二个网格中获取它们 但由于我的第二个网格没有刷新 我无法获取刚刚插入第一个网格的最后一个值 那么我
  • 将联系人从 gmail/hotmail/yahoo 导入到 php

    我想将联系人从 gmail hotmail yahoo 导入到我的 php 应用程序 就像在社交网络中找到的那样 我已经读过 gmail 是如何做到这一点的 但我仍然不太清楚 它说我需要像这样做一个http请求https www opens
  • ValueError:使用 numpy 设置带有序列的数组元素

    我在 python 中有这段代码 data np empty temp shape maxlat temp shape 0 maxlon temp shape 1 print maxlat maxlon for i in range 0 m
  • 如何将 MySQL 数据库结构导出到 Excel 文件?

    有没有工具可以将 MySQL 数据库结构导出到 Excel 文件 例如 1 ID int 10 not null pri 0 index comment 谢谢你的帮助 这是一个更简单的方法 从 phpMyAdmin 中 选择您的数据库 然后
  • NSNumberFormatter 四舍五入到负零

    I m using NSNumberFormatter to format float values as integer strings i e omitting the fractional part I find it odd tha
  • sass可以转换为css,但不能与watch命令一起使用

    大家好 我是SASS初学者 刚刚开始学习Sass 所以 这个问题对某些人来说可能看起来很荒谬 在这里 我得到了 style scss myColor 009a82 myString some text here myFontSize 13p
  • 一个可调整大小的“antd”抽屉?

    我想提供一种方法来制作antd抽屉大小可以调整吗 我读过一本流行的answer https stackoverflow com questions 49469834 recommended way to have drawer resiza
  • 如何使用 Spring Boot Thymeleaf 显示当前登录的用户?

    我正在尝试显示当前用户的详细信息 但是我不断收到错误 我尝试从模板访问经过身份验证的用户 但这不起作用 因为我收到此错误 在 org springframework security core userdetails User 类型上找不到