我必須從我的User班級(jí)中刪除一個(gè)登錄字段并email在 SecurityUtils 中用作用戶名我已經(jīng)j_username在前端更改了參數(shù),但現(xiàn)在問題仍然存在于后端public static String getCurrentUserLogin() { SecurityContext securityContext = SecurityContextHolder.getContext(); Authentication authentication = securityContext.getAuthentication(); String userName = null; if (authentication != null) { if (authentication.getPrincipal() instanceof UserDetails) { UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal(); userName = springSecurityUser.getUsername(); } else if (authentication.getPrincipal() instanceof String) { userName = (String) authentication.getPrincipal(); } } return userName; }結(jié)果userName是空的,因?yàn)閁serDetails并且Authentication沒有電子郵件。如何將字段設(shè)置email為“j_username”?我試過這個(gè)如何在春季安全中通過電子郵件而不是用戶名登錄解決方案,但這還不夠,因?yàn)槲沂褂昧薬nonymousUser另外,我有一個(gè)實(shí)現(xiàn),UserDetailsService但是在調(diào)試時(shí)它不會(huì)被調(diào)用anonymousUserpublic class DomainUserDetailsService implements UserDetailsService { private final UserRepository userRepository; public DomainUserDetailsService(UserRepository userRepository) { this.userRepository = userRepository; } @Override public UserDetails loadUserByUsername(final String login) { String lowercaseLogin = login.toLowerCase(Locale.ENGLISH); Optional<User> userFromDatabase = userRepository.findOneByLogin(lowercaseLogin); return userFromDatabase.map(user -> { if (!user.getActivated()) { throw new UserNotActivatedException("User " + lowercaseLogin + " was not activated"); } List<GrantedAuthority> grantedAuthorities = user.getAuthorities().stream() .map(authority -> new SimpleGrantedAuthority(authority.getName())) .collect(Collectors.toList()); return new org.springframework.security.core.userdetails.User(lowercaseLogin, user.getPassword(), grantedAuthorities); }}
2 回答

ABOUTYOU
TA貢獻(xiàn)1812條經(jīng)驗(yàn) 獲得超5個(gè)贊
在這里我分享一些來自我的 Spring Security Configuration 類的代碼
.formLogin().loginPage("/login") .usernameParameter("logInId").passwordParameter("password")
這里我使用'logInId'參數(shù)登錄而不是默認(rèn)參數(shù)......
我想你在搜索這樣的東西.......

狐的傳說
TA貢獻(xiàn)1804條經(jīng)驗(yàn) 獲得超3個(gè)贊
為了實(shí)現(xiàn)您的目標(biāo),您必須控制匿名用戶行為。我之前遇到過這個(gè)問題,當(dāng)用戶登錄時(shí),查詢工作正常。正如 M. Denim 建議的那樣,您應(yīng)該在這里通過電子郵件搜索 ->Optional<User> userFromDatabase = userRepository.findOneByEmail(lowercaseLogin);
但是如果是匿名用戶,getCurrentUserLogin()
您必須編寫一個(gè) if 語句以返回anonymous@localhost
以防萬一userName = anonymousUser
添加回答
舉報(bào)
0/150
提交
取消