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

时间:2018-01-20 16:31:12

标签: spring spring-boot login spring-security thymeleaf

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

在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 =&#34; $ {#authentication.getPrincipal()。getFirstName()}&#34;&gt;

th:text =&#34; $ {#authentication.getPrincipal()。getUser()。getFirstName()}&#34;&gt;

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

@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

5 个答案:

答案 0 :(得分:4)

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

Thymeleaf Extras Springsecurity4

    <div th:text="${#authentication.name} ></div>

答案 1 :(得分:1)

问题在于:

return new 
org.springframework.security.core.userdetails.User(user.getEmailAddress(),
        user.getPassword(),
        mapRolesToAuthorities(user.getRoles()));

您将失去对User实体的引用。将其更改为:

return user;

为此,您需要更新User实体以实施AsyncTasks界面:

public class User implements UserDetails {
    // some new methods to implement
}

然后,你的Thymleaf代码应该可行。获得firstName的另一种方法是:

<span th:text="${#request.userPrincipal.principal.firstName}"></span>

答案 2 :(得分:0)

我想出了如何解决我的问题。

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

  @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模板中添加了这行代码:

电子邮件:th:text =&#34; $ {emailAddress}&#34;

答案 3 :(得分:0)

参考(4. Spring安全性方言):

https://www.thymeleaf.org/doc/articles/springsecurity.html

添加依赖项pom.xml

<dependency>
        <groupId>org.thymeleaf.extras</groupId>
        <artifactId>thymeleaf-extras-springsecurity4</artifactId>
</dependency>

和视图(胸腺):

<div sec:authorize="isAuthenticated()"> 
    Authenticated user roles:
    Logged user: <span sec:authentication="name"></span> |
    Roles: <span sec:authentication="principal.authorities"></span>
</div>

我希望你能为他们服务

答案 4 :(得分:0)

您可以轻松地从 Principal 类中获取用户名属性。

@GetMapping(value = "/")
    public String index(@AuthenticationPrincipal MyUserPrincipal principal) {
        String username = principal.getUsername();
        //Do whatever you want here
        return "index";
    }

然而,如果你想要比 Principal 类中的更多细节,那么你需要在你的 principal 类中明确定义它们:

public int getId() {
    return member.getId();
}

所以现在你可以直接调用它了:

@GetMapping(value = "/")
    public String index(@AuthenticationPrincipal MyUserPrincipal principal) {
        int userId = principal.getId();
        //Do whatever you want here
        return "index";
    }

您需要导入以下内容:

import org.springframework.security.core.annotation.AuthenticationPrincipal;

如果您只想直接从 Thymeleaf 获取 Principal 类属性,那么您也可以执行以下操作:

<span sec:authentication="principal.username">Username</span>