ClaimType 来存储头像 URI
ClaimType to store avatar URI
我在我的应用程序中使用 Facebook/Google 身份验证,一旦通过身份验证,我就会创建自己的 cookie。
什么 ClaimType
适合存储用户的头像 URI?
如果找不到匹配项,则不需要坚持使用 ClaimTypes
枚举,因为支持字符串。
使用字符串完全有效:
var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
identity.AddClaim(new Claim("Gravatar", user.GravatarLink));
收回索赔:
var gravatar = HttpContext.User.Claims
.Where(c => c.Type == "Gravatar")
.Select(c => c.Value).FirstOrDefault();
这样做的明显缺点是,这是一个 'magical' 字符串,可能会在运行时被打错并中断。如果您绝对想要这些额外类型的强类型,请创建您自己的提供自定义声明的静态类型:
public static class MyClaimTypes
{
public static string Gravatar = "Gravatar";
public static string FullName = "FullName";
}
这确保您获得强类型而不是魔术字符串。现在您可以在代码中将 "Gravatar"
字符串替换为 MyClaimTypes.Gravatar
。
我在我的应用程序中使用 Facebook/Google 身份验证,一旦通过身份验证,我就会创建自己的 cookie。
什么 ClaimType
适合存储用户的头像 URI?
如果找不到匹配项,则不需要坚持使用 ClaimTypes
枚举,因为支持字符串。
使用字符串完全有效:
var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
identity.AddClaim(new Claim("Gravatar", user.GravatarLink));
收回索赔:
var gravatar = HttpContext.User.Claims
.Where(c => c.Type == "Gravatar")
.Select(c => c.Value).FirstOrDefault();
这样做的明显缺点是,这是一个 'magical' 字符串,可能会在运行时被打错并中断。如果您绝对想要这些额外类型的强类型,请创建您自己的提供自定义声明的静态类型:
public static class MyClaimTypes
{
public static string Gravatar = "Gravatar";
public static string FullName = "FullName";
}
这确保您获得强类型而不是魔术字符串。现在您可以在代码中将 "Gravatar"
字符串替换为 MyClaimTypes.Gravatar
。