前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >专栏 >ASP.NET Core技术--使用用户密码保护API接口

ASP.NET Core技术--使用用户密码保护API接口

原创
作者头像
软件架构师Michael
发布2023-03-19 12:25:45
发布2023-03-19 12:25:45
62700
代码可运行
举报
运行总次数:0
代码可运行

使用用户密码保护API接口

代码语言:javascript
代码运行次数:0
运行
复制
public static IEnumerable<IdentityResource> GetIdentityResources()
{
 var customProfile = new IdentityResource(
 name: "custom.profile",
 displayName: "Custom profile",
 claimTypes: new[] { "name", "email", "status" });
 return new List<IdentityResource>
 {
 new IdentityResources.OpenId(),
 new IdentityResources.Profile(),
 customProfile
 };
}

//JWT令牌格式

//JSON Web Token 是一种开放的行业标准 RFC 7519方法,用于在双方之间安全地表示声明。

//获取令牌值

string token = HttpContext.GetTokenAsync("access_token").Result;

//JWT身份令牌中的申明转换为微软申明

JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

ClaimTypeMapping.cs

//扩展用户密码验证逻辑

public class ResourceOwnerPasswordValidator : IResourceOwnerPasswordValidator
{
 public Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
 {
 if (context.UserName == "username" && context.Password == "password")
 {

 context.Result = new GrantValidationResult(context.UserName, 
GrantType.ResourceOwnerPassword);

 }

 }
 return Task.CompletedTask;
 }
}
services.AddIdentityServer().AddResourceOwnerValidator<ResourceOwnerPasswordValidator>();

获取用户详细信息

代码语言:javascript
代码运行次数:0
运行
复制
public static IEnumerable<IdentityResource> IdentityResources =>
 new List<IdentityResource>
 {
 new IdentityResources.OpenId(),
 new IdentityResources.Profile()
 };

AllowedScopes = {

 "api1",
 IdentityServerConstants.StandardScopes.OpenId,
 IdentityServerConstants.StandardScopes.Profile
},

var userInfo = await apiClient.GetUserInfoAsync(new UserInfoRequest

{

 Token = tokenResponse.AccessToken,
 Address = disco.UserInfoEndpoint,
});

【小结】

本小节简单介绍了使用API时所采用的安全措施。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档