wxd 2 years ago
parent
commit
ded8b9137e
  1. 204
      src/Shentun.WebPeis.HttpApi.Host/Controllers/WeChatController.cs

204
src/Shentun.WebPeis.HttpApi.Host/Controllers/WeChatController.cs

@ -64,7 +64,7 @@ namespace Shentun.WebPeis.Controllers
_personRepository = personRepository;
_unitOfWorkManager = unitOfWorkManager;
}
[UnitOfWork(IsDisabled = true)]
//[UnitOfWork(IsDisabled = true)]
public async virtual Task<IActionResult> HandleAsync(ExtensionGrantContext context)
{
@ -73,109 +73,119 @@ namespace Shentun.WebPeis.Controllers
try
{
//确保只有授权的应用程序才能够调用
var httpClient = new HttpClient();
var request = new ClientCredentialsTokenRequest
{
Address = _configuration["AuthServer:Authority"] + "/connect/token",
GrantType = OpenIddictConstants.GrantTypes.ClientCredentials,
ClientId = context.Request.GetParameter("client_id").ToString(),
ClientSecret = context.Request.GetParameter("client_secret").ToString(),
};
var clientCredentialsResult = await httpClient.RequestClientCredentialsTokenAsync(request);
if (clientCredentialsResult.IsError)
{
throw new Exception("应用程序没有权限" + clientCredentialsResult.ErrorDescription);
}
if (context.Request.GetParameter("jsCode") == null)
{
throw new Exception("jsCode不能为空");
}
string jsCode = context.Request.GetParameter("jsCode").ToString();
var wechatSession = await WeChatHelper.GetWechatSession(_configuration, jsCode);
var person = (await _personRepository.GetQueryableAsync()).Where(o => o.WechatOpenId == wechatSession.OpenId).FirstOrDefault();
var wechatUser = new WechatUserDto();
var principal = new ClaimsPrincipal();
var claimsIdentity = new ClaimsIdentity(OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
var scopes = context.Request.GetScopes();
var resources = await GetResourcesAsync(scopes);
if (person == null)
{
wechatUser.IsNewUser = "Y";
wechatUser.OpenId = wechatSession.OpenId;
return Ok(wechatUser);
}
//var user = (await _identityUserRepository.GetQueryableAsync()).Where(o => o.UserName == "admin").FirstOrDefault();
var user = (await _identityUserRepository.GetQueryableAsync()).Where(o => o.Id == person.PersonId).FirstOrDefault();
if (user == null)
{
throw new Exception("用户不存在");
}
if (!user.IsActive)
using (var unitOfWork = _unitOfWorkManager.Begin(requiresNew: true, isTransactional: false))
{
throw new Exception("用户已被禁用");
}
principal = await SignInManager.CreateUserPrincipalAsync(user);
if (principal == null)
{
throw new Exception("principal不能为空");
}
var claim = new Claim("IsNewUser", "N");
principal.Identities.First().AddClaim(claim);
principal.Identities.First().AddClaim(new Claim("WeChatOpenId", wechatSession.OpenId));
//确保只有授权的应用程序才能够调用
var httpClient = new HttpClient();
var request = new ClientCredentialsTokenRequest
{
Address = _configuration["AuthServer:Authority"] + "/connect/token",
GrantType = OpenIddictConstants.GrantTypes.ClientCredentials,
ClientId = context.Request.GetParameter("client_id").ToString(),
ClientSecret = context.Request.GetParameter("client_secret").ToString(),
};
var clientCredentialsResult = await httpClient.RequestClientCredentialsTokenAsync(request);
if (clientCredentialsResult.IsError)
{
throw new Exception("应用程序没有权限" + clientCredentialsResult.ErrorDescription);
}
if (context.Request.GetParameter("jsCode") == null)
{
throw new Exception("jsCode不能为空");
}
string jsCode = context.Request.GetParameter("jsCode").ToString();
var wechatSession = await WeChatHelper.GetWechatSession(_configuration, jsCode);
var person = (await _personRepository.GetQueryableAsync()).Where(o => o.WechatOpenId == wechatSession.OpenId).FirstOrDefault();
var wechatUser = new WechatUserDto();
var claimsIdentity = new ClaimsIdentity(OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
var scopes = context.Request.GetScopes();
var resources = await GetResourcesAsync(scopes);
if (person == null)
{
wechatUser.IsNewUser = "Y";
wechatUser.OpenId = wechatSession.OpenId;
return Ok(wechatUser);
}
//var user = (await _identityUserRepository.GetQueryableAsync()).Where(o => o.UserName == "admin").FirstOrDefault();
var user = (await _identityUserRepository.GetQueryableAsync()).Where(o => o.Id == person.PersonId).FirstOrDefault();
if (user == null)
{
throw new Exception("用户不存在");
}
if (!user.IsActive)
{
throw new Exception("用户已被禁用");
}
principal = await SignInManager.CreateUserPrincipalAsync(user);
if (principal == null)
{
throw new Exception("principal不能为空");
}
var claim = new Claim("IsNewUser", "N");
principal.Identities.First().AddClaim(claim);
principal.Identities.First().AddClaim(new Claim("WeChatOpenId", wechatSession.OpenId));
if (scopes == null || !scopes.Any())
{
throw new Exception("scopes不能为空");
}
if (resources == null || !resources.Any())
{
throw new Exception("resources不能为空");
}
principal.SetScopes(scopes);
principal.SetResources(resources);
principal.SetDestinations(static claim =>
claim.Type switch
{
// If the "profile" scope was granted, allow the "name" claim to be
// added to the access and identity tokens derived from the principal.
Claims.Name when claim.Subject.HasScope(Scopes.Profile) =>
[
OpenIddictConstants.Destinations.AccessToken,
OpenIddictConstants.Destinations.IdentityToken
],
// Never add the "secret_value" claim to access or identity tokens.
// In this case, it will only be added to authorization codes,
// refresh tokens and user/device codes, that are always encrypted.
"preferred_username" => [],
"AspNet.Identity.SecurityStamp" => [],
"phone_number" => [],
"phone_number_verified" => [],
"email_verified" => [],
"unique_name" => [],
"role" => [],
"given_name" => [],
"client_id" => [],
"oi_tkn_id" => [],
"oi_prst" => [],
// Otherwise, add the claim to the access tokens only.
_ => [OpenIddictConstants.Destinations.AccessToken]
});
// await _unitOfWorkManager.Current.CompleteAsync();
if (scopes == null || !scopes.Any())
{
throw new Exception("scopes不能为空");
}
await unitOfWork.CompleteAsync();
if (resources == null || !resources.Any())
{
throw new Exception("resources不能为空");
}
principal.SetScopes(scopes);
principal.SetResources(resources);
principal.SetDestinations(static claim =>
claim.Type switch
{
// If the "profile" scope was granted, allow the "name" claim to be
// added to the access and identity tokens derived from the principal.
Claims.Name when claim.Subject.HasScope(Scopes.Profile) =>
[
OpenIddictConstants.Destinations.AccessToken,
OpenIddictConstants.Destinations.IdentityToken
],
// Never add the "secret_value" claim to access or identity tokens.
// In this case, it will only be added to authorization codes,
// refresh tokens and user/device codes, that are always encrypted.
"preferred_username" => [],
"AspNet.Identity.SecurityStamp" => [],
"phone_number" => [],
"phone_number_verified" => [],
"email_verified" => [],
"unique_name" => [],
"role" => [],
"given_name" => [],
"client_id" => [],
"oi_tkn_id" => [],
"oi_prst" => [],
// Otherwise, add the claim to the access tokens only.
_ => [OpenIddictConstants.Destinations.AccessToken]
});
await _unitOfWorkManager.Current.CompleteAsync();
var authenticationProperties = new AuthenticationProperties();
using (var unitOfWork = _unitOfWorkManager.Begin(requiresNew: true, isTransactional: false))

Loading…
Cancel
Save