首页后端开发ASP.NETASP.NET Core技术--使用用户密码保护API接口

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

时间2023-03-24 17:30:28发布访客分类ASP.NET浏览940
导读:使用用户密码保护API接口public static IEnumerable<IdentityResource> GetIdentityResources( { var customProfile = new Identit...

使用用户密码保护API接口

public static IEnumerableIdentityResource>
 GetIdentityResources()
{

 var customProfile = new IdentityResource(
 name: "custom.profile",
 displayName: "Custom profile",
 claimTypes: new[] {
 "name", "email", "status" }
    );
    
 return new ListIdentityResource>

 {

 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().AddResourceOwnerValidatorResourceOwnerPasswordValidator>
    ();
    

获取用户详细信息

public static IEnumerableIdentityResource>
     IdentityResources =>
    
 new ListIdentityResource>

 {

 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时所采用的安全措施。

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!

apiasp

若转载请注明出处: ASP.NET Core技术--使用用户密码保护API接口
本文地址: https://pptw.com/jishu/269.html
正式开始学习ASP.NET Core 6 Razor Pages 介绍 安全攻防 | MSF生成Payload方式总结

游客 回复需填写必要信息