Startup.cs 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Configuration;
  4. using System.Security.Claims;
  5. using System.Threading.Tasks;
  6. using Abp.Dependency;
  7. using Abp.Extensions;
  8. using Abp.Owin;
  9. using IwbZero.Authorization;
  10. using Microsoft.Owin;
  11. using Microsoft.Owin.Security;
  12. using Microsoft.Owin.Security.Cookies;
  13. using Microsoft.Owin.Security.Infrastructure;
  14. using Microsoft.Owin.Security.OAuth;
  15. using Owin;
  16. using ShwasherSys;
  17. using ShwasherSys.Api.Controllers;
  18. using ShwasherSys.Authorization.Users;
  19. using ShwasherSys.Authorization;
  20. using IwbZero.Authorization.Permissions;
  21. using ShwasherSys.BaseSysInfo;
  22. using IwbZero.Session;
  23. using System.Globalization;
  24. using System.Net;
  25. [assembly: OwinStartup(typeof(Startup))]
  26. namespace ShwasherSys
  27. {
  28. public class Startup
  29. {
  30. public void Configuration(IAppBuilder app)
  31. {
  32. app.UseAbp();
  33. app.UseOAuthBearerAuthentication(AccountController.OAuthBearerOptions);
  34. var logInManager = IocManager.Instance.Resolve<LogInManager>();
  35. app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions()
  36. {
  37. AllowInsecureHttp = true,
  38. AuthenticationMode = AuthenticationMode.Active,
  39. TokenEndpointPath = new PathString("/token"), //获取 access_token 授权服务请求地址
  40. AuthorizeEndpointPath = new PathString("/authorize"), //获取 authorization_code 授权服务请求地址
  41. AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30), //access_token 过期时间
  42. Provider = new OpenAuthorizationServerProvider(logInManager), //access_token 相关授权服务
  43. RefreshTokenProvider = new OpenRefreshTokenProvider() //refresh_token 授权服务
  44. });
  45. app.UseCookieAuthentication(new CookieAuthenticationOptions
  46. {
  47. AuthenticationType = ShwasherConsts.AuthenticationTypes,
  48. LoginPath = new PathString("/Account/Login"),
  49. // by setting following values, the auth cookie will expire after the configured amount of time (default 14 days) when user set the (IsPermanent == true) on the login
  50. ExpireTimeSpan = new TimeSpan(int.Parse(ConfigurationManager.AppSettings["AuthSession.ExpireTimeInDays.WhenPersistent"] ?? "14"), 0, 0, 0),
  51. SlidingExpiration = bool.Parse(ConfigurationManager.AppSettings["AuthSession.SlidingExpirationEnabled"] ?? bool.FalseString)
  52. });
  53. app.MapSignalR();
  54. //app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
  55. //ENABLE TO USE HANGFIRE dashboard (Requires enabling Hangfire in IwbYueWebModule)
  56. //app.UseHangfireDashboard("/hangfire", new DashboardOptions
  57. //{
  58. // Authorization = new[] { new AbpHangfireAuthorizationFilter() } //You can remove this line to disable authorization
  59. //});
  60. }
  61. }
  62. public class OpenRefreshTokenProvider : AuthenticationTokenProvider
  63. {
  64. private static ConcurrentDictionary<string, string> _refreshTokens = new ConcurrentDictionary<string, string>();
  65. /// <summary>
  66. /// 生成 refresh_token
  67. /// </summary>
  68. public override void Create(AuthenticationTokenCreateContext context)
  69. {
  70. context.Ticket.Properties.IssuedUtc = DateTime.UtcNow;
  71. context.Ticket.Properties.ExpiresUtc = DateTime.UtcNow.AddDays(60);
  72. context.SetToken(Guid.NewGuid().ToString("n") + Guid.NewGuid().ToString("n"));
  73. _refreshTokens[context.Token] = context.SerializeTicket();
  74. }
  75. /// <summary>
  76. /// 由 refresh_token 解析成 access_token
  77. /// </summary>
  78. public override void Receive(AuthenticationTokenReceiveContext context)
  79. {
  80. if (_refreshTokens.TryGetValue(context.Token, out string ticketData))
  81. {
  82. context.DeserializeTicket(ticketData);
  83. }
  84. }
  85. }
  86. public class OpenAuthorizationServerProvider : OAuthAuthorizationServerProvider
  87. {
  88. public LogInManager LogInManager { get; set; }
  89. public OpenAuthorizationServerProvider(LogInManager logInManager)
  90. {
  91. LogInManager = logInManager;
  92. }
  93. /// <summary>
  94. /// 验证 client 信息
  95. /// </summary>
  96. public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
  97. {
  98. // if (context.ClientId == null)
  99. // {
  100. // context.Validated();
  101. // }
  102. context.Validated();
  103. return Task.CompletedTask;
  104. }
  105. /// <summary>
  106. /// 生成 access_token(resource owner password credentials 授权方式)
  107. /// </summary>
  108. public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
  109. {
  110. context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
  111. // var user = context.OwinContext.Authentication.User;
  112. // var identity = new ClaimsIdentity(context.Options.AuthenticationType);
  113. // identity.AddClaim(new Claim(ClaimTypes.Name, user.Identity.Name));
  114. //获取用户传入的用户名和密码
  115. string username = context.UserName;
  116. string password = context.Password;
  117. var loginResult = await LogInManager.LoginAsync(username, password);
  118. if (loginResult.Result != AbpLoginResultType.Success)
  119. {
  120. context.SetError("invalid_grant", "用户名或密码不正确");
  121. return;
  122. }
  123. var identity = loginResult.Identity;
  124. identity.AddClaim(new Claim(IwbClaimTypes.RememberMe, "true"));
  125. identity.AddClaim(new Claim(ShwasherConsts.UserDepartmentIdClaimType, loginResult.User.DepartmentID ?? ""));
  126. var expiresUtc = DateTimeOffset.UtcNow.AddMinutes(int.Parse(
  127. System.Configuration.ConfigurationManager.AppSettings[
  128. "AuthSession.ExpireTimeInMinutes"] ?? "90"));
  129. identity.AddClaim(new Claim(IwbClaimTypes.ExpireTime, expiresUtc.ToString(CultureInfo.InvariantCulture)));
  130. context.Validated(loginResult.Identity);
  131. }
  132. }
  133. }