统一基础配置名

This commit is contained in:
ronger 2019-12-02 09:39:23 +08:00
parent 2c65a03a4f
commit 4e0e91071e
16 changed files with 72 additions and 100 deletions

View File

@ -4,7 +4,7 @@ import com.alibaba.fastjson.support.spring.FastJsonJsonView;
import com.rymcu.vertical.core.exception.ServiceException;
import com.rymcu.vertical.core.result.GlobalResult;
import com.rymcu.vertical.core.result.ResultCode;
import com.rymcu.vertical.web.api.exception.MallApiException;
import com.rymcu.vertical.web.api.exception.BaseApiException;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
@ -25,16 +25,16 @@ import java.util.Map;
* 全局异常处理器
* */
@RestControllerAdvice
public class HpeisExceptionHandler {
public class BaseExceptionHandler {
private final Logger logger = LoggerFactory.getLogger(HpeisExceptionHandler.class);
private final Logger logger = LoggerFactory.getLogger(BaseExceptionHandler.class);
@SuppressWarnings("Duplicates")
@ExceptionHandler(Exception.class)
public Object errorHandler(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex){
if(isAjax(request)){
GlobalResult result = new GlobalResult();
if (ex instanceof MallApiException){
if (ex instanceof BaseApiException){
result.setCode(401);
result.setMessage("用户未登录");
logger.info("用户未登录");
@ -79,7 +79,7 @@ public class HpeisExceptionHandler {
ModelAndView mv = new ModelAndView();
FastJsonJsonView view = new FastJsonJsonView();
Map<String, Object> attributes = new HashMap();
if (ex instanceof MallApiException){
if (ex instanceof BaseApiException){
attributes.put("code", "401");
attributes.put("message", "用户未登录");
} else if (ex instanceof UnauthenticatedException) {

View File

@ -9,12 +9,12 @@ import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.Serializable;
public class HpeisSessionManager extends DefaultWebSessionManager {
public class BaseSessionManager extends DefaultWebSessionManager {
private static final String AUTHORIZATION = "Authorization";
private static final String REFERENCED_SESSION_ID_SOURCE = "Stateless request";
public HpeisSessionManager() {
public BaseSessionManager() {
super();
}

View File

@ -21,11 +21,11 @@ import java.util.Set;
/**
* Shiro静态资源配置
* */
public class HpeisShiroFilterFactoryBean extends ShiroFilterFactoryBean {
public class BaseShiroFilterFactoryBean extends ShiroFilterFactoryBean {
// 对ShiroFilter来说需要直接忽略的请求
private Set<String> ignoreExt;
public HpeisShiroFilterFactoryBean() {
public BaseShiroFilterFactoryBean() {
super();
ignoreExt = new HashSet<>();
ignoreExt.add(".svg");
@ -56,12 +56,12 @@ public class HpeisShiroFilterFactoryBean extends ShiroFilterFactoryBean {
PathMatchingFilterChainResolver chainResolver = new PathMatchingFilterChainResolver();
chainResolver.setFilterChainManager(manager);
return new HpeisSpringShiroFilter((WebSecurityManager) securityManager, chainResolver);
return new BaseSpringShiroFilter((WebSecurityManager) securityManager, chainResolver);
}
private final class HpeisSpringShiroFilter extends AbstractShiroFilter {
private final class BaseSpringShiroFilter extends AbstractShiroFilter {
protected HpeisSpringShiroFilter(WebSecurityManager webSecurityManager, FilterChainResolver resolver) {
protected BaseSpringShiroFilter(WebSecurityManager webSecurityManager, FilterChainResolver resolver) {
super();
if (webSecurityManager == null) {
throw new IllegalArgumentException("WebSecurityManager property cannot be null.");

View File

@ -30,7 +30,7 @@ import java.util.List;
* @since 2018/05/28 11:00
* 自定义权限匹配和账号密码匹配
* */
public class HpeisShiroRealm extends AuthorizingRealm {
public class BaseShiroRealm extends AuthorizingRealm {
@Resource
private RoleService roleService;

View File

@ -35,7 +35,7 @@ public class ShiroConfig implements EnvironmentAware {
@Bean
public ShiroFilterFactoryBean shirFilter(SecurityManager securityManager) {
ShiroFilterFactoryBean shiroFilterFactoryBean = new HpeisShiroFilterFactoryBean();
ShiroFilterFactoryBean shiroFilterFactoryBean = new BaseShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(securityManager);
Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>();
@ -50,16 +50,8 @@ public class ShiroConfig implements EnvironmentAware {
filterChainDefinitionMap.put("/uploadFile/**", "anon");
filterChainDefinitionMap.put("/login", "anon");
filterChainDefinitionMap.put("/swagger-ui.html", "anon");
filterChainDefinitionMap.put("/swagger-resources", "anon");
filterChainDefinitionMap.put("/swagger-resources/configuration/security", "anon");
filterChainDefinitionMap.put("/swagger-resources/configuration/ui", "anon");
filterChainDefinitionMap.put("/v2/api-docs", "anon");
filterChainDefinitionMap.put("/webjars/springfox-swagger-ui/**", "anon");
filterChainDefinitionMap.put("/api/**", "anon");
// filterChainDefinitionMap.put("/**", "authc");
filterChainDefinitionMap.put("/**", "authc");
filterChainDefinitionMap.put("/**", "auth");
//配置shiro默认登录界面地址前后端分离中登录界面跳转应由前端路由控制后台仅返回json数据
shiroFilterFactoryBean.setLoginUrl("/login");
// 登录成功后要跳转的链接
@ -69,10 +61,10 @@ public class ShiroConfig implements EnvironmentAware {
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
Map<String, Filter> filtersMap = new LinkedHashMap<>();
filtersMap.put("authc",hpeisFormAuthenticationFilter());
filtersMap.put("auth", baseFormAuthenticationFilter());
shiroFilterFactoryBean.setFilters(filtersMap);
filterChainDefinitionMap.put("/**", "authc");
filterChainDefinitionMap.put("/**", "auth");
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
return shiroFilterFactoryBean;
@ -88,14 +80,16 @@ public class ShiroConfig implements EnvironmentAware {
@Bean
public HashedCredentialsMatcher hashedCredentialsMatcher() {
HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
hashedCredentialsMatcher.setHashAlgorithmName("SHA-1");//散列算法:这里使用MD5算法;
hashedCredentialsMatcher.setHashIterations(1024);//散列的次数比如散列两次相当于 md5(md5(""));
// 散列算法:这里使用MD5算法;
hashedCredentialsMatcher.setHashAlgorithmName("SHA-1");
// 散列的次数比如散列两次相当于 md5(md5(""));
hashedCredentialsMatcher.setHashIterations(1024);
return hashedCredentialsMatcher;
}
@Bean
public HpeisShiroRealm hpeisShiroRealm() {
HpeisShiroRealm shiroRealm = new HpeisShiroRealm();
public BaseShiroRealm baseShiroRealm() {
BaseShiroRealm shiroRealm = new BaseShiroRealm();
shiroRealm.setCredentialsMatcher(hashedCredentialsMatcher());
return shiroRealm;
}
@ -104,18 +98,18 @@ public class ShiroConfig implements EnvironmentAware {
@Bean
public SecurityManager securityManager() {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setRealm(hpeisShiroRealm());
securityManager.setRealm(baseShiroRealm());
// 自定义session管理 使用redis
securityManager.setSessionManager(sessionManager());
// 自定义缓存实现 使用redis
//securityManager.setCacheManager(cacheManager());
return securityManager;
}
//自定义sessionManager
/**
* 自定义sessionManager
* */
@Bean
public SessionManager sessionManager() {
HpeisSessionManager sessionManager = new HpeisSessionManager();
BaseSessionManager sessionManager = new BaseSessionManager();
sessionManager.setSessionDAO(redisSessionDAO());
sessionManager.setSessionIdUrlRewritingEnabled(false);
sessionManager.setGlobalSessionTimeout(21600000L);
@ -169,9 +163,6 @@ public class ShiroConfig implements EnvironmentAware {
RedisSessionDAO redisSessionDAO = new RedisSessionDAO();
redisSessionDAO.setRedisManager(redisManager());
redisSessionDAO.setExpire(21600);
// Custom your redis key prefix for session management, if you doesn't define this parameter,
// shiro-redis will use 'shiro_redis_session:' as default prefix
// redisSessionDAO.setKeyPrefix("");
return redisSessionDAO;
}
@ -197,21 +188,13 @@ public class ShiroConfig implements EnvironmentAware {
public LifecycleBeanPostProcessor lifecycleBeanPostProcessor(){
return new LifecycleBeanPostProcessor();
}
//
// /**
// * 开启Shiro的注解(@RequiresRoles,@RequiresPermissions),需借助SpringAOP扫描使用Shiro注解的类,并在必要时进行安全逻辑验证
// * 配置以下两个bean(DefaultAdvisorAutoProxyCreator(可选)和AuthorizationAttributeSourceAdvisor)即可实现此功能
// *
// * @return
// */
// @Bean
// @DependsOn({"lifecycleBeanPostProcessor"})
// public DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator() {
// DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
// advisorAutoProxyCreator.setProxyTargetClass(true);
// return advisorAutoProxyCreator;
// }
/**
* 开启Shiro的注解(@RequiresRoles,@RequiresPermissions),需借助SpringAOP扫描使用Shiro注解的类,并在必要时进行安全逻辑验证
* 配置以下两个bean(DefaultAdvisorAutoProxyCreator(可选)和AuthorizationAttributeSourceAdvisor)即可实现此功能
*
* @return
*/
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor() {
AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
@ -219,7 +202,7 @@ public class ShiroConfig implements EnvironmentAware {
return authorizationAttributeSourceAdvisor;
}
public FormAuthenticationFilter hpeisFormAuthenticationFilter(){
public FormAuthenticationFilter baseFormAuthenticationFilter(){
FormAuthenticationFilter formAuthenticationFilter = new ShiroLoginFilter();
return formAuthenticationFilter;
}
@ -227,22 +210,9 @@ public class ShiroConfig implements EnvironmentAware {
@Bean
public FilterRegistrationBean someFilterRegistration() {
FilterRegistrationBean registration = new FilterRegistrationBean();
FormAuthenticationFilter hpeisFormAuthenticationFilter = new ShiroLoginFilter();
registration.setFilter(hpeisFormAuthenticationFilter);
FormAuthenticationFilter baseFormAuthenticationFilter = new ShiroLoginFilter();
registration.setFilter(baseFormAuthenticationFilter);
registration.setEnabled(false);
return registration;
}
/**
* 注册全局异常处理
*
* @return
*/
/*@Bean(name = "exceptionHandler")
public HandlerExceptionResolver handlerExceptionResolver() {
return new HpeisExceptionHandler();
}*/
}

View File

@ -10,6 +10,9 @@ import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* @author ronger
*/
@Configuration
@EnableSwagger2
public class Swagger2Configuration {
@ -19,7 +22,7 @@ public class Swagger2Configuration {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.rymcu.vertical.web.api"))//这是注意的代码
.apis(RequestHandlerSelectors.basePackage("com.rymcu.vertical.web.api"))
.paths(PathSelectors.any())
.build();
}

View File

@ -7,7 +7,7 @@ import com.rymcu.vertical.jwt.model.TokenModel;
import com.rymcu.vertical.jwt.service.TokenManager;
import com.rymcu.vertical.jwt.util.oConvertUtils;
import com.rymcu.vertical.web.api.exception.ErrorCode;
import com.rymcu.vertical.web.api.exception.MallApiException;
import com.rymcu.vertical.web.api.exception.BaseApiException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureException;
@ -44,19 +44,19 @@ public class RestAuthTokenInterceptor implements HandlerInterceptor {
authHeader = request.getHeader(JwtConstants.UPLOAD_TOKEN);
}
if (StringUtils.isBlank(authHeader)) {
throw new MallApiException(ErrorCode.UNAUTHORIZED);
throw new BaseApiException(ErrorCode.UNAUTHORIZED);
}
// 验证token
Claims claims = null;
try {
claims = Jwts.parser().setSigningKey(JwtConstants.JWT_SECRET).parseClaimsJws(authHeader).getBody();
}catch (final SignatureException e) {
throw new MallApiException(ErrorCode.INVALID_TOKEN);
throw new BaseApiException(ErrorCode.INVALID_TOKEN);
}
Object username = claims.getId();
if (oConvertUtils.isEmpty(username)) {
throw new MallApiException(ErrorCode.INVALID_TOKEN);
throw new BaseApiException(ErrorCode.INVALID_TOKEN);
}
TokenModel model = manager.getToken(authHeader,username.toString());
if (manager.checkToken(model)) {
@ -66,7 +66,7 @@ public class RestAuthTokenInterceptor implements HandlerInterceptor {
request.setAttribute(JwtConstants.CURRENT_USER_NAME, model.getUsername());
return true;
} else {
throw new MallApiException(ErrorCode.TOKEN_);
throw new BaseApiException(ErrorCode.TOKEN_);
}
}

View File

@ -3,7 +3,7 @@ package com.rymcu.vertical.service;
import com.rymcu.vertical.core.service.Service;
import com.rymcu.vertical.dto.ArticleDTO;
import com.rymcu.vertical.entity.Article;
import com.rymcu.vertical.web.api.exception.MallApiException;
import com.rymcu.vertical.web.api.exception.BaseApiException;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
@ -21,5 +21,5 @@ public interface ArticleService extends Service<Article> {
List<ArticleDTO> findUserArticlesByIdUser(Integer idUser);
Map postArticle(ArticleDTO article, HttpServletRequest request) throws UnsupportedEncodingException, MallApiException;
Map postArticle(ArticleDTO article, HttpServletRequest request) throws UnsupportedEncodingException, BaseApiException;
}

View File

@ -3,11 +3,11 @@ package com.rymcu.vertical.service;
import com.rymcu.vertical.core.service.Service;
import com.rymcu.vertical.entity.Article;
import com.rymcu.vertical.entity.Tag;
import com.rymcu.vertical.web.api.exception.MallApiException;
import com.rymcu.vertical.web.api.exception.BaseApiException;
import java.io.UnsupportedEncodingException;
public interface TagService extends Service<Tag> {
void saveTagArticle(Article article) throws UnsupportedEncodingException, MallApiException;
void saveTagArticle(Article article) throws UnsupportedEncodingException, BaseApiException;
}

View File

@ -13,7 +13,7 @@ import com.rymcu.vertical.service.UserService;
import com.rymcu.vertical.util.Html2TextUtil;
import com.rymcu.vertical.util.UserUtils;
import com.rymcu.vertical.util.Utils;
import com.rymcu.vertical.web.api.exception.MallApiException;
import com.rymcu.vertical.web.api.exception.BaseApiException;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@ -79,7 +79,7 @@ public class ArticleServiceImpl extends AbstractService<Article> implements Arti
@Override
@Transactional(rollbackFor = Exception.class)
public Map postArticle(ArticleDTO article, HttpServletRequest request) throws UnsupportedEncodingException, MallApiException {
public Map postArticle(ArticleDTO article, HttpServletRequest request) throws UnsupportedEncodingException, BaseApiException {
Map map = new HashMap(1);
if(StringUtils.isBlank(article.getArticleTitle())){
map.put("message","标题不能为空!");

View File

@ -7,7 +7,7 @@ import com.rymcu.vertical.entity.User;
import com.rymcu.vertical.mapper.TagMapper;
import com.rymcu.vertical.service.TagService;
import com.rymcu.vertical.util.UserUtils;
import com.rymcu.vertical.web.api.exception.MallApiException;
import com.rymcu.vertical.web.api.exception.BaseApiException;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@ -25,7 +25,7 @@ public class TagServiceImpl extends AbstractService<Tag> implements TagService {
@Override
@Transactional
public void saveTagArticle(Article article) throws UnsupportedEncodingException, MallApiException {
public void saveTagArticle(Article article) throws UnsupportedEncodingException, BaseApiException {
User user = UserUtils.getWxCurrentUser();
String articleTags = article.getArticleTags();
if(StringUtils.isNotBlank(articleTags)){

View File

@ -7,7 +7,7 @@ import com.rymcu.vertical.jwt.model.TokenModel;
import com.rymcu.vertical.jwt.service.TokenManager;
import com.rymcu.vertical.mapper.UserMapper;
import com.rymcu.vertical.web.api.exception.ErrorCode;
import com.rymcu.vertical.web.api.exception.MallApiException;
import com.rymcu.vertical.web.api.exception.BaseApiException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureException;
@ -22,7 +22,7 @@ public class UserUtils {
* 通过token获取当前用户的信息
* @return
*/
public static User getWxCurrentUser() throws MallApiException {
public static User getWxCurrentUser() throws BaseApiException {
String authHeader = ContextHolderUtils.getRequest().getHeader(JwtConstants.AUTHORIZATION);
if (authHeader == null) {
return null;
@ -32,7 +32,7 @@ public class UserUtils {
try {
claims = Jwts.parser().setSigningKey(JwtConstants.JWT_SECRET).parseClaimsJws(authHeader).getBody();
} catch (final SignatureException e) {
throw new MallApiException(ErrorCode.UNAUTHORIZED);
throw new BaseApiException(ErrorCode.UNAUTHORIZED);
}
Object account = claims.getId();
if (!oConvertUtils.isEmpty(account)) {
@ -41,7 +41,7 @@ public class UserUtils {
return userMapper.findByAccount(account.toString());
}
} else {
throw new MallApiException(ErrorCode.UNAUTHORIZED);
throw new BaseApiException(ErrorCode.UNAUTHORIZED);
}
return null;
}

View File

@ -4,7 +4,7 @@ import com.rymcu.vertical.core.result.GlobalResult;
import com.rymcu.vertical.core.result.GlobalResultGenerator;
import com.rymcu.vertical.dto.ArticleDTO;
import com.rymcu.vertical.service.ArticleService;
import com.rymcu.vertical.web.api.exception.MallApiException;
import com.rymcu.vertical.web.api.exception.BaseApiException;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
@ -20,13 +20,13 @@ public class ArticleController {
private ArticleService articleService;
@PostMapping("/post")
public GlobalResult postArticle(@RequestBody ArticleDTO article, HttpServletRequest request) throws MallApiException, UnsupportedEncodingException {
public GlobalResult postArticle(@RequestBody ArticleDTO article, HttpServletRequest request) throws BaseApiException, UnsupportedEncodingException {
Map map = articleService.postArticle(article,request);
return GlobalResultGenerator.genSuccessResult(map);
}
@PutMapping("/post")
public GlobalResult updateArticle(@RequestBody ArticleDTO article, HttpServletRequest request) throws MallApiException, UnsupportedEncodingException {
public GlobalResult updateArticle(@RequestBody ArticleDTO article, HttpServletRequest request) throws BaseApiException, UnsupportedEncodingException {
Map map = articleService.postArticle(article,request);
return GlobalResultGenerator.genSuccessResult(map);
}

View File

@ -8,13 +8,12 @@ import com.rymcu.vertical.util.FileUtils;
import com.rymcu.vertical.util.UserUtils;
import com.rymcu.vertical.util.Utils;
import com.rymcu.vertical.web.api.exception.ErrorCode;
import com.rymcu.vertical.web.api.exception.MallApiException;
import com.rymcu.vertical.web.api.exception.BaseApiException;
import org.apache.commons.lang.StringUtils;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
@ -124,10 +123,10 @@ public class UploadController {
}
@GetMapping("/token")
public GlobalResult uploadToken(HttpServletRequest request) throws MallApiException {
public GlobalResult uploadToken(HttpServletRequest request) throws BaseApiException {
String authHeader = request.getHeader(JwtConstants.AUTHORIZATION);
if(StringUtils.isBlank(authHeader)){
throw new MallApiException(ErrorCode.UNAUTHORIZED);
throw new BaseApiException(ErrorCode.UNAUTHORIZED);
}
TUser tUser = UserUtils.getTUser(authHeader);
Map map = new HashMap(2);

View File

@ -3,12 +3,12 @@ package com.rymcu.vertical.web.api.exception;
/**
* 服务业务异常如 账号或密码错误 该异常只做INFO级别的日志记录 @see WebMvcConfigurer
*/
public class MallApiException extends Exception {
public class BaseApiException extends Exception {
private int code;
private String message;
public MallApiException(ErrorCode errorCode) {
public BaseApiException(ErrorCode errorCode) {
super(errorCode.getMessage());
this.code = errorCode.getCode();
this.message = errorCode.getMessage();

View File

@ -1,6 +1,6 @@
package com.rymcu.vertical.web.api.exception;
import com.rymcu.vertical.config.HpeisExceptionHandler;
import com.rymcu.vertical.config.BaseExceptionHandler;
import com.rymcu.vertical.core.result.GlobalResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -12,17 +12,17 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@ControllerAdvice(basePackages = {"com.rymcu.vertical.web.api", "com.rymcu.vertical.jwt"} )
public class MallApiExceptionHandler {
public class BaseApiExceptionHandler {
private final Logger logger = LoggerFactory.getLogger(HpeisExceptionHandler.class);
private final Logger logger = LoggerFactory.getLogger(BaseExceptionHandler.class);
@ExceptionHandler(MallApiException.class)
@ExceptionHandler(BaseApiException.class)
@ResponseBody
public GlobalResult handlerException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
logger.error(ex.getMessage());
GlobalResult result = new GlobalResult();
if (ex instanceof MallApiException) {
result.setCode(((MallApiException) ex).getCode());
if (ex instanceof BaseApiException) {
result.setCode(((BaseApiException) ex).getCode());
result.setMessage(ex.getMessage());
} /*else if (ex instanceof Exception) {
result.setCode(ErrorCode.INTERNAL_SERVER_ERROR.getCode());