SpringBoot利用security、jwt、redis、MySQL、mybatis分层controller、service、mapper、util实现用户登录的代码和各个类的分析
时间: 2023-11-06 07:05:04 浏览: 188
以下是SpringBoot利用security、jwt、redis、MySQL、mybatis分层controller、service、mapper、util实现用户登录的代码:
### UserController.java
```java
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@PostMapping("/register")
public Result register(@RequestBody User user) {
userService.register(user);
return Result.success();
}
@PostMapping("/login")
public Result login(@RequestBody User user) {
String token = userService.login(user.getUsername(), user.getPassword());
return Result.success(token);
}
}
```
### UserServiceImpl.java
```java
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Autowired
private RedisTemplate<String, Object> redisTemplate;
private static final String REDIS_USER_PREFIX = "user:";
@Override
public void register(User user) {
userMapper.insert(user);
}
@Override
public String login(String username, String password) {
User user = userMapper.selectByUsername(username);
if (user == null || !user.getPassword().equals(password)) {
throw new BusinessException(ResultCode.USER_LOGIN_ERROR);
}
String token = JwtTokenUtil.generateToken(user.getId());
redisTemplate.opsForValue().set(REDIS_USER_PREFIX + token, user, JwtTokenUtil.EXPIRATION_TIME, TimeUnit.MILLISECONDS);
return token;
}
@Override
public User getUserByToken(String token) {
return (User) redisTemplate.opsForValue().get(REDIS_USER_PREFIX + token);
}
}
```
### UserMapper.java
```java
@Mapper
public interface UserMapper {
void insert(User user);
User selectByUsername(String username);
}
```
### JwtTokenUtil.java
```java
public class JwtTokenUtil {
public static final long EXPIRATION_TIME = 86400000L;
private static final String SECRET = "mysecret";
public static String generateToken(int userId) {
Date now = new Date();
Date expirationTime = new Date(now.getTime() + EXPIRATION_TIME);
return Jwts.builder()
.setSubject(String.valueOf(userId))
.setIssuedAt(now)
.setExpiration(expirationTime)
.signWith(SignatureAlgorithm.HS512, SECRET)
.compact();
}
public static boolean validateToken(String token) {
try {
Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token);
return true;
} catch (Exception e) {
return false;
}
}
public static int getUserIdFromToken(String token) {
Claims claims = Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token).getBody();
return Integer.parseInt(claims.getSubject());
}
}
```
### WebSecurityConfig.java
```java
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private JwtAuthenticationFilter jwtAuthenticationFilter;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/user/register", "/user/login").permitAll()
.anyRequest().authenticated()
.and()
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
```
### JwtAuthenticationFilter.java
```java
public class JwtAuthenticationFilter extends OncePerRequestFilter {
@Autowired
private UserService userService;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
String token = request.getHeader("Authorization");
if (StringUtils.hasText(token) && JwtTokenUtil.validateToken(token)) {
User user = userService.getUserByToken(token);
if (user != null) {
SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(user, null, Collections.emptyList()));
}
}
filterChain.doFilter(request, response);
}
}
```
### UserDetailsServiceImple.java
```java
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
private UserMapper userMapper;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userMapper.selectByUsername(username);
if (user == null) {
throw new UsernameNotFoundException("用户名不存在");
}
return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), Collections.emptyList());
}
}
```
### Result.java
```java
public class Result {
private int code;
private String message;
private Object data;
public static Result success() {
return new Result(ResultCode.SUCCESS);
}
public static Result success(Object data) {
return new Result(ResultCode.SUCCESS, data);
}
public static Result failure(ResultCode resultCode) {
return new Result(resultCode);
}
public static Result failure(ResultCode resultCode, Object data) {
return new Result(resultCode, data);
}
private Result(ResultCode resultCode) {
this.code = resultCode.getCode();
this.message = resultCode.getMessage();
}
private Result(ResultCode resultCode, Object data) {
this.code = resultCode.getCode();
this.message = resultCode.getMessage();
this.data = data;
}
// getter and setter
}
```
### BusinessException.java
```java
public class BusinessException extends RuntimeException {
private ResultCode resultCode;
public BusinessException(ResultCode resultCode) {
super(resultCode.getMessage());
this.resultCode = resultCode;
}
public ResultCode getResultCode() {
return resultCode;
}
}
```
### ResultCode.java
```java
public enum ResultCode {
SUCCESS(200, "操作成功"),
USER_LOGIN_ERROR(401, "用户名或密码错误"),
UNAUTHORIZED(401, "未授权访问"),
FORBIDDEN(403, "禁止访问"),
NOT_FOUND(404, "资源不存在"),
INTERNAL_SERVER_ERROR(500, "服务器内部错误");
private int code;
private String message;
ResultCode(int code, String message) {
this.code = code;
this.message = message;
}
// getter
}
```
以上是代码,下面是各个类的分析:
- UserController:用户控制器,处理用户注册和登录请求。
- UserServiceImpl:用户服务实现类,处理用户注册、登录和获取用户信息。
- UserMapper:用户数据访问接口,提供插入用户和根据用户名查询用户的方法。
- JwtTokenUtil:JWT令牌工具类,提供生成令牌、验证令牌和从令牌中获取用户ID的方法。
- WebSecurityConfig:Web安全配置类,配置用户认证和授权相关信息。
- JwtAuthenticationFilter:JWT认证过滤器,用于从HTTP请求中提取JWT令牌,并进行认证和授权。
- UserDetailsServiceImpl:用户详情服务实现类,用于从数据库中查询用户信息,并返回一个UserDetails对象。
- Result:结果类,用于封装请求的处理结果和响应给客户端。
- BusinessException:业务异常类,用于封装业务错误信息。
- ResultCode:结果代码枚举类,用于定义响应状态码和对应的消息。
阅读全文