• 保存到桌面  加入收藏  设为首页
Web综合

C#-WCF框架-访问认证与接口安全-拦截器-ServiceStack.Redis-AccessToken-url请求过滤-限制越权访问-已登录-核心代码

时间:2018-05-10 21:38:46   作者:江节胜   来源:胜行天下网   阅读:703   评论:0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
Git地址:待上传
 
TestServiceImpl.svc中的Service 需要对应 webconfig中的serviceActivations下service节点
 
redis windows端程序去网上下载,redis账号在web.config中配置,但是要注意ServiceStack.Redis库配置密码时无法连接redis服务
 
redis第三方库为ServiceStack.Redis
 
开启或关闭认证过滤或需要忽略认证的接口、资源、文件夹 均在App_Data/Config/Auth.config中配置
 
------------------------------------------------------------------------------
 
测试接口一览
http://localhost:23322/TestServiceImpl.svc/help
 
1、模拟登录
http://localhost:23322/TestServiceImpl.svc/Test/Login GET
{
    "code": 0,
    "message""登录成功,看看能不能调用需要认证接口",
    "result": {
        "AccessToken""5842735E-78C9-4235-833F-8029D489AA84",
        "UserId""88888" 
    }
}
 
2、需要登陆的接口需要添加头
http://localhost:23322/TestServiceImpl.svc/Test/Auth/1/5 GET
Content-Type application/json
accesstoken 5842735E-78C9-4235-833F-8029D489AA84
accessid 88888
 
{
    "code": 0,
    "message""请求成功啦",
    "result""Param1=1,Param2=5"
}
 
3、会忽略登录认证的接口
http://localhost:23322/TestServiceImpl.svc/Test/IgnoreAuth GET
{
    "code": 0,
    "message""请求成功啦",
    "result"null
}
 
 
核心代码
--------------AuthInterceptor.cs
 
 
using com.jiangjiesheng.auth;
using com.jiangjiesheng.auth.Constant;
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;
using System.Text.RegularExpressions;
using System.Web;
  
 
namespace com.jiangjiesheng.auth.Interceptors
{//IDispatchMessageInspector IClientMessageInspector  
 
    /**
     
     * 20180429 拦截器
     * 江节胜 dev@jiangjiesheng.cn
     
     */
    public class AuthInterceptor : IDispatchMessageInspector
    {
        // 备份桌面的Weiz.Redis文件夹
 
     
        String  AuthConfigPath = JSConfigTool.getAppDataConfigPath(JSConfigTool.DataConfigPath.AuthConfig);
         
 
 
        public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
        {
      
 
            bool isOpenAuth = Boolean.Parse(JSConfigTool.getAppDataConfig(AuthConfigPath, "authConfig/isOpenAuth"));
            if (!isOpenAuth)//关闭验证
            {
                return true;
            }
 
            HttpRequest currentRequest = HttpContext.Current.Request;
            String rawUrl = currentRequest.RawUrl;
            if (!isSkipCheck(rawUrl))
            {
                 
 
                //  var user = GetHeaderValue("keyval");
                //  throw new Exception("未经授权的访问!"); 没能处理异常 但是这个是必须的 WCF_ExceptionHandler : IErrorHandler 添加后还是提示没有处理异常
 
 
                // return ResponseStatus.getCode(Status.NEED_LOGIN);
 
                // throw new FaultException(string.Format("Exception accessing database:{0}",
                //"ceshi "), new FaultCode("Connect to database"));
                  
                //获取登录数据 然后 放行 ,如果实在获取不到action 方法名 ,就通过参数来数据
 
 
                var accessToken = HttpContext.Current.Request.Headers["accesstoken"];
                var accessId = HttpContext.Current.Request.Headers["accessid"];
 
                if (String.IsNullOrWhiteSpace(accessToken) || String.IsNullOrWhiteSpace(accessId))
                {
                    ServerResponse r = ServerResponse.create(ResponseStatus.getCode(Status.ILLEGAL_REQUEST), ResponseStatus.getDesc(Status.ILLEGAL_REQUEST), "");
                    this.ReplyAndAbortRequest(r, channel, instanceContext);
                    return false;
                }
                ServerResponse query = UserInfoCache.getUserInfo(accessId, accessToken);
                bool isLogined = query.IsSuccess();
                if (!isLogined)
                {
                    ServerResponse r = ServerResponse.create(ResponseStatus.getCode(Status.NEED_LOGIN), query.message, "");
                    this.ReplyAndAbortRequest(r, channel, instanceContext);
                    return false;
                }
                //刷新有效时间放在getUserInfo() 中了
                return false;
 
            }
            return true;
        }
 
        public void BeforeSendReply(ref Message reply, object correlationState)// //AfterReceiveRequest 的返回值 将在BeforeSendReply 中 correlationState 上读取
        {
            Message returnV = reply;
            Console.Write(reply.ToString());
        }
 
 
        private string GetHeaderValue(string name, string ns = "http://tempuri.org")
        {
            var RequestMessage = OperationContext.Current.RequestContext.RequestMessage;
            var headers = OperationContext.Current.IncomingMessageHeaders;
            var index = headers.FindHeader(name, ns);
            if (index > -1)
                return headers.GetHeader(index);
            else
                return null;
        }
 
        private void ReplyAndAbortRequest(T t, IClientChannel channel, InstanceContext instanceContext) //
        {    
            String res = JsonHelper.ObjectToJsonNotForSerialize(t);
 
            HttpContext.Current.Response.AddHeader("Content-Type""application/json");//实测两个都可以
            HttpContext.Current.Response.ContentType = "application/json";//实测两个都可以
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.AddHeader("Content-Length","");//去掉Transfer-Encoding:chunked 头必须 但是某些情况导致请求不能中断
            HttpContext.Current.Response.Write(JsonHelper.ObjectToJsonNotForSerialize(t));
            HttpContext.Current.Response.Flush();
            HttpContext.Current.Response.End();
            HttpContext.Current.Response.Close();//这里处理结束后不要在BeforeSendReply()中继续调用
            instanceContext.Abort();//起关键作用 中断
            channel.Abort();
            channel.Close();
            HttpContext.Current.Request.Abort();
        }
 
 
 
        private bool isSkipCheck(String rawUrl)
        {
   
            if (string.IsNullOrEmpty(rawUrl))
            {
                return false;
            }
            String authIgnorePathStr = JSConfigTool.getAppDataConfig(AuthConfigPath, "authConfig/authIgnorePath");
            authIgnorePathStr = authIgnorePathStr.Replace("\\r\\n""").Replace("\\\"""\"").Replace("\r\n""").Replace(" """);
 
            string[] arr = Regex.Split(authIgnorePathStr, "###", RegexOptions.IgnoreCase);
            foreach (var url in arr)
            {
                if (String.IsNullOrWhiteSpace(url))//最后一个是空
                {
                    continue;
 
                }
                if (rawUrl.IndexOf(url) > -1)
                {
                    return true;
 
                }
            }
            return false;
        }
    }
}
 
--------RedisCacheHelper.cs
 
using ServiceStack.Redis;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
 
namespace com.jiangjiesheng.auth
{
 
    /**
     
     * 20180429 redis (ServiceStack.Redis)
     * 江节胜 dev@jiangjiesheng.cn
     
     */
    public class RedisCacheHelper
    {
         private static readonly PooledRedisClientManager pool = null;
        private static readonly string[] redisHosts = null;
        public static int RedisMaxReadPool = int.Parse(ConfigurationManager.AppSettings["redis_max_read_pool"]);
        public static int RedisMaxWritePool = int.Parse(ConfigurationManager.AppSettings["redis_max_write_pool"]);
 
        static RedisCacheHelper()//static 会优先初始化,测试如果不通过的话使用单例模式写
        {
            var redisHostStr = ConfigurationManager.AppSettings["redis_server_session"];
 
            if (!string.IsNullOrEmpty(redisHostStr))
            {
                redisHosts = redisHostStr.Split(',');
 
                if (redisHosts.Length > 0)
                {
                    //var client = new RedisClient("127.0.0.1", 6379);
                  
                    pool = new PooledRedisClientManager(redisHosts, redisHosts,
                        new RedisClientManagerConfig()
                        {
                            MaxWritePoolSize = RedisMaxWritePool,
                            MaxReadPoolSize = RedisMaxReadPool,
                            AutoStart = true
                        });
                }
            }
        }
 
 
        public static Int32 Add(string key, T value, DateTime expiry)
        {
            if (value == null)
            {
                return 0;
            }
 
            if (expiry <= DateTime.Now)
            {
                Remove(key);
 
                return 0;
            }
 
            try
            {
                if (pool != null)
                {
                    using (var r = pool.GetClient())
                    {
                        if (r != null)
                        {
                            r.SendTimeout = 1000;
                            r.Set(key, value, expiry - DateTime.Now);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string msg = string.Format("{0}:{1}发生异常!{2}""cache""存储", key);
                throw ex;
                return 0;
            }
            return 1;
        }
 
        public static void Add(string key, T value, TimeSpan slidingExpiration)
        {
            if (value == null)
            {
                return;
            }
 
            if (slidingExpiration.TotalSeconds <= 0)
            {
                Remove(key);
 
                return;
            }
 
            try
            {
                if (pool != null)
                {
                    using (var r = pool.GetClient())
                    {
                        if (r != null)
                        {
                            r.SendTimeout = 1000;
                            r.Set(key, value, slidingExpiration);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string msg = string.Format("{0}:{1}发生异常!{2}""cache""存储", key);
                throw ex;
            }
 
        }
 
 
 
        public static T Get(string key)
        {
            if (string.IsNullOrEmpty(key))
            {
                return default(T);
            }
 
            T obj = default(T);
 
            try
            {
                if (pool != null)
                {
                    using (var r = pool.GetClient())
                    {
                        if (r != null)
                        {
                            r.SendTimeout = 1000;
                            obj = r.Get(key);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string msg = string.Format("{0}:{1}发生异常!{2}""cache""获取", key);
                throw ex;
            }
 
 
            return obj;
        }
 
        public static void Remove(string key)
        {
            try
            {
                if (pool != null)
                {
                    using (var r = pool.GetClient())
                    {
                        if (r != null)
                        {
                            r.SendTimeout = 1000;
                            r.Remove(key);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string msg = string.Format("{0}:{1}发生异常!{2}""cache""删除", key);
                throw ex;
            }
 
        }
 
        public static bool Exists(string key)
        {
            try
            {
                if (pool != null)
                {
                    using (var r = pool.GetClient())
                    {
                        if (r != null)
                        {
                            r.SendTimeout = 1000;
                            return r.ContainsKey(key);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string msg = string.Format("{0}:{1}发生异常!{2}""cache""是否存在", key);
                throw ex;
            }
 
            return false;
        }
 
 
 
        public static bool Expire(string key,TimeSpan expireIn)
        {
            try
            {
                if (pool != null)
                {
                    using (var r = pool.GetClient())
                    {
                        if (r != null)
                        {
                            r.SendTimeout = 1000;
                            return r.ExpireEntryIn(key,expireIn);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string msg = string.Format("{0}:{1}发生异常!{2}""cache""是否存在", key);
                throw ex;
            }
 
            return false;
        }
 
    }
}
 
 
--------UserInfoCache.cs
 
 
using com.jiangjiesheng.auth;
using com.jiangjiesheng.auth.Constant;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
  
namespace com.jiangjiesheng.auth
{
    /**
    
    * 20180429 登录用户信息读取、保存、更新等
    * 江节胜 dev@jiangjiesheng.cn
    
    */
    public class UserInfoCache
    {
        public const Double userValidTime = 12;
        static String AuthConfigPath = JSConfigTool.getAppDataConfigPath(JSConfigTool.DataConfigPath.AuthConfig);
         
        /// 
        /// 存值统一使用手机号(方便管理)
        /// 
        /// 特别注意:此服务不能用作SSO登录,因为校验了accesstoken,不需要,后期如果要做SSO,就要在客户端保存一个独立固定值key,相当于cookie值
        /// 
        /// 成功时 msg 中返回key
        /// 
        public static ServerResponse setOrUpdateUserInfo(AppUserInfoEntity user)
        {
            bool isOpenAuth = Boolean.Parse(JSConfigTool.getAppDataConfig(AuthConfigPath, "authConfig/isOpenAuth"));
            if (!isOpenAuth)//关闭验证
            {
                return ServerResponse.create(-1, "保存登陆信息失败:配置设置为不使用接口校验""");
            }
 
            String accessToken = (Keys.KEY_REDIS_USER_ACCESSTOKEN_PREFIX + System.Guid.NewGuid().ToString()).ToUpper();//accessToken
            try
            {
                //存的时候使用openId取值
                //取值的时候使用使用accessToken+(手机号或者openId)校验
                if (user != null && !String.IsNullOrWhiteSpace(user.UserId))
                {
                    user.AccessToken = accessToken;//用于读取时校验accessToken和accessId是否匹配
 
                    String userJson = JsonHelper.ObjectToJsonNotForSerialize(user);
 
                    String accessId = (Keys.KEY_REDIS_USER_ACCESSID_PREFIX + user.UserId);// accessId
 
                    var nowT = DateTime.Now;//UtcNow
                    var expiredT = nowT.AddHours(userValidTime);
                    int result = RedisCacheHelper.Add(accessId, userJson, expiredT);
                    if (result == 1)
                    {
                        return ServerResponse.create(0, "保存登陆信息成功", accessToken);//成功的时候返回 reidsKey
                    }
                    return ServerResponse.create(-1, "保存登陆信息失败", accessToken);
                }
                return ServerResponse.create(-1, "保存登陆信息失败:数据异常", accessToken);
 
            }
            catch (Exception ex)
            {
                return ServerResponse.create(-1, "保存登陆信息失败:Redis服务异常,请联系管理员", accessToken);
            }
 
        }
        public static ServerResponse updateUserInfoExpireTime(String reidsKey, TimeSpan timeSpan)//TimeSpan.FromHours(userValidTime)
        {
            try
            {
                bool res = RedisCacheHelper.Expire(reidsKey, timeSpan);
                if (res == true)
                {
                    return ServerResponse.create(0, "设置成功"null);
                }
                return ServerResponse.create(-1, "设置失败"null);
            }
            catch (Exception ex)
            {
                return ServerResponse.create(-1, "设置失败:Redis服务异常,请联系管理员"null);
            }
 
        }
 
        /// 
        /// 
        /// 
        /// 手机号或者openid都行
        /// 
        /// 
        public static ServerResponse getUserInfo(String accessId, String reidsKey)//reidsKey 外部提交
        {
            try
            {
                if (String.IsNullOrWhiteSpace(accessId) || String.IsNullOrWhiteSpace(reidsKey))
                {
                    return ServerResponse.create(-1, "读取失败:无效请求"null);
                }
                String _accessId = (Keys.KEY_REDIS_USER_ACCESSID_PREFIX + accessId);// accessId
 
                String userJson = RedisCacheHelper.Get(_accessId);//通过手机号取值
 
                if (String.IsNullOrWhiteSpace(userJson))
                {
                    return ServerResponse.create(-1, "用户未登录或登录失效"null);
                }
                userJson = userJson.Replace("\\r\\n""").Replace("\\\"""\"");
                AppUserInfoEntity user = JsonHelper.JsonToObjectNotForSerialize(userJson);
                if (String.Equals(user.UserId, accessId) && String.Equals(user.AccessToken, reidsKey))//redis保存和接口提交的做一次校验
                {
                    //刷新有效时间
                    var nowT = DateTime.Now;//UtcNow
                    var expiredT = TimeSpan.FromHours(userValidTime);
                    UserInfoCache.updateUserInfoExpireTime(_accessId, expiredT);
                    return ServerResponse.create(0, "读取用户缓存信息成功", user);
                }
                return ServerResponse.create(-1, "读取失败:非法请求", user);
            }
            catch (Exception ex)
            {
                return ServerResponse.create(-1, "读取失败:Redis服务异常,请联系管理员"null);
            }
        }
    }
}
 
 
-----------JSConfigTool.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml;
 
namespace com.jiangjiesheng.auth
{
 
    /**
     
     * 读取App_Data下自定义配置文件
     
     * 20180125 江节胜 dev@jiangjiesheng.cn
     
     */
    public class JSConfigTool
    {
 
        public enum DataConfigPath//枚举
        {
            WeChatOfficalAccount,//微信公众号
            SMSSender,//短信发送,
            AuthConfig//接口安全校验配置
        }
        public static String getAppDataConfigPath(DataConfigPath path)
        {
 
            switch (path)
            {
                case DataConfigPath.WeChatOfficalAccount:
                    return "~/App_Data/Config/WeiXin.config";
 
                case DataConfigPath.SMSSender:
                    return "~/App_Data/Config/SMS.config";
                case DataConfigPath.AuthConfig:
                    return "~/App_Data/Config/Auth.config";
                default:
                    return null;
 
            }
 
        }
 
        /// 
        /// 20180125 江节胜 dev@jiangjiesheng.cn
        /// 
        /// 获取XML配置的信息
        /// 
        ///  ~/App_Data/Config/WeiXin.config
        ///  weixin/appid (注意加上父节点)
        public static String getAppDataConfig(String xmlConfigPath, String xmlNodeName)
        {
            XmlDocument Xml = new XmlDocument();
            Xml.Load(HttpContext.Current.Server.MapPath(xmlConfigPath));
            XmlNode xmlNode = Xml.SelectSingleNode(xmlNodeName);
            if (xmlNode != null)
            {
                return xmlNode.InnerText;
            }
            return null;
        }
        /// 
        /// 20180125 江节胜 dev@jiangjiesheng.cn
        /// 
        /// 设置XML配置的信息
        /// 
        ///  ~/App_Data/Config/WeiXin.config
        ///  weixin/appid (注意加上父节点)
        /// 
        /// 
        public static Boolean setAppDataConfig(String xmlConfigPath, String xmlNodeName, String value)
        {
            XmlDocument Xml = new XmlDocument();
            Xml.Load(HttpContext.Current.Server.MapPath(xmlConfigPath));
            XmlNode xmlNode = Xml.SelectSingleNode(xmlNodeName);
            if (xmlNode != null)
            {
                xmlNode.InnerText = value;
                Xml.Save(HttpContext.Current.Server.MapPath(xmlConfigPath));
                return true;
            }
 
            return false;
        }
    }
}

有任何疑问或技术合作都可联系我

微信:767000122 【推荐】

QQ:596957738


相关评论

加我微信 596957738 (QQ同号)加我微信   QQ联系:596957738   地址:江苏省南京市雨花台区

苏公网安备32011402010305号

皖ICP备16019989号

江节胜的Gitee,江节胜的Git地址