我一直在努力让@AuthenticationPrincipal与自定义User类一起正常工作.不幸的是,用户始终为空.这是代码:
调节器
@RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView index(@AuthenticationPrincipal User user) {
ModelAndView mav= new ModelAndView("/web/index");
mav.addObject("user", user);
return mav;
}
Run Code Online (Sandbox Code Playgroud)
安全配置
@Configuration
@EnableWebMvcSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
CustomUserDetailsService customUserDetailsService;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(customUserDetailsService).passwordEncoder(passwordEncoder());
}
Run Code Online (Sandbox Code Playgroud)
}
CustomUserDetailsService
@Component
public class CustomUserDetailsService implements UserDetailsService {
@Autowired
UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// Spring Data findByXY function
return userRepository.findByUsername(username);
}
Run Code Online (Sandbox Code Playgroud)
用户实体
public class User implements UserDetails{
private …Run Code Online (Sandbox Code Playgroud) 问题: 我想从authenticate.getName()中获取/提取用户名/电子邮件...如果可能,不要使用解析字符串.
authentication.getName()或principal.getName()值:
[username]: org.springframework.security.core.userdetails.User@21463e7a: Username: butitoy@iyotbihagay.com; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Not granted any authorities
Run Code Online (Sandbox Code Playgroud)
在这个例子中,我只想获得Username的值,即butitoy@iyotbihagay.com
解:
由于我只想获得用户名/电子邮件(butitoy@iyotbihagay.com),并且它返回了整个主要内容/文本(上图),我将主题中设置的值从主要值...替换为电子邮件价值..它现在有效.
@Override
protected void successfulAuthentication(HttpServletRequest req,
HttpServletResponse res,
FilterChain chain,
Authentication auth) throws IOException, ServletException {
String email = auth.getName();
String principal = auth.getPrincipal().toString();
Date expiration = new Date(System.currentTimeMillis() + SecurityConstants.EXPIRATION_TIME);
String token = Jwts.builder()
.setSubject(email) //from principal to email
.setExpiration(expiration)
.signWith(SignatureAlgorithm.HS512, SecurityConstants.SECRET.getBytes())
.compact();
AuthenticatedUser loginUser = new AuthenticatedUser(email);
loginUser.setToken(token);
String jsonUser = Util.objectToJsonResponseAsString(loginUser, "user");
res.addHeader(SecurityConstants.HEADER_STRING, SecurityConstants.TOKEN_PREFIX …Run Code Online (Sandbox Code Playgroud)