c# - 如何自定义 JWT 认证响应?
问题描述
我在 asp.net Web Api 中使用 JWT 默认行为进行身份验证,下面是 oAuthProvider 类中的代码:
public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
var emailAddress = context.UserName;
var password = context.Password;
User user = DbContext.User.Where(m => m.EmailAddress == emailAddress && m.IsDeleted == false).FirstOrDefault();
if (user != null)
{
string encryptedPassword = CryptoUtility.GetPasswordHash(password, user.SaltKey);
if (encryptedPassword == user.Password)
{
if (user.IsActive)
{
var claims = new List<Claim>()
{
new Claim(ClaimTypes.Sid, Convert.ToString(user.Id)),
new Claim(ClaimTypes.Name, user.FullName),
new Claim(ClaimTypes.Email, user.EmailAddress)
};
ClaimsIdentity oAuthIdentity = new ClaimsIdentity(claims,
DefaultAuthenticationTypes.ExternalBearer);
var properties = CreateProperties(user.FullName);
var ticket = new AuthenticationTicket(oAuthIdentity, properties);
context.Validated(ticket);
}
else
{
context.SetCustomError(JsonConvert.SerializeObject(new CommonModel()
{
StatusCode = (int)ApiStatus.AccountDisabled,
Message = "Sorry your account is inactive. Please contact your administrator",
Data = new { }
}));
}
}
else
{
context.SetCustomError(JsonConvert.SerializeObject(new CommonModel()
{
StatusCode = (int)ApiStatus.InvalidCredentials,
Message = "The user name or password is incorrect",
Data = new { }
}));
}
}
return Task.FromResult<object>(null);
}
我尝试了很多方法,但我无法更改上述方法调用的 JWT 响应。我得到的结果是这样的(默认情况下在 JWT 中),
{
"access_token": "eyJef4AiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9zaWQiOiIxIiwidW5pcXVlX25hbWUiOiJTYW12ZWRhbmEgVHJ1c3QiLCJlbWFpbCI6ImFkbWluQGRyY3N5c3RlbXMuY29tIiwiaXNzIjoiaHR0cDovL2NybS5zYW12ZWRhbmEub3JnLmluIiwiYXVkIjoiQW55IiwiZXhwIjoxNTM2MzA4OTg1LCJuYmYiOjE1MzYyMjI1ODV9.xBKt-WxVTzDyg1kYoynXGzDU-gl0l3vp9zeAQyHLPdE",
"token_type": "bearer",
"expires_in": 86399,
"userName": "Demo 1",
".issued": "Thu, 06 Sep 2018 08:29:45 GMT",
".expires": "Fri, 07 Sep 2018 08:29:45 GMT"
}
怎么改回复啊!
解决方案
推荐阅读
- wpf - 在 Telerik 富文本框中获取更改的上下文
- python - 不同 socks5 代理的不同电子邮件验证结果
- ocaml - OCaml/ReasonML 是否支持核心语言或核心库中的 DSL?
- javascript - 为计数器创建重置按钮
- css - 如何在 div 上制作响应式背景
- java - 除非使用相同的命令编译包类,否则不会编译模块信息
- uml - 如何在 UML 中为字典添加简单的泛型类型注释?
- google-sheets - Google 表格:无法向图表系列添加标签
- javascript - 如何在 npm 模块上使用 web worker
- reactjs - 无法读取 Apollo 中未定义的属性“subscribeToMore”