注册和登录的实现

一、注册
在注册过程中,除了要对用户提交的注册信息的合法性进行验证,还要对用户的密码进行加密存储,这是注册流程的重点和难点。
用户密码的加密,要通过BCryptPasswordEncoder对象上的encode方法来实现,这个方法返回了一个加密的字符串。

PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
String encodedPassword = passwordEncoder.encode(password);

二、登录
登录过程,它的本质是前端拿到后端返回的token,这样就算成功了。它的实现,重点和难点是token的生成和验证。
首先,生成一个UsernamePasswordAuthenticationToken对象,形参传入用户名和密码,接下来通过authenticationManager(私有的自动装入的Bean)给这个对象进行认证(判断用户名和密码是否正确),如果用户名或密码异常会抛出对应的错误,并返回给前端,如果认证通过,我们可以拿到这个账户的id并给它生成一个jwt返回给前端。

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private AuthenticationManager authenticationManager;
    @Override
    public Map<String, String> getToken(String account_id, String password) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(account_id, password);
        Map<String, String> map = new HashMap<>();
        try{
            Authentication authenticate = authenticationManager.authenticate(authenticationToken);  //  认证用户名和密码是否正确如果认证失败会抛出异常
            UserDetailsImpl loginUser = (UserDetailsImpl) authenticate.getPrincipal();  //  principal意思有当事人、校长的意思
            Account account = loginUser.getAccount();
            String jwt = JwtUtil.createJWT(account.getAccountId());
            map.put("error_message","success");
            map.put("token", jwt);
        } catch(AuthenticationException e){
            if (e instanceof BadCredentialsException) {
                map.put("error_message", "用户名或密码不正确");
            } else if (e instanceof LockedException) {
                map.put("error_message", "该账户状态存在异常");
            } else {
                map.put("error_message", "Authentication failed");
            }
        }
        return map;
    }
}
posted @ 2024-02-14 12:08  惊朝  阅读(5)  评论(0编辑  收藏  举报