Authored by fangyeqing

ADD:add SignCheckAspect

package com.xkl.authorization.annotation;
import java.lang.annotation.*;
/**
* Created by win7 on 2016/11/20.
* 检查不同平台的签名
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Sign {
}
... ...
package com.xkl.authorization.aspect;
import com.xkl.repository.XklInterKeyRespository;
import com.xkl.security.SecurityTool;
import com.xkl.tools.UtilTools;
import lombok.extern.apachecommons.CommonsLog;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import java.nio.file.AccessDeniedException;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
* Created by win7 on 2016/11/20.
*加密算法:
* t: 北京时间距离1970年1月1日的秒数
* key:(平台对应的key,此值喜开路管理员授予)
* str:业务参数数组,按参数名递增排序排列拼接,例如用户登陆接口,coid+password+username
* sign=md5(str+t+key),32位小写md5
* 需要验证:
* sign:是否正确
* t:是否过期,客户端与服务器时间必须为±300s以内,否则时间验证过期。
*/
@Service
@Aspect
@CommonsLog
public class SignAspect {
@Autowired
private XklInterKeyRespository xklInterKeyRespository;
/**
* 由接口传过来的type获取xkl_inter_key表中的key
* @param type
* @return
*/
private String getKeyByType(int type){
int id = 0;
if(type == 1)
id = 1;
else
id = 2;
return xklInterKeyRespository.findById(id).getKey();
}
/**
* 定义切点,定位到@Sign注解的地方
*/
@Pointcut("@annotation(com.xkl.authorization.annotation.Sign)")
public void signPointCut() {
}
@Before(value="signPointCut()")
public void beforeSign(JoinPoint joinPoint) throws Exception {
Object[] args = joinPoint.getArgs();
//Controller中所有方法的参数,前两个分别为:Request,Response
HttpServletRequest request = (HttpServletRequest) args[0];
// HttpServletResponse response = (HttpServletResponse)args[1];
String sign = request.getParameter("sign");
long t = UtilTools._long(request.getParameter("t"));
int type = UtilTools._int(request.getParameter("type"));
/**
* str为
* sign=md5(str+t+key)
*/
Map<String,String[]> map=request.getParameterMap();
List<String> list=Collections.list(request.getParameterNames());
Collections.sort(list);
String str="";
for(String para:list){
if(!para.equals("sign")&&!para.equals("t")&&!para.equals("type"))
str += map.get(para)[0];
}
String key = getKeyByType(type);
long t1= UtilTools.get10Second();
String sign1= SecurityTool.encode("MD5",str+t1+key);
/**
* 比较sign和过期时间
*/
if(sign1.equals(sign)&&Math.abs(t1-t)<300){
}else{
throw new Exception("您无权操作!");
}
}
}
... ...
... ... @@ -21,6 +21,8 @@ import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
/**
* 获取和删除token的请求地址,在Restful设计中其实就对应着登录和退出登录的资源映射
*/
... ... @@ -34,9 +36,11 @@ public class TokenController {
@Autowired
private ITokenManager tokenManager;
//@Sign
@RequestMapping(method = RequestMethod.POST)
@ApiOperation(value = "登录")
public ResponseEntity<ResultModel> login(@RequestParam String username, @RequestParam String password) {
public ResponseEntity<ResultModel> login(HttpServletRequest request,@RequestParam String username, @RequestParam String password,
@RequestParam String sign,@RequestParam long t,@RequestParam int type) {
Assert.notNull(username, "username can not be empty");
Assert.notNull(password, "password can not be empty");
... ... @@ -56,8 +60,10 @@ public class TokenController {
return new ResponseEntity<>(ResultModel.ok(model), HttpStatus.OK);
}
@RequestMapping(method = RequestMethod.DELETE)
@Authorization
//@Sign
@RequestMapping(method = RequestMethod.DELETE)
@ApiOperation(value = "退出登录")
@ApiImplicitParams({
@ApiImplicitParam(name = "authorization", value = "请输入登录返回信息:userId_tokens", required = true, dataType = "string", paramType = "header"),
... ...
... ... @@ -2,6 +2,7 @@ package com.xkl.controller;
import com.xkl.authorization.annotation.Authorization;
import com.xkl.authorization.annotation.CurrentUser;
import com.xkl.authorization.annotation.Sign;
import com.xkl.authorization.manager.ITokenManager;
import com.xkl.config.ResultStatus;
import com.xkl.domain.User;
... ... @@ -21,6 +22,8 @@ import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
/**
* Created by win7 on 2016/10/19.
*/
... ... @@ -33,9 +36,11 @@ public class UserInfoController {
private ITokenManager tokenManager;
@AntiXSS
//@Sign
@RequestMapping(method = RequestMethod.POST)
@ApiOperation(value = "注册")
public ResponseEntity<ResultModel> register(@RequestParam String username, @RequestParam String password) {
public ResponseEntity<ResultModel> register(HttpServletRequest request,@RequestParam String username, @RequestParam String password,
@RequestParam String sign,@RequestParam long t,@RequestParam int type) {
Assert.notNull(username, "username can not be empty");
Assert.notNull(password, "password can not be empty");
... ... @@ -56,14 +61,17 @@ public class UserInfoController {
return new ResponseEntity<>(ResultModel.ok(), HttpStatus.OK);
}
@RequestMapping(method = RequestMethod.PUT)
@Authorization
@AntiXSS
//@Sign
@RequestMapping(method = RequestMethod.PUT)
@ApiOperation(value = "修改用户密码")
@ApiImplicitParams({
@ApiImplicitParam(name = "authorization", value = "请输入登录返回信息:userId_tokens", required = true, dataType = "string", paramType = "header"),
})
public ResponseEntity<ResultModel> modPassword(@CurrentUser User user,@RequestParam String password) {
public ResponseEntity<ResultModel> modPassword(HttpServletRequest request,@CurrentUser User user,@RequestParam String password,
@RequestParam String sign,@RequestParam long t,@RequestParam int type) {
Assert.notNull(password, "password can not be empty");
String salt= SecurityTool.genSalt();
String pass=SecurityTool.getPassword(user.getUsername(),password,salt);
... ...
package com.xkl.domain;
import lombok.Data;
import javax.persistence.*;
/**
* Created by win7 on 2016/11/20.
*/
@Data
@Entity
@Table(name = "xkl_inter_key", schema = "hanhe_test", catalog = "")
public class XklInterKeyEntity {
@Id
@Column(name = "id")
private int id;
@Basic
@Column(name = "key")
private String key;
@Basic
@Column(name = "status")
private byte status;
@Basic
@Column(name = "note")
private String note;
@Basic
@Column(name = "company_id")
private int companyId;
}
... ...
package com.xkl.domain;
import javax.persistence.*;
import java.io.Serializable;
import java.sql.Date;
/**
* Created by win7 on 2016/11/20.
*/
@Entity
@Table(name = "xkl_member", schema = "hanhe_test", catalog = "")
public class XklMemberEntity {
@Id
@Column(name = "id")
private int id;
@Basic
@Column(name = "name")
private String name;
@Basic
@Column(name = "sex")
private Byte sex;
@Basic
@Column(name = "birth_date")
private Date birthDate;
@Basic
@Column(name = "idcard")
private String idcard;
@Basic
@Column(name = "phone")
private String phone;
@Basic
@Column(name = "register_time")
private String registerTime;
@Basic
@Column(name = "company_id")
private int companyId;
@Basic
@Column(name = "province")
private int province;
@Basic
@Column(name = "city")
private int city;
@Basic
@Column(name = "country")
private int country;
@Basic
@Column(name = "register_by")
private int registerBy;
@Basic
@Column(name = "status")
private Byte status;
}
... ...
package com.xkl.repository;
import com.xkl.domain.User;
import com.xkl.domain.XklInterKeyEntity;
import org.springframework.data.repository.CrudRepository;
/**
* Created by win7 on 2016/11/20.
*/
public interface XklInterKeyRespository extends CrudRepository<XklInterKeyEntity, Long> {
public XklInterKeyEntity findById(int companyId);
}
... ...
package com.xkl.tools;
import org.joda.time.DateTime;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
/**
* Created by win7 on 2016/11/20.
*/
public class UtilTools {
/**
* support time format yyyy-MM-dd'T'HH:mm:ss.SSS
*
* @param timestamp
* @return
* @throws Exception
*/
public static int getTime(String timestamp) throws Exception {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.CHINA);
Date time = format.parse(timestamp);
SimpleDateFormat dayFormat = new SimpleDateFormat("yyyyMMdd");
return Integer.parseInt(dayFormat.format(time));
}
public static Timestamp getTimestamp(String timestamp) throws Exception {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.CHINA);
Date time = format.parse(timestamp);
return new Timestamp(time.getTime());
}
public static DateTime getDateTime(String timestamp) throws Exception {
SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHH");
Date time = format.parse(timestamp);
return new DateTime(time.getTime());
}
public static int getDay(Timestamp timestamp) {
SimpleDateFormat dayFormat = new SimpleDateFormat("yyyyMMdd");
return Integer.parseInt(dayFormat.format(new Date(timestamp.getTime())));
}
public static int getHour(Timestamp timestamp) {
SimpleDateFormat dayFormat = new SimpleDateFormat("yyyyMMddHH");
return Integer.parseInt(dayFormat.format(new Date(timestamp.getTime())));
}
public static long get13Second(){
Calendar c = Calendar.getInstance();//可以对每个时间域单独修改
long a=c.getTimeInMillis();
return a;
}
public static long get10Second(){
Calendar c = Calendar.getInstance();//可以对每个时间域单独修改
long a=c.getTimeInMillis()/1000;
return a;
}
public static long _long(String value) {
if (value == null || "null".equals(value)) {
return 0;
}
try {
return Long.parseLong(value.toString());
} catch (Exception e) {
return 0;
}
}
public static long _long(Object value) {
if (value == null || "null".equals(value)) {
return 0;
}
try {
return Long.parseLong(value.toString());
} catch (Exception e) {
return 0;
}
}
public static int _int(String value) {
if (value == null || "null".equals(value)) {
return 0;
}
try {
return Integer.parseInt(value.toString());
} catch (Exception e) {
return 0;
}
}
public static Double _double(String value) {
if (value == null || "null".equals(value)) {
return 0.0;
}
try {
return Double.parseDouble(value.toString());
} catch (Exception e) {
return 0.0;
}
}
public static String _string(Object object) {
if (object == null || "null".equals(object)) {
return "";
}
return object.toString();
}
}
\ No newline at end of file
... ...