我有这堂课:
@Service
public class AppUserDetailsService implements UserDetailsService {
@Autowired
private UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
Optional<User> optionalUser = userRepository.findByEmailAndStatus(email, UserStatusEnum.ACTIVE);
User user = optionalUser.orElseThrow(() -> new UsernameNotFoundException("Usuário e/ou senha incorretos"));
return new UserSystem(user, getPermissoes(user));
}
private Collection<? extends GrantedAuthority> getPermissoes(User user) {
Set<SimpleGrantedAuthority> authorities = new HashSet<>();
user.getPermitionList().forEach(p -> authorities.add(new SimpleGrantedAuthority(p.getCode().getDescription().toUpperCase())));
return authorities;
}
}
我的HTML格式:
<form name="login" method="POST" th:action="@{/login}">
<div class="form-group">
<input type="email" class="form-control input-lg" id="email" placeholder="Email" name="email"
required="required"/>
</div>
<div class="form-group">
<input type="password" class="form-control input-lg" id="password" placeholder="Senha" name="password"
required="required"/>
</div>
<div class="btn-group btn-group-justified" role="group">
<div class="btn-group" role="group">
<button type="button" class="btn btn-danger" onclick="showUserForm()">Cadastar</button>
</div>
<div class="btn-group" role="group">
<button type="submit" class="btn btn-default">Entrar</button>
</div>
</div>
<button type="button" class="btn btn-link wimoo-link">Esqueceu sua senha?</button>
</form>
我的登录Bean:
@GetMapping("/login")
public ModelAndView login(@AuthenticationPrincipal User user) {
ModelAndView mv = new ModelAndView("login");
mv.addObject(new User());
if (user != null) {
mv = new ModelAndView("masterdata/home");
return mv;
}
return mv;
}
问题是,用户在我的方法&#39;公共ModelAndView登录(@AuthenticationPrincipal用户用户)&#39;永远是空的。 loadUserByUsername方法没问题,但在我的bean中,用户始终为null。
答案 0 :(得分:1)
你遗漏了一些东西。您没有在登录方法中将表单详细信息绑定到您的用户。为了做绑定,请执行以下操作:
在您的表单上,您有:
<div class="form-group">
<input type="email" class="form-control input-lg" id="email" placeholder="Email" name="email" required="required"/>
</div>
如果您要将表单中的此电子邮件绑定到User对象上的电子邮件字段,那么如果您在User类上有:
public class User{
private String myEmailAddress;
}
然后在输入标记上,您应该添加一个等于myEmailAddress的name属性,以便将您的表单中的值绑定到登录方法上的User对象。
<div class="form-group">
<input type="email" name="myEmailAddress" class="form-control input-lg" id="email" placeholder="Email" required="required"/>
</div>
您现在需要做的就是将@ModelAttribute
注释添加到您的登录方法中,以便实际执行此绑定。像这样:
@GetMapping("/login")
public ModelAndView login(@AuthenticationPrincipal @ModelAttribute User user) {
ModelAndView mv = new ModelAndView("login");
mv.addObject(new User());
if (user != null) {
mv = new ModelAndView("masterdata/home");
return mv;
}
return mv;
}