我怎样才能显示登录用户与Spring引导Thymeleaf当前?

问题描述 投票:2回答:4

我想,但是我不断收到错误显示当前用户的详细信息。我试图从模板访问身份验证的用户,但因为我得到这个错误,没有工作:

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

我想从控制器的信息,然后将其保存在一个字符串,passsing字符串到模板但不工作要么。

这里是我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());
}


}

下面是从模板类,我想获取一些信息的代码:

个:文本= “$ {#authentication.getPrincipal()的getFirstName()}”>

个:文本= “$ {#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

spring spring-boot login spring-security thymeleaf
4个回答
6
投票

您可以使用Thymeleaf额外显示身份验证的用户的详细信息。

Thymeleaf Extras Springsecurity4

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

1
投票

问题就在这里:

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

你失去了参考您的User实体。将其更改为:

return user;

对于这个工作,你需要更新你的User实体,实现UserDetails接口:

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

然后,你Thymeleaf代码应工作。获得firstName将是另一种方式:

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

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模板:

电子邮箱:到:文本= “$ {电子邮件地址}”


0
投票

参考(4 Spring Security的话):

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

添加依赖的pom.xml

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

和视图(Thymeleaf):

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

我希望你能为他们服务

© www.soinside.com 2019 - 2024. All rights reserved.