FastChar-Security是FastChar框架的安全验证插件,主要用来配置api接口安全验证,支持的验证方式有:sign签名验证和token验证,可在main方法中,快速生成javascript、android和ios的验证代码,提高api的安全性。使用步骤如下:
前提:开启了缓存处理!【重要】
1、下载并引用FastChar-Security到项目中。或通maven引用如下代码:
<dependency>
<groupId>com.fastchar</groupId>
<artifactId>fastchar-security</artifactId>
<version>1.0</version><!--具体版本请前往maven中心查看 https://mvnrepository.com/artifact/com.fastchar/fastchar-security -->
</dependency>
2.1、配置安全验证的模式之签名验证模式
@Override
public void onInit(FastEngine engine) throws Exception { /**省略其他配置**/
engine.getConfig(FastSecurityConfig.class)//获取安全验证插件的配置类
.setSecurityModule(FastSecurityConfig.MD5_PARAMS_SIGN) //此处配置了sign签名模式验证,并配置了验证签名的key
.setMd5Key("41e5bc8d1b312c276d9ca650cf8e1ffb");
}
2.2、配置安全验证的模式之RSA密钥加密验证方式【推荐】
//接口安全配置
engine.getConfig(FastSecurityConfig.class)
.excludeRemote("localhost", "192.168.0.7")//可以排除指定ip地址,免除安全验证,一般用作调试使用
.setSecurityModule(FastSecurityConfig.RSA_HEADER_TOKEN)//配置rsa密钥方式
.setRsaPrivateKeyPkcs8("rsa_private_pkcs8.pem") //配置rsa加密的pkcs8格式的私钥文件,注意此文件必须在class目录下,或开发者也可以直接配置密钥内容;
.setRsaPassword("94fed7e96933c5642fd5421d1d582ae2"); //需要加密的二级密钥,一般使用MD5生成一个唯一字符即可!
3、使用注解或拦截器配置需要安全验证的FastAction或路由方法
通过注解配置:
@AFastSecurity //配置安全验证注解
public void login() {
String email = getParam("email", true);
String password = getParam("password", true);
String code = getParam("loginCode", true);
if (validateCaptcha(code)) {
FcUserEntity user = FcUserEntity.dao().getUser(email, password);
if (user == null) {
responseJson(-2, "登录失败!邮箱或密码错误!");
return;
}
setCookie("userId", user.getId());
responseJson(0, "登录成功!");
} else {
responseJson(-1, "登录失败!验证码错误!");
}
}
//直接注解整个FastAction类 @AFastSecurity
public class UserAction extends FastAction {
@Override
protected String getRoute() {
return "/user";
} }
通过拦截器配置:
@AFastBefore(FastSecurityInterceptor.class) //配置安全验证的拦截器
public void register() {
String email = check("@email:邮箱格式输入错误!").getParam("email", true);
FcUserEntity user = FcUserEntity.dao().getUser(email);
if (user != null) {
responseJson(-2, "注册失败!当前邮箱已被注册!");
}
String password = getParam("password", true);
int code = check("@int:验证码必须为数字类型!").getParamToInt("code", true);
int error = EmailUtils.validateRegisterCode(email, code);
if (error == 0) {
user = new FcUserEntity();
user.set("userEmail", email);
user.set("userPassword", password);
user.set("userNickName", CommonUtils.hideCenter(email));
if (user.save()) {
responseJson(0, "注册成功!");
}
} else {
responseJson(-1, EmailUtils.convertError(error));
}
}
注:
1、安全验证模式:MD5_PARAMS_SIGN
签名验证方式,调用者需要把参数按照ASCII排序后,按照“key=value”以“&”符号拼接接着在拼接“key=值”后在用MD5加密。
2、安全验证模式:RSA_HEADER_TOKEN
请求头token验证方式,调用者需要把密钥进行rsa加密然后设置到请求的头中带到后台做验证。
以上的描述只是简单介绍了验证的基本规则!由于FastChar-Security提供了对应ios、android和js端的签名或token的生成代码,所以开发也不用担心与接口调用者对接问题
在Main方法中生成javascript、android和ios相关的验证代码如下:
public static void main(String[] args) {
FastSecurityAuto.buildMd5();//生成验证模式为sign的代码
FastSecurityAuto.buildRsa();//生成验证模式为token的代码
}
在FastChar-Security中两种验证模式可单独使用也可以组合使用。