using System; using System.Collections.Concurrent; using System.Configuration; using System.Security.Claims; using System.Threading.Tasks; using Abp.Dependency; using Abp.Extensions; using Abp.Owin; using IwbZero.Authorization; using Microsoft.Owin; using Microsoft.Owin.Security; using Microsoft.Owin.Security.Cookies; using Microsoft.Owin.Security.Infrastructure; using Microsoft.Owin.Security.OAuth; using Owin; using ShwasherSys; using ShwasherSys.Api.Controllers; using ShwasherSys.Authorization.Users; using ShwasherSys.Authorization; using IwbZero.Authorization.Permissions; using ShwasherSys.BaseSysInfo; using IwbZero.Session; using System.Globalization; using System.Net; [assembly: OwinStartup(typeof(Startup))] namespace ShwasherSys { public class Startup { public void Configuration(IAppBuilder app) { app.UseAbp(); app.UseOAuthBearerAuthentication(AccountController.OAuthBearerOptions); var logInManager = IocManager.Instance.Resolve(); app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions() { AllowInsecureHttp = true, AuthenticationMode = AuthenticationMode.Active, TokenEndpointPath = new PathString("/token"), //获取 access_token 授权服务请求地址 AuthorizeEndpointPath = new PathString("/authorize"), //获取 authorization_code 授权服务请求地址 AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30), //access_token 过期时间 Provider = new OpenAuthorizationServerProvider(logInManager), //access_token 相关授权服务 RefreshTokenProvider = new OpenRefreshTokenProvider() //refresh_token 授权服务 }); app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = ShwasherConsts.AuthenticationTypes, LoginPath = new PathString("/Account/Login"), // 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 ExpireTimeSpan = new TimeSpan(int.Parse(ConfigurationManager.AppSettings["AuthSession.ExpireTimeInDays.WhenPersistent"] ?? "14"), 0, 0, 0), SlidingExpiration = bool.Parse(ConfigurationManager.AppSettings["AuthSession.SlidingExpirationEnabled"] ?? bool.FalseString) }); app.MapSignalR(); //app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); //ENABLE TO USE HANGFIRE dashboard (Requires enabling Hangfire in IwbYueWebModule) //app.UseHangfireDashboard("/hangfire", new DashboardOptions //{ // Authorization = new[] { new AbpHangfireAuthorizationFilter() } //You can remove this line to disable authorization //}); } } public class OpenRefreshTokenProvider : AuthenticationTokenProvider { private static ConcurrentDictionary _refreshTokens = new ConcurrentDictionary(); /// /// 生成 refresh_token /// public override void Create(AuthenticationTokenCreateContext context) { context.Ticket.Properties.IssuedUtc = DateTime.UtcNow; context.Ticket.Properties.ExpiresUtc = DateTime.UtcNow.AddDays(60); context.SetToken(Guid.NewGuid().ToString("n") + Guid.NewGuid().ToString("n")); _refreshTokens[context.Token] = context.SerializeTicket(); } /// /// 由 refresh_token 解析成 access_token /// public override void Receive(AuthenticationTokenReceiveContext context) { if (_refreshTokens.TryGetValue(context.Token, out string ticketData)) { context.DeserializeTicket(ticketData); } } } public class OpenAuthorizationServerProvider : OAuthAuthorizationServerProvider { public LogInManager LogInManager { get; set; } public OpenAuthorizationServerProvider(LogInManager logInManager) { LogInManager = logInManager; } /// /// 验证 client 信息 /// public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context) { // if (context.ClientId == null) // { // context.Validated(); // } context.Validated(); return Task.CompletedTask; } /// /// 生成 access_token(resource owner password credentials 授权方式) /// public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" }); // var user = context.OwinContext.Authentication.User; // var identity = new ClaimsIdentity(context.Options.AuthenticationType); // identity.AddClaim(new Claim(ClaimTypes.Name, user.Identity.Name)); //获取用户传入的用户名和密码 string username = context.UserName; string password = context.Password; var loginResult = await LogInManager.LoginAsync(username, password); if (loginResult.Result != AbpLoginResultType.Success) { context.SetError("invalid_grant", "用户名或密码不正确"); return; } var identity = loginResult.Identity; identity.AddClaim(new Claim(IwbClaimTypes.RememberMe, "true")); identity.AddClaim(new Claim(ShwasherConsts.UserDepartmentIdClaimType, loginResult.User.DepartmentID ?? "")); var expiresUtc = DateTimeOffset.UtcNow.AddMinutes(int.Parse( System.Configuration.ConfigurationManager.AppSettings[ "AuthSession.ExpireTimeInMinutes"] ?? "90")); identity.AddClaim(new Claim(IwbClaimTypes.ExpireTime, expiresUtc.ToString(CultureInfo.InvariantCulture))); context.Validated(loginResult.Identity); } } }