用到了如鹏的代码
jwt验证
public class MyAuthoFilterPostOrgInfoAttribute: AuthorizationFilterAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
IEnumerable<string> addToken;
if (actionContext.Request.Headers.TryGetValues("addToken", out addToken))
{
string tokenStr = addToken.First();
var secret = "GQDstcKsmarcccPOuXOYg9MbeJ1XT0uFiwDVvVBrk";//不要泄露
try
{
IJsonSerializer serializer = new JsonNetSerializer();
IDateTimeProvider provider = new UtcDateTimeProvider();
IJwtValidator validator = new JwtValidator(serializer, provider);
IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder);
var json = decoder.Decode(tokenStr, secret, verify: true);
//Console.WriteLine(json);
//MessageBox.Show("解密成功" + json); }
catch (TokenExpiredException)
{
//MessageBox.Show("token过期");
returnFunc(actionContext, "token过期"); }
catch (SignatureVerificationException)
{
//MessageBox.Show("签名校验失败,数据可能被篡改");
returnFunc(actionContext, "签名校验失败,数据可能被篡改");
}
catch (Exception)
{
returnFunc(actionContext, "身份验证未通过");
}
}
//base.OnAuthorization(actionContext);
} private void returnFunc(HttpActionContext actionContext,string msg)
{
ApiResult<string> result = new ApiResult<string>
{
Code = (int)HttpStatusCode.Unauthorized,
Message = msg };
string resultJson = JsonConvert.SerializeObject(result);
//context.
//actionContext.RequestContext actionContext.Response = new HttpResponseMessage
{
Content = new StringContent(resultJson, Encoding.GetEncoding("UTF-8"), "application/json"),
StatusCode = HttpStatusCode.Unauthorized
};
}
}
base64验证
public class MyAuthoFilterForGetTokenAttribute: AuthorizationFilterAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
//base.OnAuthorization(actionContext);
IEnumerable<string> getToken;
if (actionContext.Request.Headers.TryGetValues("getToken", out getToken))
{
//通过base64解密
string tokenStr = getToken.First();
byte[] bytes;
string result;
try
{
bytes = System.Convert.FromBase64String(tokenStr);
result = System.Text.Encoding.UTF8.GetString(bytes);
JObject jsonModel = (JObject)JsonConvert.DeserializeObject(result);
string userName = jsonModel["userName"].ToString();
string password = jsonModel["password"].ToString();
if (userName == "admin" && password == "qwe321")
{ }
else
{
returnFunc(actionContext);
}
}
catch (Exception)
{
returnFunc(actionContext);
}
}
else
{
returnFunc(actionContext);
} } private void returnFunc(HttpActionContext actionContext)
{
ApiResult<string> result = new ApiResult<string>
{
Code = (int)HttpStatusCode.Unauthorized,
Message = "未授权" };
string resultJson = JsonConvert.SerializeObject(result);
//context.
//actionContext.RequestContext actionContext.Response = new HttpResponseMessage
{
Content = new StringContent(resultJson, Encoding.GetEncoding("UTF-8"), "application/json"),
StatusCode = HttpStatusCode.Unauthorized
};
}
}
controller
public class ValueController: AbpApiController
{
private readonly IOrganizationAppService _orgService; public ValueController(IOrganizationAppService orgService)
{
this._orgService = orgService;
}
[HttpGet] public async Task<string> GetOrgInfo()
{
EntityDto<int> entity = new EntityDto<int>();
entity.Id = ;
OrganizationListDto org = new OrganizationListDto();
try
{
org = await _orgService.GetOrganizationByIdAsync(entity);
}
catch (Exception ex)
{
string ex1 = ex.ToString();
throw;
} return JsonConvert.SerializeObject(org);
}
[HttpGet]
public string Get()
{
return "OK";
} [MyAuthoFilterForGetToken]
public IHttpActionResult GetToken()
{ //返回jwt加密
double exp = (DateTime.UtcNow.AddSeconds() - new DateTime(, , )).TotalSeconds;
var payload = new Dictionary<string, object>
{
{ "userName", "admin" },
{ "password", "qwe321" },
{"exp",exp }
};
var secret = "GQDstcKsx0NHjPOuXOYg9MbeJ1XT0uFiwDVvVBrk";//不要泄露
IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
IJsonSerializer serializer = new JsonNetSerializer();
IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);
string token = encoder.Encode(payload, secret);
//textBox1.Text = token; ApiResult<string> result = new ApiResult<string>
{
Code = ,
Message ="请求成功",
ReturnValue=token };
//JsonConvert.SerializeObject(result);
return Json(result);
} [HttpPost]
[MyAuthoFilterPostOrgInfo]
public async Task<IHttpActionResult> PostOrgInfo([FromBody]JObject par)
{
//var varlue11 = value;
string data = par["data"].ToString(); string dataDeal = data.Replace("\r\n ", " ").Replace("\\", " ").Trim();
List<OrganizationEditDtoForInterface> orgInfoList = JsonConvert.DeserializeObject<List<OrganizationEditDtoForInterface>>(dataDeal); //验证字段是否完整??? //验证数据重复性
foreach (var orgInfo in orgInfoList)
{ if (_orgService.CheckIsExitOrgName(orgInfo.OrgName,))
{ return Json(returnFunc((int)HttpStatusCode.Forbidden, "已存在服务商"));
} } //验证完重复性,现在开始存数据
bool isSucceed = await _orgService.CreateOrganizationForInterfaceAsync(orgInfoList); if (isSucceed)
{
return Json(returnFunc((int)HttpStatusCode.OK,"数据保存成功"));
}
else
{
return Json(returnFunc((int)HttpStatusCode.Forbidden, "数据保存失败"));
} //return "PostOrgInfo";
} public ApiResult<string> returnFunc(int statueCode,string msg)
{
ApiResult<string> result = new ApiResult<string>
{
Code = statueCode,
Message = msg };
return result;
} public string Post([FromBody] LoginModel2 model)
{
if (model.UserName=="admin"&&model.Password=="")
{
return "Ok,userName=" + model.UserName;
}
else
{
return "Bad";
} } }