123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176 |
- using Microsoft.AspNetCore.Authentication;
- using Microsoft.AspNetCore.Authorization;
- using Microsoft.AspNetCore.Http;
- using Microsoft.AspNetCore.Http.Features;
- using Microsoft.Extensions.Logging;
- using Microsoft.Extensions.Options;
- using System.Net.Http.Headers;
- using System.Security.Claims;
- using System.Text.Encodings.Web;
- using XYY.Core.Standard.Data.Infrastructure;
- using XYY.Core.Standard.Mvc;
- public class BasicAuthenticationHandler : AuthenticationHandler<BasicAuthenticationOption>
- {
-
- private readonly IUnitOfWork unitOfWork;
- public BasicAuthenticationHandler(
- IOptionsMonitor<BasicAuthenticationOption> options,
- ILoggerFactory logger,
- UrlEncoder encoder,
- ISystemClock clock,
- IUnitOfWork unitOfWork)
- : base(options, logger, encoder, clock)
- {
- this.unitOfWork = unitOfWork;
- }
- public Endpoint? GetEndpoint(HttpContext context)
- {
- if (context == null)
- {
- return null;
- }
- return context.Features.Get<IEndpointFeature>()?.Endpoint;
- }
- /// <summary>
- /// 认证 Token
- /// </summary>
- /// <returns></returns>
- protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
- {
- bool isAllow = false;
- var endpoint = GetEndpoint(this.Context);
- if (endpoint != null)
- {
- var allow = endpoint.Metadata.GetMetadata<IAllowAnonymous>();
- if (allow != null)
- {
- isAllow = true;
- }
- }
- if (isAllow || Request.Path.Value.Contains("dingtalk") || Request.Path.Value.Contains("SendNowCustomerQuotaion", StringComparison.InvariantCultureIgnoreCase))
- {
- var claims = new[]
- {
- new Claim(ClaimTypes.StreetAddress,""),
- };
- var identity = new ClaimsIdentity(claims, Scheme.Name);
- var principal = new ClaimsPrincipal(identity);
- var ticket = new AuthenticationTicket(principal, Scheme.Name);
- unitOfWork.CurrentName = "";
- return await Task.FromResult(AuthenticateResult.Success(ticket));
- }
- if (!Request.Headers.ContainsKey("Authorization"))
- {
- if (string.IsNullOrEmpty(Request.Query["access_token"]))
- {
- return AuthenticateResult.Fail("Missing Authorization ");
- }
- }
- try
- {
- string token = "";
- //var uservice = Context.RequestServices.GetService<IUserService>();
- if (Request.Headers.ContainsKey("Authorization"))
- {
- var authHeader = AuthenticationHeaderValue.Parse(Request.Headers["Authorization"]);
- //var credentialBytes = Convert.FromBase64String(authHeader.Parameter);
- if (!authHeader.Scheme.Equals("token", StringComparison.InvariantCultureIgnoreCase)
- && !authHeader.Scheme.Equals("bearer", StringComparison.InvariantCultureIgnoreCase))
- {
- return AuthenticateResult.Fail("Invalid Token");
- }
- else
- {
- token = authHeader.Parameter;
- }
- }
- else
- {
- token = Request.Query["access_token"];
- }
- var user = await Authorized(token);
- if (user != null)
- {
- ///当前用户的身份信息
- var claims = new[]
- {
- new Claim(ClaimTypes.NameIdentifier,user.Id.ToString()),
- new Claim(ClaimTypes.Name,user.Name),
- new Claim(ClaimTypes.StreetAddress,token),
- new Claim(ClaimTypes.GivenName,user.CustomeCompanyName??""),
- new Claim(ClaimTypes.GroupSid,user.CustomerId.ToString()),
- new Claim(ClaimTypes.Role,string.Join(",",user.RoleNames)),
- new Claim(ClaimTypes.AuthorizationDecision,string.Join(",",user.Permissions.Select(x=>x.Url)))
- };
- var identity = new ClaimsIdentity(claims, Scheme.Name);
- var principal = new ClaimsPrincipal(identity);
- var ticket = new AuthenticationTicket(principal, Scheme.Name);
- unitOfWork.CurrentName = user.Name;
- unitOfWork.CurrentId = user.CustomerId;
- return await Task.FromResult(AuthenticateResult.Success(ticket));
- }
- else
- {
- return AuthenticateResult.Fail("token无效");
- }
- }
- catch
- {
- return AuthenticateResult.Fail("Invalid Authorization Header");
- }
- }
- /// <summary>
- /// 质询
- /// </summary>
- /// <param name="properties"></param>
- /// <returns></returns>
- protected override async Task HandleChallengeAsync(AuthenticationProperties properties)
- {
- //Response.Headers["WWW-Authenticate"] = $"Basic realm=our site";
- await base.HandleChallengeAsync(properties);
- }
- /// <summary>
- /// 认证失败
- /// </summary>
- /// <param name="properties"></param>
- /// <returns></returns>
- protected override async Task HandleForbiddenAsync(AuthenticationProperties properties)
- {
- await base.HandleForbiddenAsync(properties);
- }
- private async Task<UserInfo> Authorized(string token)
- {
- System.Net.WebClient client = new System.Net.WebClient();
- client.BaseAddress = "http://120.24.149.148:9500/";
- client.Headers.Add("Content-Type", "application/json; charset=utf-8");
- client.Headers.Add("Authorization", "token 132A7468DE079C6CEB59F383A661E612");
- try
- {
- var response = client.UploadString("/api/auth/GetUserInfoAsToken?token=" + token, "");
- var u = Newtonsoft.Json.JsonConvert.DeserializeObject<ApiJsonModel<UserInfo>>(response);
- if (u.success)
- {
- return u.data;
- }
- else
- {
- throw new Exception("鉴权失败" + u.message);
- }
- }
- catch (Exception ex)
- {
- throw new Exception("登陆失败" + ex.Message);
- }
- }
- }
|