如何显示使用Spring Boot Thymeleaf的当前登录用户? [英] How can I display the current logged in User with Spring Boot Thymeleaf?

查看:139
本文介绍了如何显示使用Spring Boot Thymeleaf的当前登录用户?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试显示当前用户的详细信息,但是我一直遇到错误.我尝试从模板访问经过身份验证的用户,但是由于出现此错误,该操作不起作用:

I am trying to display the details of the current user however I keep getting errors. I tried accessing the authenticated user from the template but that did not work as I was getting this error:

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

Method getFirstName() cannot be found on org.springframework.security.core.userdetails.User type

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

I was trying to get the information from a controller and then saving it in a string and passsing the string to a template but that wasn't working either.

这是我的SecurityConfig类:

Here is my SecurityConfig class:

    @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类:

Here is my UserService Class:

 public interface UserService extends UserDetailsService {

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

User save(UserRegistrationDto registration);
}

这是我的UserServiceImpl类:

Here is my UserServiceImpl class:

 @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());
}


}

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

Here is some code from the template class where I'm trying to get the information:

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

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

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

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

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

This is the login controller. The parts I have commented out was another way I was trying to get the current users details:

@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

This is all over the place I'm sorry! Thanks so much for anyone who helps :D

推荐答案

我想出了解决问题的方法.

I figured out how to fix my problem.

我在控制器中创建了此方法:

I created this method in a controller:

  @Autowired
UserRepository userR;
@GetMapping
public String currentUser(@ModelAttribute("user") @Valid UserRegistrationDto userDto, BindingResult result, Model model) {

    Authentication loggedInUser = SecurityContextHolder.getContext().getAuthentication();
    String email = loggedInUser.getName(); 

     User user = userR.findByEmailAddress(email);
    String firstname = user.getFirstName();
     model.addAttribute("firstName", firstname);
    model.addAttribute("emailAddress", email);

    return "userProfile1"; //this is the name of my template
}

,然后在我的html模板中添加以下代码行:

and then I added this line of code in my html template:

电子邮件:th:text ="$ {emailAddress}"

Email: th:text="${emailAddress}"

这篇关于如何显示使用Spring Boot Thymeleaf的当前登录用户?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆