| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152 |
- 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<LogInManager>();
- 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<string, string> _refreshTokens = new ConcurrentDictionary<string, string>();
- /// <summary>
- /// 生成 refresh_token
- /// </summary>
- 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();
- }
- /// <summary>
- /// 由 refresh_token 解析成 access_token
- /// </summary>
- 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;
- }
- /// <summary>
- /// 验证 client 信息
- /// </summary>
- public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
- {
- // if (context.ClientId == null)
- // {
- // context.Validated();
- // }
- context.Validated();
- return Task.CompletedTask;
- }
- /// <summary>
- /// 生成 access_token(resource owner password credentials 授权方式)
- /// </summary>
- 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);
- }
-
- }
- }
|