网站防篡改设备(篡改常识的系统最新章节)
-
-
类目:知识大全
-
联系人:
-
微信号:
-
Q Q 号:
-
手机号:
-
浏览量:
352
【商户信息】
【货源详情】
什么是Api接口幂等?
简而言之,Api接口幂等可以在有限的时间内限制接口访问请求,限制ip访问的次数,并在没有限制平台访问的情况下获得数据。 一个接口不能重复提交表格,生产并一次性消费。
用户方案:在同一时间重复发送多次请求。
什么是数据篡改?
篡改api接口的数据、脚本文件和接口参数来窃取服务器数据,严重的数据篡改会导致数据库崩溃,程序软件崩溃。
想到这里,你应该知道背景api接口的幂等多重要请求吧。 今天介绍基于非对称加密的后台接口api幂等。
实现思路:jtw认证id签名密钥实现当前时间戳保存期限AES加密算法token。
实现步骤:1,用户注册成功后,生产加密token存储redis。
2、下次登录确认token是否过期。 过期后请再次登录。
3、用户注册有有效期,不需要注册。 (这里是单点登录方式)
代码核心实现类:
import io.jsonwebtoken.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
importorg.spring framework.security.authentic ation.usernamepasswordauthenticationtoken;
importorg.spring framework.security.core.authentic ation;
importorg.spring framework.security.core.granted authority;
importorg.spring framework.security.core.authority.simplegrantedauthority;
importorg.spring framework.security.core.user details.user;
importorg.spring framework.stereotype.com ponent;
importorg.spring framework.util.string utils;
import javax.annotation.post construct;
import javax.servlet.http.http servlet request;
import java.util.*;
import Java.util.stream.collectors;
@Component
公共类jwttokenutils {
publicstaticfinalstringauthorization _ header=' x-token ';
publicstaticfinalstringauthorization _ token=' x-token ';
privatefinalloggerlogger=logger factory.getlogger (jwttokenutils.class;
privatestaticfinalstringauthorities _ key=' auth ';
私有字符串安全密钥; //签名密钥
privatelongtokenvalidityinmilliseconds; //失效日期
privatelongtokenvalidityinmillisecondsforrememberme; //(记住我)失效日期
@PostConstruct
公共void init (
this.secret key=' isoft stone.huwei ';
int secondIn1day=1000 * 60 * 60 * 24;
this.tokenvalidityinmilliseconds=second in1d ay * 2l;
this.tokenvalidityinmillisecondsforrememberme=second in1d ay * 7l;
}
制作Token
publicstringcreatetoken (authenticationauthentication,Boolean rememberMe ) {
string authorities=authentic ation.get authorities (.stream ) )获取用户的权限字符串,如用户、管理员等
.接地授权:3360 get授权(.map ) (.collect ) collectors.joining )、'、');
longnow=(newdate () ) ).getTime ); //获取当前时间戳
日期验证; //保管期限
remember me (if )
validity=new date (now this.tokenvalidityinmilliseconds;
} else {
validity=new date (now this.tokenvalidityinmillisecondsforrememberme;
}
returnsysconst.sys _ company _ head '.' jwts.builder (创建/token令牌
. set subject (authentic ation.getname ) )//为用户设置
. claim(authorities_key,authorities )//添加权限属性
设定. setexpiration(validity ) /失效时间
. sign with (signature algorithm.hs 512,secretKey )//生成签名
.compact (;
}
//获取用户权限
publicauthenticationgetauthentication (string token ) {
logger.info (jwttokenutilsstartgetuserauth );
解析Token的payload
claims claims=jwts.parser (.setsigningkey (secret key ).parseclaimsjws ) token ).getBody );
Collection? extendsgrantedauthorityauthorities=arrays
. stream (claims.get (authorities _ key ).toString ) (.split ),) /获取用户权限字符串
. map (simplegrantedauthority : new ).collect ) collectors.tolist; //将元素转换为接地授权接口集合
user principal=new user (claims.get subject (),',authorities );
returnnewusernamepasswordauthenticationtoken (principal,null,authorities );
}
publicstringgetauthsubject (string token ) {
claims claims=jwts.parser (.setsigningkey (secret key ).parseclaimsjws ) token ).getBody );
return claims.getSubject (;
}
publicstringresolvetoken (httpservletrequestrequest ) {
stringbearertoken=request.get header (authorization _ header ); 从HTTP标头获取TOKEN
string utils.hastext (bearer token ) bearer token.starts with (sysconst.sys _ company _ head ) ) ) ) )
returnbearertoken.substring (bearer token.index of (“.”) 1,bearerToken.length ) ); 返回Token字符串并删除Bearer
}
string jwt=request.getparameter (authorization _ token ); //从请求参数中获取TOKEN
string utils.hastext (jwt ) jwt.starts with (sysconst.sys _ company _ head ) }
return jwt.substring (bearer token.index of ('.' ) 1,jwt.length );
}
返回空值;
}
验证Token是否正确
publicbooleanvalidatetoken (string token ) {
try {
Jwts.parser ().setsigningkey (secret key ).parseclaimsjws (token ); 用//键验证Token
返回真;
}catch(malformedjwtexceptione ) { //JWT格式错误
Logger.info(InvalidjwtToken.);
logger.trace (invalidjwttokentrace : ),e );
}catch(expiredjwtexceptione ) { //JWT已过期
Logger.info(expiredjwtToken.);
logger.trace (expiredjwttokentrace : ),e );
} catch (unsupportedjwtexceptione )//不支持此jwt
logger.info (unsupportedjwttoken.);
logger.trace (unsupportedjwttokentrace : ),e );
} catch (illegalargumentexceptione )//参数错误异常
logger.info (jwttokencompactofhandlerareinvalid.' );
logger.trace (jwttokencompactofhandlerareinvalidtrace : (,e ) );
}catch(signatureexceptione )//签名异常
logger.info (invalidjwtsignature.' );
logger.trace (invalidjwtsignaturetrace : ),e );
}
返回假;
}
}
redis写缓存:
RedisModel model=new RedisModel (;
model.setmodelname(Token );
model.setmodelkey('userinfo );
MapString,Object params=new HashMapString,Object (;
params.put('username ',customerDto.getUsername ) );
vocustomervo=newcustomervo (;
客户VO.set email (客户dto.get email ();
VO.set phone (dto.get phone ) );
vouserinfo=customerservice.queryuserbyusername (customer VO;
MapString,objectusertoken=newhashmapstring,object (;
usertoken.put(usertoken )、token );
usertoken.put(userInfo )、userinfo );
model.setmodeldata(usertoken;
model.settimeouttype('m );
model.settimeout (redistokentimeout;
result map.setcode (commonresultstatus.success.getcode );
result map.set message (commonresultstatus.success.getmessage );
写为hash实体
redistemplate.opsforhash(.put ) model.getmode lname (model.getmode lkey )、model.getModelData ) );
redis template.expire (model.getmode lname (,model.getTimeout ),TimeUnit.MINUTES );
@Configuration
@EnableWebSecurity
@ enableglobalmethodsecurity (prepostenabled=true ) )。
publicclasswebsecurityconfigextendswebsecurityconfigureradapter {
publicstaticfinalstringauthorization _ header=' x-token ';//授权
//允许访问的路径
privatestaticfinalstring [ ] auth _ without list={
//-- swagger ui
'/v2/api-docs ','/swagger-resources ','/swagger-resources/** ','/configuration/ui ',
'/configuration/security ','/swagger-ui.html ','/webjars/** ',
//otherpublicendpointsofyourapimaybeappendedtothisarray
'/druid/** ','/health ','/info ','/info/** ',//druid sql监听
'/hystrix ','/hystrix/** ','/error ','/loggers ','/loggers/** ',
'/service-registry/instance-status '、'/hystrix.stream '、'/turbine/** '、'/turbine.stream ',
'/autoconfig ','/archaius ','/beans ','/features ','/configprops ','/mappings ','/auditevents,
'/env '、'/env/** '、'/metrics '、'/metrics/** '、'/trace '、'/trace/** '、'/dump(/dump ) )。
'/info/** '、'/activiti/** '、'/logfile/** '、'/refresh '、'/flyway/** '、'/liquibase/**,
'/v1/authcenter/login ','/v1/authcenter/fiberhomeLogin ','/v1/authcenter/registered ',//注册URL
'/v1/authcenter/queryAuthInfo ',//认证URL
'/u/sms/sendPhone ','/citry/getChineseProvinces ','/code/getCaptchaImage ','/u/sms/forgetEmailPwd '
'/u/sms/sendEmail ','/citry/getOtherCoutryList ','/upload/pngDir/* ','/job/getJobList ','/u/SME
'/v1/auth center/queryuserinfobymap ','/v1/authcenter/forgetPwd ',
'/diagram-viwmer/** ','/editor-marketing/** ',
'/modeler.html ',
'/actuator/health '
(;
@Autowired
privatesecurityuserdetailsservicesecurityuserdetailsservice
@Autowired
privateauthlogoutsuccesshandlerauthlogoutsuccesshandler;
@Autowired
privatejwttokenutilstokenprovider;
@Override
保护性视觉配置(authenticationmanagerbuilderauth ) throws Exception {
//自定义用户信息获取以设置密码加密和使用DaoAuthenticationProvider加密默认设置的选项
auth.user details service (securityuserdetailsservice ).passwordencoder () );
}
@Override
保护性dvoidconfigure (httpsecurityhttp ) throws Exception {
//配置请求访问策略
关闭CSRF、CORS
http.CORS(.disable ) (.csrf ).disable ) )。
因为使用Token,所以不需要会话
. sessionManagement () (.sessioncreationpolicy (sessioncreationpolicy.stateless ).and ) ) )。
验证Http请求
. authorizeRequests () )
//允许所有用户访问和登录主页
. antmatchers(auth_withoutlist ).permitAll ) )。
//其他任何要求都必须通过认证
. anyRequest ().authenticated ) (.and ) )。
//用户页面需要用户权限
//设置注销
. logout ().logoutsuccesshandler (authlogoutsuccesshandler ).permitAll;
添加jwt过滤器
http.addfilterbefore (newjwtauthenticationtokenfilter (token provider ),usernamepasswordauthenticationfilter.class );
}
//判断是否有权限分为三个步骤
后台security屏蔽了地址。 必须在请求标头中设置请求参数参数
1 )判断token是否存在(security实现了) ) ) ) ) ) ) ) ) ) ) ) ) ) token ) ) ) )。
2 )2:token是否有效(基于redis ) ) ) ) ) ) ) ) ) ) )。
3:访问API是否具有权限
缓存结构:
[
' java.util.HashMap ',
{
' user token ' : ' isoft stone.eyjhbgcioijiuzuxmij9. eyjzdwiioii0mmrkmgjlzmwndg0mmyodhin2qxzjvkytcwmnjnisimf1dgioij 11 qpdi _ ykk XP G3 l 90 dnn5WG k2 rzxs 471 PME by-bdhphd2- ink fa ',
' userInfo': [
' com.common.vo.CustomerVo ',
{
' id ' : ' 42 dd0 befd 04842 c 288 b7D1 F5 da 701 cc6',
' createTime': [
' java.util.Date ',
' 2021-06-10 '
]、
'更新时间' : [
' java.util.Date ',
' 2021-06-10 '
]、
“deleted': 0,
' phone': '13797004616 ',
' password': '123456 ',
' email ' : ' sunlin @ fiberhome.com ',
“状态”:“3”是,
' isEnable': '1',
' userType': '1',
' roleId': null,
“计数”: null,
' provinces': null,
' company': null,
' jobs ' :空,
' realName': '孙子'、
' fiberhomeEmail': null,
“部署”: null,
“注册为”: null,
' onlineTime': null,
' expireDate': null,
' register IP ' :空值,
“语言”: null,
' equipmentType': null,
“帐户类型”: null,
“平台类型”: null,
' companyType': null,
' userdesc': null,
' userid': '0210990342 ',
' typeConfig': null,
' isActive': '1',
“postname':“副总裁”、
' did1': '701387 ',
' dname1': '财务管理部',
' did2' :空,
' dname2': null,
' did3' :空,
' dname3': null,
' did4' :空,
' dname4': null,
' postid': '803711 '
}
]
}
]
接口实现返回:
x-token : isoft stone.eyjhbgcioijiuzuxmij9. eyjzdwiioii0mmrkmgjlzmqwndg0mmyodhin2qxzjvkytcwmwnjnisimf1dgioij 1c2vyiwiwwwiwiwiwwwin ub0eu 6jj Xin0khigzlfqzh 7a xt1a id0rhr vs-o5vf 7cv p5jd9cqpkqwfp 724 a
请求访问其他接口并加入请求头Headers即可。 我们的api接口的乘方等完成了。