WebApi中关于base64和jwt的联合验证

用到了如鹏的代码

jwt验证

 1  public class MyAuthoFilterPostOrgInfoAttribute: AuthorizationFilterAttribute
 2     {
 3         public override void OnAuthorization(HttpActionContext actionContext)
 4         {
 5             IEnumerable<string> addToken;
 6             if (actionContext.Request.Headers.TryGetValues("addToken", out addToken))
 7             {
 8                 string tokenStr = addToken.First();
 9                 var secret = "GQDstcKsmarcccPOuXOYg9MbeJ1XT0uFiwDVvVBrk";//不要泄露
10                 try
11                 {
12                     IJsonSerializer serializer = new JsonNetSerializer();
13                     IDateTimeProvider provider = new UtcDateTimeProvider();
14                     IJwtValidator validator = new JwtValidator(serializer, provider);
15                     IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
16                     IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder);
17                     var json = decoder.Decode(tokenStr, secret, verify: true);
18                     //Console.WriteLine(json);
19                     //MessageBox.Show("解密成功" + json);
20 
21                 }
22                 catch (TokenExpiredException)
23                 {
24                     //MessageBox.Show("token过期");
25                     returnFunc(actionContext, "token过期");
26 
27                 }
28                 catch (SignatureVerificationException)
29                 {
30                     //MessageBox.Show("签名校验失败,数据可能被篡改");
31                     returnFunc(actionContext, "签名校验失败,数据可能被篡改");
32                 }
33                 catch (Exception)
34                 {
35                     returnFunc(actionContext, "身份验证未通过");
36                 }
37             }
38             //base.OnAuthorization(actionContext);
39         }
40 
41 
42         private void returnFunc(HttpActionContext actionContext,string msg)
43         {
44             ApiResult<string> result = new ApiResult<string>
45             {
46                 Code = (int)HttpStatusCode.Unauthorized,
47                 Message = msg
48 
49             };
50             string resultJson = JsonConvert.SerializeObject(result);
51             //context.
52             //actionContext.RequestContext
53 
54             actionContext.Response = new HttpResponseMessage
55             {
56                 Content = new StringContent(resultJson, Encoding.GetEncoding("UTF-8"), "application/json"),
57                 StatusCode = HttpStatusCode.Unauthorized
58             };
59         }
60     }

base64验证

 1 public class MyAuthoFilterForGetTokenAttribute: AuthorizationFilterAttribute
 2     {
 3         public override void OnAuthorization(HttpActionContext actionContext)
 4         {
 5             //base.OnAuthorization(actionContext);
 6             IEnumerable<string> getToken;
 7             if (actionContext.Request.Headers.TryGetValues("getToken", out getToken))
 8             {
 9                 //通过base64解密
10                 string tokenStr = getToken.First();
11                 byte[] bytes;
12                 string result;
13                 try
14                 {
15                     bytes = System.Convert.FromBase64String(tokenStr);
16                      result = System.Text.Encoding.UTF8.GetString(bytes);
17                     JObject jsonModel = (JObject)JsonConvert.DeserializeObject(result);
18                     string userName = jsonModel["userName"].ToString();
19                     string password = jsonModel["password"].ToString();
20                     if (userName == "admin" && password == "qwe321")
21                     {
22                         
23                     }
24                     else
25                     {
26                         returnFunc(actionContext);
27                     }
28                 }
29                 catch (Exception)
30                 {
31                     returnFunc(actionContext);
32                 }
33             }
34             else
35             {
36                 returnFunc(actionContext);
37             }
38 
39         }
40 
41 
42         private void returnFunc(HttpActionContext actionContext)
43         {
44             ApiResult<string> result = new ApiResult<string>
45             {
46                 Code = (int)HttpStatusCode.Unauthorized,
47                 Message = "未授权"
48 
49             };
50             string resultJson = JsonConvert.SerializeObject(result);
51             //context.
52             //actionContext.RequestContext
53 
54             actionContext.Response = new HttpResponseMessage
55             {
56                 Content = new StringContent(resultJson, Encoding.GetEncoding("UTF-8"), "application/json"),
57                 StatusCode = HttpStatusCode.Unauthorized
58             };
59         }
60     }

controller

  1  public class ValueController: AbpApiController
  2     {
  3         private readonly IOrganizationAppService _orgService;
  4 
  5        
  6        public ValueController(IOrganizationAppService orgService)
  7         {
  8             this._orgService = orgService;
  9         }
 10         [HttpGet]
 11        
 12         public async  Task<string>  GetOrgInfo()
 13         {
 14             EntityDto<int> entity = new EntityDto<int>();
 15             entity.Id = 1;
 16             OrganizationListDto org = new OrganizationListDto();
 17             try
 18             {
 19                  org = await _orgService.GetOrganizationByIdAsync(entity);
 20             }
 21             catch (Exception ex)
 22             {
 23                 string ex1 = ex.ToString();
 24                 throw;
 25             }
 26             
 27             return  JsonConvert.SerializeObject(org);
 28         }
 29         [HttpGet]
 30         public  string Get()
 31         {
 32             return "OK";
 33         }
 34 
 35 
 36         [MyAuthoFilterForGetToken]
 37         public IHttpActionResult GetToken()
 38         {
 39 
 40             //返回jwt加密
 41             double exp = (DateTime.UtcNow.AddSeconds(60) - new DateTime(1970, 1, 1)).TotalSeconds;
 42             var payload = new Dictionary<string, object>
 43                             {
 44                                 { "userName", "admin" },
 45                                 { "password", "qwe321" },
 46                                 {"exp",exp }
 47                             };
 48             var secret = "GQDstcKsx0NHjPOuXOYg9MbeJ1XT0uFiwDVvVBrk";//不要泄露
 49             IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
 50             IJsonSerializer serializer = new JsonNetSerializer();
 51             IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
 52             IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);
 53             string token = encoder.Encode(payload, secret);
 54             //textBox1.Text = token;
 55 
 56             ApiResult<string> result = new ApiResult<string>
 57             {
 58                 Code = 200,
 59                 Message ="请求成功",
 60                 ReturnValue=token
 61                 
 62             };
 63              //JsonConvert.SerializeObject(result);
 64             return Json(result);
 65         }
 66 
 67         [HttpPost]
 68         [MyAuthoFilterPostOrgInfo]
 69         public async Task<IHttpActionResult> PostOrgInfo([FromBody]JObject par)
 70         {
 71             //var varlue11 = value;
 72             string data = par["data"].ToString();
 73             
 74             string dataDeal = data.Replace("\r\n ", " ").Replace("\\", " ").Trim();
 75             List<OrganizationEditDtoForInterface> orgInfoList = JsonConvert.DeserializeObject<List<OrganizationEditDtoForInterface>>(dataDeal);
 76 
 77             //验证字段是否完整???
 78 
 79 
 80             //验证数据重复性
 81             foreach (var orgInfo in orgInfoList)
 82             {
 83                 
 84                 if (_orgService.CheckIsExitOrgName(orgInfo.OrgName,0))
 85                 {
 86 
 87                     return Json(returnFunc((int)HttpStatusCode.Forbidden, "已存在服务商"));
 88                 }
 89                 
 90             }
 91 
 92             //验证完重复性,现在开始存数据
 93            bool isSucceed =  await _orgService.CreateOrganizationForInterfaceAsync(orgInfoList);
 94 
 95             if (isSucceed)
 96             {
 97                 return Json(returnFunc((int)HttpStatusCode.OK,"数据保存成功"));
 98             }
 99             else
100             {
101                 return Json(returnFunc((int)HttpStatusCode.Forbidden, "数据保存失败"));
102             }
103 
104             
105             //return "PostOrgInfo";
106         }
107 
108         public ApiResult<string> returnFunc(int statueCode,string msg)
109         {
110             ApiResult<string> result = new ApiResult<string>
111             {
112                 Code = statueCode,
113                 Message = msg
114 
115             };
116             return result;
117         }
118 
119         public string Post([FromBody] LoginModel2 model)
120         {
121             if (model.UserName=="admin"&&model.Password=="321")
122             {
123                 return "Ok,userName=" + model.UserName;
124             }
125             else
126             {
127                 return "Bad";
128             }
129 
130         }
131 
132 
133     }

 

转载于:https://www.cnblogs.com/Spinoza/p/9697893.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值