62 lines
2.4 KiB
Java
62 lines
2.4 KiB
Java
|
|
package com.rzyc.service;
|
|||
|
|
|
|||
|
|
|
|||
|
|
import com.common.utils.jwt.JwtUtil;
|
|||
|
|
import com.rzyc.config.EntUserDetails;
|
|||
|
|
import org.springframework.beans.factory.annotation.Autowired;
|
|||
|
|
import org.springframework.security.authentication.BadCredentialsException;
|
|||
|
|
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
|||
|
|
import org.springframework.security.core.AuthenticationException;
|
|||
|
|
import org.springframework.security.core.context.SecurityContextHolder;
|
|||
|
|
import org.springframework.security.core.userdetails.UserDetails;
|
|||
|
|
import org.springframework.security.core.userdetails.UserDetailsService;
|
|||
|
|
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
|||
|
|
import org.springframework.security.crypto.password.PasswordEncoder;
|
|||
|
|
import org.springframework.stereotype.Service;
|
|||
|
|
import java.util.Objects;
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 用户登陆 Service
|
|||
|
|
* @author Xuwanxin
|
|||
|
|
* @date 2022/9/26
|
|||
|
|
* */
|
|||
|
|
|
|||
|
|
@Service
|
|||
|
|
public class UserLoginService {
|
|||
|
|
|
|||
|
|
|
|||
|
|
private UserDetailsService userDetailsService;
|
|||
|
|
|
|||
|
|
|
|||
|
|
private PasswordEncoder passwordEncoder;
|
|||
|
|
|
|||
|
|
@Autowired
|
|||
|
|
public void UserLoginServiceFinder(UserDetailsService userDetailsService,PasswordEncoder passwordEncoder){
|
|||
|
|
this.userDetailsService = userDetailsService;
|
|||
|
|
this.passwordEncoder = passwordEncoder;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
public String login(String username, String password) {
|
|||
|
|
String token = null;
|
|||
|
|
try {
|
|||
|
|
UserDetails userDetails = userDetailsService.loadUserByUsername(username);
|
|||
|
|
if (Objects.isNull(userDetails)) {
|
|||
|
|
throw new UsernameNotFoundException("账号不存在");
|
|||
|
|
}
|
|||
|
|
//这里可能会不对,因为我们是MD5,这个是spring security 中的 encoder加密
|
|||
|
|
if (!passwordEncoder.matches(password, userDetails.getPassword())) {
|
|||
|
|
throw new BadCredentialsException("密码不正确");
|
|||
|
|
}
|
|||
|
|
//spring security context insert
|
|||
|
|
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
|
|||
|
|
SecurityContextHolder.getContext().setAuthentication(authentication);
|
|||
|
|
//企业用户id
|
|||
|
|
String id = ((EntUserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getId();
|
|||
|
|
token = JwtUtil.createToken(id);
|
|||
|
|
} catch (AuthenticationException e) {
|
|||
|
|
e.printStackTrace();
|
|||
|
|
}
|
|||
|
|
return token;
|
|||
|
|
}
|
|||
|
|
}
|