From 7b047820f10ec636bdadde4c4a700265f8197fa6 Mon Sep 17 00:00:00 2001 From: fengjing Date: Wed, 11 Oct 2017 17:44:13 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0redis=E3=80=81swagger?= =?UTF-8?q?=E3=80=81=E7=BB=9F=E4=B8=80=E5=BC=82=E5=B8=B8=E5=A4=84=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/net/ameizi/config/RedisConfig.java | 40 ++++++ .../java/net/ameizi/config/ShiroConfig.java | 10 +- .../net/ameizi/controller/BaseController.java | 119 ++++++++++++++++++ .../ameizi/controller/LoginController.java | 14 +-- src/main/java/net/ameizi/shiro/LoginUser.java | 17 +++ .../shiro/filter/JwtAuthenticationFilter.java | 17 +-- .../java/net/ameizi/utils/HttpStatus.java | 28 +++++ src/main/resources/application.properties | 18 --- src/main/resources/application.yml | 20 ++- 9 files changed, 248 insertions(+), 35 deletions(-) create mode 100644 src/main/java/net/ameizi/config/RedisConfig.java create mode 100644 src/main/java/net/ameizi/controller/BaseController.java create mode 100644 src/main/java/net/ameizi/shiro/LoginUser.java create mode 100644 src/main/java/net/ameizi/utils/HttpStatus.java delete mode 100644 src/main/resources/application.properties diff --git a/src/main/java/net/ameizi/config/RedisConfig.java b/src/main/java/net/ameizi/config/RedisConfig.java new file mode 100644 index 0000000..33c6d9f --- /dev/null +++ b/src/main/java/net/ameizi/config/RedisConfig.java @@ -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 redisTemplate() { + RedisTemplate redisTemplate = new RedisTemplate(); + redisTemplate.setConnectionFactory(jedisConnectionFactory()); + return redisTemplate; + } +} diff --git a/src/main/java/net/ameizi/config/ShiroConfig.java b/src/main/java/net/ameizi/config/ShiroConfig.java index 5201b98..94b7239 100644 --- a/src/main/java/net/ameizi/config/ShiroConfig.java +++ b/src/main/java/net/ameizi/config/ShiroConfig.java @@ -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); diff --git a/src/main/java/net/ameizi/controller/BaseController.java b/src/main/java/net/ameizi/controller/BaseController.java new file mode 100644 index 0000000..5558b35 --- /dev/null +++ b/src/main/java/net/ameizi/controller/BaseController.java @@ -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 success(Object data) { +// return responseEntity(HttpStatus.OK,data,HttpStatus.OK.msg()); +// } +// +// protected ResponseEntity success(String msg) { +// return responseEntity(HttpStatus.OK,null,msg); +// } +// +// protected ResponseEntity success() { +// return responseEntity(HttpStatus.OK,null,HttpStatus.OK.msg()); +// } +// +// protected ResponseEntity success(Object data,String msg) { +// return responseEntity(HttpStatus.OK,data,msg); +// } +// +// /** 设置失败响应 */ +// protected ResponseEntity error(Object data) { +// return responseEntity(HttpStatus.BAD_REQUEST,data,HttpStatus.BAD_REQUEST.msg()); +// } +// +// protected ResponseEntity error(String msg) { +// return responseEntity(HttpStatus.BAD_REQUEST,null,msg); +// } +// +// protected ResponseEntity error() { +// return responseEntity(HttpStatus.BAD_REQUEST,null,HttpStatus.BAD_REQUEST.msg()); +// } +// +// protected ResponseEntity error(Object data,String msg) { +// return responseEntity(HttpStatus.BAD_REQUEST,data,msg); +// } +// +// /** 设置响应代码 */ +// protected ResponseEntity responseEntity(HttpStatus code, Object data, String msg) { +// Map 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 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()); +// } +// +//} diff --git a/src/main/java/net/ameizi/controller/LoginController.java b/src/main/java/net/ameizi/controller/LoginController.java index e62fdaf..ca894aa 100644 --- a/src/main/java/net/ameizi/controller/LoginController.java +++ b/src/main/java/net/ameizi/controller/LoginController.java @@ -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); diff --git a/src/main/java/net/ameizi/shiro/LoginUser.java b/src/main/java/net/ameizi/shiro/LoginUser.java new file mode 100644 index 0000000..c8c8404 --- /dev/null +++ b/src/main/java/net/ameizi/shiro/LoginUser.java @@ -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; +} diff --git a/src/main/java/net/ameizi/shiro/filter/JwtAuthenticationFilter.java b/src/main/java/net/ameizi/shiro/filter/JwtAuthenticationFilter.java index 208fd3e..751d106 100644 --- a/src/main/java/net/ameizi/shiro/filter/JwtAuthenticationFilter.java +++ b/src/main/java/net/ameizi/shiro/filter/JwtAuthenticationFilter.java @@ -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() diff --git a/src/main/java/net/ameizi/utils/HttpStatus.java b/src/main/java/net/ameizi/utils/HttpStatus.java new file mode 100644 index 0000000..c4f300a --- /dev/null +++ b/src/main/java/net/ameizi/utils/HttpStatus.java @@ -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; + } +} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties deleted file mode 100644 index afcd47c..0000000 --- a/src/main/resources/application.properties +++ /dev/null @@ -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 \ No newline at end of file diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 91a080a..94a08dd 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -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 \ No newline at end of file + 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 \ No newline at end of file