我试图弄清楚如何实现授权,我设法做到了,但它只能在浏览器重新启动之前起作用。
我在谷歌上搜索了在单独的服务器上为客户端实现授权的示例,但到处都是与 JSP 相同的文章,最终决定尝试为我自己采用其中一个并实现以下类
UserDetailsService
和AuthenticationManager
一个授权类AuthenticateService
。然后我决定添加rememberm-me功能,在config中添加设置,在数据库中添加了一个表,但是在授权时,没有添加cookie和数据库条目。也许在使用 rememberm-me 时你需要不使用UsernamePasswordAuthenticationToken
或添加某种过滤器?所以我想知道应该使用哪些接口\类通过令牌进行授权。
@Component
public class CustomUserDetails implements UserDetailsService {
@Autowired
private UserRepo userRepo;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
EntityUser user = userRepo.findByUsername(username);
List<GrantedAuthority> grantedAuthorities =new ArrayList<>();
for (EntityRole entityRole : user.getRoles()) {
grantedAuthorities.add(new SimpleGrantedAuthority(entityRole.getRoleName()));
}
return new User(user.getUsername(),user.getPassword(),grantedAuthorities);
}
}
@Component
public class CustomAuthentivationManager implements AuthenticationManager {
@Autowired
private UserRepo userRepo;
@Autowired
private CustomUserDetails customUserDetails;
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
UserDetails userDetails = (UserDetails) authentication.getPrincipal();
if (userDetails.getPassword().equals(authentication.getPrincipal())){
authentication.setAuthenticated(true);
}
return authentication;
}
}
@Service
public class AuthenticateService implements IAuthentivateService {
@Autowired
private CustomAuthentivationManager authenticationManager;
@Autowired
private CustomUserDetails customUserDetails;
@Override
public String findLigInUsername() {
Object userDetails = SecurityContextHolder.getContext().getAuthentication().getDetails();
if (userDetails instanceof UserDetails){
return ((UserDetails) userDetails).getUsername();
}
return null;
}
@Override
public boolean autologin(String username, String password) {
UserDetails userDetails = customUserDetails.loadUserByUsername(username);
UsernamePasswordAuthenticationToken token
= new UsernamePasswordAuthenticationToken(userDetails,password,userDetails.getAuthorities());
authenticationManager.authenticate(token);
if (token.isAuthenticated()){
SecurityContextHolder.getContext().setAuthentication(token);
return true;
}
return false;
}
}
现在 cookie 被发送到客户端,token 也存储在数据库中。我是这样做的:
1)我们继承自
PersistentTokenBasedRememberMeServices
override 方法onLoginSuccess
并将其公开。2) 从步骤 1 创建一个类 bean
3) 在控制器中,为映射到登录页面 URL 的方法的参数添加
HttpServletRequest request, HttpServletResponse response
,例如4)创建一个令牌
UsernamePasswordAuthenticationToken
,填写并调用将onLoginSuccess
创建的令牌作为参数之一传递的方法,检查身份验证是否已通过并将令牌添加到安全上下文中。PS 我有这样的感觉,这是一个硬拐杖,你可以让一切变得更容易,但现在它工作正常))