添加redis、swagger、统一异常处理

This commit is contained in:
fengjing
2017-10-11 17:44:13 +08:00
parent e2cea0422c
commit 7b047820f1
9 changed files with 248 additions and 35 deletions
@@ -0,0 +1,40 @@
package net.ameizi.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
@Configuration
public class RedisConfig {
@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.password}")
private String password;
@Value("${spring.redis.port}")
private Integer port = 6379;
@Value("${spring.redis.database}")
private Integer database = 0;
@Bean
JedisConnectionFactory jedisConnectionFactory() {
JedisConnectionFactory connectionFactory = new JedisConnectionFactory();
connectionFactory.setHostName(host);
connectionFactory.setPassword(password);
connectionFactory.setPort(port);
connectionFactory.setDatabase(database);
return connectionFactory;
}
@Bean("redisTemplate")
public RedisTemplate<String, Object> redisTemplate() {
RedisTemplate redisTemplate = new RedisTemplate();
redisTemplate.setConnectionFactory(jedisConnectionFactory());
return redisTemplate;
}
}
@@ -65,12 +65,18 @@ public class ShiroConfig {
// 允许用户匿名访问/login(登录接口)
filterChainDefinitionMap.put("/login", "anon");
// 验证码允许匿名访问
filterChainDefinitionMap.put("/captcha*","anon");
filterChainDefinitionMap.put("/captcha","anon");
filterChainDefinitionMap.put("/api-docs","anon");
filterChainDefinitionMap.put("/v2/api-docs","anon");
filterChainDefinitionMap.put("/swagger-ui.html","anon");
filterChainDefinitionMap.put("/webjars/**","anon");
filterChainDefinitionMap.put("/swagger-resources/**","anon");
filterChainDefinitionMap.put("/**", "jwt");
// filterChainDefinitionMap.put("/**","anon");
// filterChainDefinitionMap.put("/**","anon");
shiroFilter.setFilterChainDefinitionMap(filterChainDefinitionMap);
@@ -0,0 +1,119 @@
//package net.ameizi.controller;
//
//import com.google.common.collect.Maps;
//import net.ameizi.utils.HttpStatus;
//import org.apache.shiro.authz.AuthorizationException;
//import org.apache.shiro.authz.UnauthorizedException;
//import org.springframework.http.MediaType;
//import org.springframework.http.ResponseEntity;
//import org.springframework.web.bind.annotation.ExceptionHandler;
//
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//import java.util.HashMap;
//import java.util.List;
//import java.util.Map;
//
//public class BaseController {
//
// /** 设置成功响应 */
// protected ResponseEntity<Object> success(Object data) {
// return responseEntity(HttpStatus.OK,data,HttpStatus.OK.msg());
// }
//
// protected ResponseEntity<Object> success(String msg) {
// return responseEntity(HttpStatus.OK,null,msg);
// }
//
// protected ResponseEntity<Object> success() {
// return responseEntity(HttpStatus.OK,null,HttpStatus.OK.msg());
// }
//
// protected ResponseEntity<Object> success(Object data,String msg) {
// return responseEntity(HttpStatus.OK,data,msg);
// }
//
// /** 设置失败响应 */
// protected ResponseEntity<Object> error(Object data) {
// return responseEntity(HttpStatus.BAD_REQUEST,data,HttpStatus.BAD_REQUEST.msg());
// }
//
// protected ResponseEntity<Object> error(String msg) {
// return responseEntity(HttpStatus.BAD_REQUEST,null,msg);
// }
//
// protected ResponseEntity<Object> error() {
// return responseEntity(HttpStatus.BAD_REQUEST,null,HttpStatus.BAD_REQUEST.msg());
// }
//
// protected ResponseEntity<Object> error(Object data,String msg) {
// return responseEntity(HttpStatus.BAD_REQUEST,data,msg);
// }
//
// /** 设置响应代码 */
// protected ResponseEntity<Object> responseEntity(HttpStatus code, Object data, String msg) {
// Map<String,Object> map = new HashMap<>();
// if (data != null) {
// if (data instanceof PageInfo) {
// PageInfo<?> page = (PageInfo<?>) data;
// map.put("data", page.getList());
// map.put("current", page.getPageNum());
// map.put("size", page.getSize());
// map.put("pages", page.getPages());
// map.put("total", page.getTotal());
// } else if (data instanceof List<?>) {
// map.put("data", data);
// } else {
// map.put("data", data);
// }
// }
// map.put("code", code.value());
// map.put("msg", msg);
// map.put("timestamp", System.currentTimeMillis());
// return ResponseEntity.ok()
// .header("Access-Control-Allow-Origin","*")
// .contentType(MediaType.APPLICATION_JSON)
// .body(map);
// }
//
// /** 异常处理 */
// @ExceptionHandler(Exception.class)
// public void exceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception ex)
// throws Exception {
// Map<String,Object> map = Maps.newHashMap();
// int status;
// // 方法级别shiro权限校验失败时异常信息处理
// if (ex instanceof AuthorizationException){
// status = HttpStatus.FORBIDDEN.value();
// map.put("code", HttpStatus.FORBIDDEN.value());
// map.put("msg", HttpStatus.FORBIDDEN.msg());
// } else if (ex instanceof UnauthorizedException) {
// status = HttpStatus.FORBIDDEN.value();
// map.put("code", HttpStatus.FORBIDDEN.value());
// map.put("msg", HttpStatus.FORBIDDEN.msg());
// } else if(ex instanceof LoginException){
// status = HttpStatus.FORBIDDEN.value();
// map.put("code", HttpStatus.LOGIN_FAIL.value());
// map.put("msg", ex.getMessage());
// } else if(ex instanceof UploadException){
// status = HttpStatus.INTERNAL_SERVER_ERROR.value();
// map.put("code", HttpStatus.JP_UPLOAD_FAIL.value());
// map.put("msg", ex.getMessage());
// } else if(ex instanceof TokenParserException){
// status = HttpStatus.FORBIDDEN.value();
// map.put("code", HttpStatus.TOKEN_PARSER_FAIL.value());
// map.put("msg",ex.getMessage());
// } else {
// status = HttpStatus.INTERNAL_SERVER_ERROR.value();
// map.put("code", HttpStatus.INTERNAL_SERVER_ERROR.value());
// map.put("msg", HttpStatus.INTERNAL_SERVER_ERROR.msg());
// }
// ex.printStackTrace();
// response.setContentType("application/json;charset=UTF-8");
// response.setHeader("Access-Control-Allow-Origin","*");
// response.setStatus(status);
// map.put("timestamp", System.currentTimeMillis());
// response.getOutputStream().write(JSONUtils.toJSONString(map).getBytes());
// }
//
//}
@@ -3,6 +3,7 @@ package net.ameizi.controller;
import com.alibaba.fastjson.JSONObject;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.common.collect.ImmutableMap;
import net.ameizi.shiro.LoginUser;
import net.ameizi.shiro.jwt.JwtToken;
import net.ameizi.utils.TokenUtil;
import org.apache.shiro.SecurityUtils;
@@ -53,11 +54,11 @@ public class LoginController {
}
@PostMapping("/login")
public Object login(HttpServletRequest request, HttpServletResponse response, Device device) throws IOException {
public Object login(@RequestBody LoginUser loginUser, HttpServletRequest request, HttpServletResponse response, Device device) throws IOException {
JSONObject jsonObject = new JSONObject();
String username = request.getParameter("username");
String password = request.getParameter("password");
String username = loginUser.getUsername();
String password = loginUser.getPassword();
// 验证用户名密码成功后生成token
String token = tokenUtil.generateToken(username, device);
@@ -97,14 +98,13 @@ public class LoginController {
response.flushBuffer();
jsonObject.put("code",200);
jsonObject.put("msg","认证成功!");
jsonObject.put("msg","success");
jsonObject.put("token",token);
jsonObject.put("timestamp", Calendar.getInstance().getTimeInMillis());
return jsonObject;
}else{
jsonObject.put("code",403);
jsonObject.put("msg","认证失败");
jsonObject.put("token",null);
jsonObject.put("msg","error");
jsonObject.put("timestamp", Calendar.getInstance().getTimeInMillis());
return jsonObject;
}
@@ -165,7 +165,7 @@ public class LoginController {
* @param token
* @return
*/
@RequestMapping("/token/refresh")
@PostMapping("/token/refresh")
public Object refreshToken(@CookieValue(value = "token") String token) {
JSONObject jsonObject = new JSONObject();
String newToken = tokenUtil.refreshToken(token);
@@ -0,0 +1,17 @@
package net.ameizi.shiro;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class LoginUser {
private String username;
private String password;
private String vcode;
String vcodeKey;
}
@@ -11,10 +11,10 @@ import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
public class JwtAuthenticationFilter extends AuthenticatingFilter {
@@ -30,12 +30,15 @@ public class JwtAuthenticationFilter extends AuthenticatingFilter {
token = httpRequest.getParameter(TOKEN);
// 还是获取不到再从Cookie中拿
if(StringUtils.isEmpty(token)){
token = Arrays.stream(httpRequest.getCookies())
.filter(ck -> "token".equals(ck.getName()))
.limit(1)
.findFirst()
.get()
.getValue();
Cookie[] cookies = httpRequest.getCookies();
if(cookies != null){
for (Cookie cookie : cookies) {
if(TOKEN.equals(cookie.getName())){
token = cookie.getValue();
break;
}
}
}
}
}
return JwtToken.builder()
@@ -0,0 +1,28 @@
package net.ameizi.utils;
public enum HttpStatus {
OK(200, "请求成功"),
BAD_REQUEST(400, "请求出错"),
UNAUTHORIZED(401, "没有登录"),
FORBIDDEN(403, "没有权限"),
NOT_FOUND(404, "找不到页面"),
INTERNAL_SERVER_ERROR(500, "服务器出错");
private final int value;
private final String msg;
HttpStatus(int value, String msg) {
this.value = value;
this.msg = msg;
}
public int value() {
return value;
}
public String msg() {
return msg;
}
}
-18
View File
@@ -1,18 +0,0 @@
#spring.datasource.url = jdbc:mysql://localhost:3306/shiro
#spring.datasource.username = root
#spring.datasource.password = root
#spring.datasource.driverClassName = com.mysql.jdbc.Driver
#spring.datasource.max-active=20
#spring.datasource.max-idle=8
#spring.datasource.min-idle=8
#spring.datasource.initial-size=10
swagger.host = localhost:8080
#jwt.header= Authorization
jwt.token.secret= mySecret
jwt.token.expiration= 604800
spring.redis.host=localhost
spring.redis.database=0
spring.redis.port=6379
+19 -1
View File
@@ -6,4 +6,22 @@ spring:
date-format: yyyy-MM-dd HH:mm:ss
joda-date-time-format: yyyy-MM-dd HH:mm:ss
default-property-inclusion: non_null
time-zone: GMT+8
time-zone: GMT+8
redis:
host: localhost
port: 6379
database: 0
password: jpdbb1387lipushdatabseredis
swagger:
host: localhost:8080
jwt:
# header: Authorization
token:
secret: mySecret
# 7天
# expiration: 604800
# 一天
expiration: 86400