创建 mall-spring-boot-starter-security-user 模块,用于用户的认证拦截器

This commit is contained in:
YunaiV 2020-07-04 23:25:22 +08:00
parent d89e5bad98
commit 93c646890d
27 changed files with 345 additions and 186 deletions

View File

@ -71,11 +71,13 @@ public class ServiceExceptionUtil {
}
public static ServiceException exception(Enumerable enumerable) {
return exception(enumerable.getCode());
String messagePattern = messages.getOrDefault(enumerable.getCode(), enumerable.getMessage());
return exception0(enumerable.getCode(), messagePattern);
}
public static ServiceException exception(Enumerable enumerable, Object... params) {
return exception(enumerable.getCode(), params);
String messagePattern = messages.getOrDefault(enumerable.getCode(), enumerable.getMessage());
return exception0(enumerable.getCode(), messagePattern, params);
}
/**

View File

@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>common</artifactId>
<groupId>cn.iocoder.mall</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>mall-security-annotations</artifactId>
</project>

View File

@ -1,4 +1,4 @@
package cn.iocoder.mall.security.core.annotation;
package cn.iocoder.security.annotations;
import java.lang.annotation.*;

View File

@ -1,4 +1,4 @@
package cn.iocoder.mall.security.core.annotation;
package cn.iocoder.security.annotations;
import java.lang.annotation.*;

View File

@ -0,0 +1,47 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>common</artifactId>
<groupId>cn.iocoder.mall</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>mall-spring-boot-starter-security-user</artifactId>
<dependencies>
<!-- Mall 相关 -->
<dependency>
<groupId>cn.iocoder.mall</groupId>
<artifactId>system-service-api</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<!-- Spring 核心 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<!-- Web 相关 -->
<dependency>
<groupId>cn.iocoder.mall</groupId>
<artifactId>mall-spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>cn.iocoder.mall</groupId>
<artifactId>mall-security-annotations</artifactId>
</dependency>
<!-- RPC 相关 -->
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo</artifactId>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,35 @@
package cn.iocoder.mall.security.user.config;
import cn.iocoder.mall.security.user.core.interceptor.UserSecurityInterceptor;
import cn.iocoder.mall.web.config.CommonWebAutoConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
@AutoConfigureAfter(CommonWebAutoConfiguration.class) // CommonWebAutoConfiguration 之后自动配置保证过滤器的顺序
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
public class UserSecurityAutoConfiguration implements WebMvcConfigurer {
private Logger logger = LoggerFactory.getLogger(getClass());
// ========== 拦截器相关 ==========
@Bean
public UserSecurityInterceptor userSecurityInterceptor() {
return new UserSecurityInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
// UserSecurityInterceptor 拦截器
registry.addInterceptor(this.userSecurityInterceptor());
logger.info("[addInterceptors][加载 UserSecurityInterceptor 拦截器完成]");
}
}

View File

@ -0,0 +1,18 @@
package cn.iocoder.mall.security.user.core.context;
import lombok.Data;
import lombok.experimental.Accessors;
/**
* User Security 上下文
*/
@Data
@Accessors(chain = true)
public class UserSecurityContext {
/**
* 用户编号
*/
private Integer userId;
}

View File

@ -0,0 +1,35 @@
package cn.iocoder.mall.security.user.core.context;
/**
* {@link UserSecurityContext} Holder
*
* 参考 spring security ThreadLocalSecurityContextHolderStrategy 简单实现
*/
public class UserSecurityContextHolder {
private static final ThreadLocal<UserSecurityContext> SECURITY_CONTEXT = new ThreadLocal<UserSecurityContext>();
public static void setContext(UserSecurityContext context) {
SECURITY_CONTEXT.set(context);
}
public static UserSecurityContext getContext() {
UserSecurityContext ctx = SECURITY_CONTEXT.get();
// 为空时设置一个空的进去
if (ctx == null) {
ctx = new UserSecurityContext();
SECURITY_CONTEXT.set(ctx);
}
return ctx;
}
public static Integer getUserId() {
UserSecurityContext ctx = SECURITY_CONTEXT.get();
return ctx != null ? ctx.getUserId() : null;
}
public static void clear() {
SECURITY_CONTEXT.remove();
}
}

View File

@ -0,0 +1,72 @@
package cn.iocoder.mall.security.user.core.interceptor;
import cn.iocoder.common.framework.enums.UserTypeEnum;
import cn.iocoder.common.framework.util.HttpUtil;
import cn.iocoder.common.framework.util.ServiceExceptionUtil;
import cn.iocoder.common.framework.vo.CommonResult;
import cn.iocoder.mall.security.user.core.context.UserSecurityContext;
import cn.iocoder.mall.security.user.core.context.UserSecurityContextHolder;
import cn.iocoder.mall.systemservice.enums.SystemErrorCodeEnum;
import cn.iocoder.mall.systemservice.rpc.oauth.OAuth2Rpc;
import cn.iocoder.mall.systemservice.rpc.oauth.vo.OAuth2AccessTokenVO;
import cn.iocoder.mall.web.core.util.CommonWebUtil;
import cn.iocoder.security.annotations.RequiresAuthenticate;
import cn.iocoder.security.annotations.RequiresPermissions;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import static cn.iocoder.mall.systemservice.enums.SystemErrorCodeEnum.OAUTH_USER_TYPE_ERROR;
public class UserSecurityInterceptor extends HandlerInterceptorAdapter {
@Reference(validation = "true", version = "${dubbo.consumer.OAuth2Rpc.version}")
private OAuth2Rpc oauth2Rpc;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
// 获得访问令牌
String accessToken = HttpUtil.obtainAuthorization(request);
Integer userId = null;
if (accessToken != null) {
CommonResult<OAuth2AccessTokenVO> checkAccessTokenResult = oauth2Rpc.checkAccessToken(accessToken);
checkAccessTokenResult.checkError();
// 校验用户类型正确
if (!UserTypeEnum.USER.getValue().equals(checkAccessTokenResult.getData().getUserType())) {
throw ServiceExceptionUtil.exception(OAUTH_USER_TYPE_ERROR);
}
// 获得用户编号
userId = checkAccessTokenResult.getData().getUserId();
// 设置到 Request
CommonWebUtil.setUserId(request, userId);
CommonWebUtil.setUserType(request, UserTypeEnum.USER.getValue());
// 设置到
UserSecurityContext userSecurityContext = new UserSecurityContext().setUserId(userId);
UserSecurityContextHolder.setContext(userSecurityContext);
}
// 校验认证
this.checkAuthentication((HandlerMethod) handler, userId);
return true;
}
private void checkAuthentication(HandlerMethod handlerMethod, Integer userId) {
boolean requiresAuthenticate = false; // 对于 USER 来说默认无需登录
if (handlerMethod.hasMethodAnnotation(RequiresAuthenticate.class)
|| handlerMethod.hasMethodAnnotation(RequiresPermissions.class)) { // 如果需要权限验证也认为需要认证
requiresAuthenticate = true;
}
if (requiresAuthenticate && userId == null) {
throw ServiceExceptionUtil.exception(SystemErrorCodeEnum.OAUTH2_NOT_AUTHENTICATION);
}
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
// 清空 SecurityContext
UserSecurityContextHolder.clear();
}
}

View File

@ -0,0 +1,2 @@
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
cn.iocoder.mall.security.user.config.UserSecurityAutoConfiguration

View File

@ -16,7 +16,9 @@
<module>mall-spring-boot</module>
<module>mall-spring-boot-starter-swagger</module>
<module>mall-spring-boot-starter-web</module>
<module>mall-security-annotations</module>
<module>mall-spring-boot-starter-security</module>
<module>mall-spring-boot-starter-security-user</module>
<module>mall-spring-boot-starter-mybatis</module>
</modules>
<dependencies>

View File

@ -140,11 +140,21 @@
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>cn.iocoder.mall</groupId>
<artifactId>mall-security-annotations</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>cn.iocoder.mall</groupId>
<artifactId>mall-spring-boot-starter-security</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>cn.iocoder.mall</groupId>
<artifactId>mall-spring-boot-starter-security-user</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>cn.iocoder.mall</groupId>

View File

@ -15,13 +15,12 @@ public enum SystemErrorCodeEnum implements ServiceExceptionUtil.Enumerable<Syste
OAUTH2_ACCESS_TOKEN_NOT_FOUND(1001001001, "访问令牌不存在"),
OAUTH2_ACCESS_TOKEN_TOKEN_EXPIRED(1001001002, "访问令牌已过期"),
OAUTH2_ACCESS_TOKEN_INVALID(1001001003, "访问令牌已失效"),
OAUTH2_NOT_AUTHENTICATE(1001001004, "账号未登陆"),
OAUTH2_NOT_AUTHENTICATION(1001001004, "账号未登录"),
OAUTH2_REFRESH_TOKEN_NOT_FOUND(1001001005, "刷新令牌不存在"),
OAUTH_REFRESH_TOKEN_EXPIRED(1001001006, "访问令牌已过期"),
OAUTH_REFRESH_TOKEN_INVALID(1001001007, "刷新令牌已失效"),
// 其它 1001001100 开始
OAUTH2_ACCOUNT_NOT_FOUND(1001001100, "账号不存在"),
OAUTH2_ACCOUNT_PASSWORD_ERROR(1001001101, "密码不正确"),
OAUTH_USER_TYPE_ERROR(1001001101, "用户类型并不正确"),
// ========== 管理员模块 1002002000 ==========
ADMIN_NOT_FOUND(1002002000, "管理员不存在"),

View File

@ -17,6 +17,10 @@ public class UserVO implements Serializable {
* 用户编号
*/
private Integer id;
/**
* 手机号
*/
private String mobile;
/**
* 昵称
*/

View File

@ -31,6 +31,11 @@
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>cn.iocoder.mall</groupId>
<artifactId>mall-spring-boot-starter-security-user</artifactId>
</dependency>
<!-- RPC 相关 -->
<dependency>
<groupId>com.alibaba.cloud</groupId>

View File

@ -1,7 +1,55 @@
package cn.iocoder.mall.userweb.controller.user;
import cn.iocoder.common.framework.vo.CommonResult;
import cn.iocoder.mall.security.user.core.context.UserSecurityContextHolder;
import cn.iocoder.mall.userweb.controller.user.vo.UserInfoVO;
import cn.iocoder.mall.userweb.manager.user.UserManager;
import cn.iocoder.security.annotations.RequiresAuthenticate;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import static cn.iocoder.common.framework.vo.CommonResult.success;
@Api(tags = "用户信息 API")
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserManager userManager;
@ApiOperation(value = "用户信息")
@GetMapping("/info")
@RequiresAuthenticate
public CommonResult<UserInfoVO> info() {
UserInfoVO user = userManager.getUser(UserSecurityContextHolder.getUserId());
return success(user);
}
// @PostMapping("/update_avatar")
// @RequiresLogin
// @ApiOperation(value = "更新头像")
// public CommonResult<Boolean> updateAvatar(@RequestParam("avatar") String avatar) {
// // 创建
// UserUpdateDTO userUpdateDTO = new UserUpdateDTO().setId(UserSecurityContextHolder.getContext().getUserId())
// .setAvatar(avatar);
// // 更新头像
// return success(userService.updateUser(userUpdateDTO));
// }
//
// @PostMapping("/update_nickname")
// @RequiresLogin
// @ApiOperation(value = "更新昵称")
// public CommonResult<Boolean> updateNickname(@RequestParam("nickname") String nickname) {
// // 创建
// UserUpdateDTO userUpdateDTO = new UserUpdateDTO().setId(UserSecurityContextHolder.getContext().getUserId())
// .setNickname(nickname);
// // 更新头像
// return success(userService.updateUser(userUpdateDTO));
// }
}

View File

@ -1,4 +1,4 @@
package cn.iocoder.mall.user.application.vo.users;
package cn.iocoder.mall.userweb.controller.user.vo;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@ -8,7 +8,7 @@ import lombok.experimental.Accessors;
@ApiModel("用户信息 VO")
@Data
@Accessors(chain = true)
public class UsersUserVO {
public class UserInfoVO {
@ApiModelProperty(value = "用户编号", required = true, example = "123")
private Integer id;

View File

@ -1 +0,0 @@
package cn.iocoder.mall.userweb.convert;

View File

@ -0,0 +1,15 @@
package cn.iocoder.mall.userweb.convert.user;
import cn.iocoder.mall.userservice.rpc.user.vo.UserVO;
import cn.iocoder.mall.userweb.controller.user.vo.UserInfoVO;
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;
@Mapper
public interface UserConvert {
UserConvert INSTANCE = Mappers.getMapper(UserConvert.class);
UserInfoVO convert(UserVO bean);
}

View File

@ -0,0 +1,23 @@
package cn.iocoder.mall.userweb.manager.user;
import cn.iocoder.common.framework.vo.CommonResult;
import cn.iocoder.mall.userservice.rpc.user.UserRpc;
import cn.iocoder.mall.userservice.rpc.user.vo.UserVO;
import cn.iocoder.mall.userweb.controller.user.vo.UserInfoVO;
import cn.iocoder.mall.userweb.convert.user.UserConvert;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Service;
@Service
public class UserManager {
@Reference(version = "${dubbo.consumer.UserRpc.version}", validation = "false")
private UserRpc userRpc;
public UserInfoVO getUser(Integer id) {
CommonResult<UserVO> userResult = userRpc.getUser(id);
userResult.checkError();
return UserConvert.INSTANCE.convert(userResult.getData());
}
}

View File

@ -16,7 +16,7 @@ spring:
dubbo:
# Spring Cloud Alibaba Dubbo 专属配置
cloud:
subscribed-services: 'user-service, system-service' # 设置订阅的应用列表,默认为 * 订阅所有应用
subscribed-services: 'user-service,system-service' # 设置订阅的应用列表,默认为 * 订阅所有应用
# Dubbo 服务消费者的配置
consumer:
timeout: 10000
@ -26,3 +26,5 @@ dubbo:
version: 1.0.0
OAuth2Rpc:
version: 1.0.0
SystemLogRPC:
version: 1.0.0

View File

@ -1,56 +0,0 @@
package cn.iocoder.mall.user.application.controller.users;
import cn.iocoder.common.framework.constant.UserTypeEnum;
import cn.iocoder.common.framework.vo.CommonResult;
import cn.iocoder.mall.system.api.OAuth2Service;
import cn.iocoder.mall.system.api.bo.oauth2.OAuth2AccessTokenBO;
import cn.iocoder.mall.system.api.dto.oauth2.OAuth2RefreshTokenDTO;
import cn.iocoder.mall.user.api.UserService;
import io.swagger.annotations.Api;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import static cn.iocoder.common.framework.vo.CommonResult.success;
@RestController
@RequestMapping("users/passport")
@Api("Passport 模块")
public class PassportController {
@Reference(validation = "true", version = "${dubbo.consumer.OAuth2Service.version}")
private OAuth2Service oauth2Service;
@Reference(validation = "true", version = "${dubbo.provider.UserService.version}")
private UserService userService;
// TODO 功能手机密码登陆
// @PostMapping("/mobile/pwd/login")
// public OAuth2AccessToken mobileLogin(@RequestParam("mobile") String mobile,
// @RequestParam("password") String password) {
// return oauth2Service.getAccessToken(clientId, clientSecret, mobile, password);
// }
// TODO 芋艿改绑手机号
// TODO 功能qq 登陆
@PostMapping("/qq/login")
public String qqLogin() {
return null;
}
// TODO 功能qq 绑定
@PostMapping("/qq/bind")
public String qqBind() {
return null;
}
@PostMapping("/refresh_token") // TODO 功能刷新 token
public CommonResult<OAuth2AccessTokenBO> refreshToken(@RequestParam("refreshToken") String refreshToken) {
return success(oauth2Service.refreshToken(new OAuth2RefreshTokenDTO().setRefreshToken(refreshToken)
.setUserType(UserTypeEnum.USER.getValue())));
}
// TODO 功能退出销毁 token
}

View File

@ -1,56 +0,0 @@
package cn.iocoder.mall.user.application.controller.users;
import cn.iocoder.common.framework.vo.CommonResult;
import cn.iocoder.mall.user.api.UserService;
import cn.iocoder.mall.user.api.bo.UserBO;
import cn.iocoder.mall.user.api.dto.UserUpdateDTO;
import cn.iocoder.mall.user.application.convert.UserConvert;
import cn.iocoder.mall.user.application.vo.users.UsersUserVO;
import cn.iocoder.mall.user.sdk.annotation.RequiresLogin;
import cn.iocoder.mall.user.sdk.context.UserSecurityContextHolder;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.*;
import static cn.iocoder.common.framework.vo.CommonResult.success;
@RestController
@RequestMapping("/users/user")
@Api("用户模块")
public class UserController {
@Reference(validation = "true", version = "${dubbo.provider.UserService.version}")
private UserService userService;
@GetMapping("/info")
@RequiresLogin
@ApiOperation(value = "用户信息")
public CommonResult<UsersUserVO> info() {
UserBO userResult = userService.getUser(UserSecurityContextHolder.getContext().getUserId());
return success(UserConvert.INSTANCE.convert2(userResult));
}
@PostMapping("/update_avatar")
@RequiresLogin
@ApiOperation(value = "更新头像")
public CommonResult<Boolean> updateAvatar(@RequestParam("avatar") String avatar) {
// 创建
UserUpdateDTO userUpdateDTO = new UserUpdateDTO().setId(UserSecurityContextHolder.getContext().getUserId())
.setAvatar(avatar);
// 更新头像
return success(userService.updateUser(userUpdateDTO));
}
@PostMapping("/update_nickname")
@RequiresLogin
@ApiOperation(value = "更新昵称")
public CommonResult<Boolean> updateNickname(@RequestParam("nickname") String nickname) {
// 创建
UserUpdateDTO userUpdateDTO = new UserUpdateDTO().setId(UserSecurityContextHolder.getContext().getUserId())
.setNickname(nickname);
// 更新头像
return success(userService.updateUser(userUpdateDTO));
}
}

View File

@ -1,22 +0,0 @@
package cn.iocoder.mall.user.application.convert;
import cn.iocoder.mall.user.api.bo.UserBO;
import cn.iocoder.mall.user.api.bo.UserPageBO;
import cn.iocoder.mall.user.application.vo.admins.AdminsUserPageVO;
import cn.iocoder.mall.user.application.vo.users.UsersUserVO;
import org.mapstruct.Mapper;
import org.mapstruct.Mappings;
import org.mapstruct.factory.Mappers;
@Mapper
public interface UserConvert {
UserConvert INSTANCE = Mappers.getMapper(UserConvert.class);
@Mappings({})
AdminsUserPageVO convert(UserPageBO result);
@Mappings({})
UsersUserVO convert2(UserBO result);
}

View File

@ -1,20 +0,0 @@
package cn.iocoder.mall.user.application.vo.users;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.experimental.Accessors;
@ApiModel("认证令牌 VO")
@Data
@Accessors(chain = true)
public class UsersAccessTokenVO {
@ApiModelProperty(value = "访问令牌", required = true, example = "2e3d7635c15e47e997611707a237859f")
private String accessToken;
@ApiModelProperty(value = "刷新令牌", required = true, example = "d091e7c35bbb4313b0f557a6ef23d033")
private String refreshToken;
@ApiModelProperty(value = "过期时间,单位:秒", required = true, example = "2879")
private Integer expiresIn;
}

View File

@ -1,20 +0,0 @@
package cn.iocoder.mall.user.application.vo.users;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.experimental.Accessors;
@ApiModel("手机注册结果 VO")
@Data
@Accessors(chain = true)
public class UsersMobileRegisterVO {
@ApiModelProperty(value = "访问令牌", required = true, example = "2e3d7635c15e47e997611707a237859f")
private String accessToken;
@ApiModelProperty(value = "刷新令牌", required = true, example = "d091e7c35bbb4313b0f557a6ef23d033")
private String refreshToken;
@ApiModelProperty(value = "过期时间,单位:秒", required = true, example = "2879")
private Integer expiresIn;
}