/// <summary>
        /// 存储Session对象
        /// </summary>
        /// <param name="sessionObject">session对象</param>
        /// <returns></returns>
        public static async Task StoreSessionAsync(AuthSession sessionObject)
        {
            if (sessionObject == null)
            {
                throw new ArgumentNullException(nameof(sessionObject));
            }
            string subjectId = sessionObject.GetSubjectId();

            if (string.IsNullOrWhiteSpace(subjectId))
            {
                throw new Exception("authentication subject is null or empty");
            }
            string sessionId = sessionObject.SessionId;

            if (string.IsNullOrWhiteSpace(sessionId))
            {
                throw new Exception("session key is null or empty");
            }
            var sessionConfig = SessionConfig.GetSessionConfig();
            var nowDate       = DateTimeOffset.Now;
            var expiresDate   = nowDate.Add(sessionConfig.Expires);

            sessionObject.Expires = expiresDate;
            var expiresSeconds = Convert.ToInt64((expiresDate - nowDate).TotalSeconds);
            await CacheManager.StringSetAsync(new StringSetRequest()
            {
                CacheObject = GetCacheObject(),
                DataItems   = new List <KeyItem>()
                {
                    new KeyItem()
                    {
                        Key          = sessionId,
                        Value        = subjectId,
                        SetCondition = CacheWhen.Always,
                        Seconds      = expiresSeconds
                    },
                    new KeyItem()
                    {
                        Key          = subjectId,
                        Value        = JsonSerialize.ObjectToJson(sessionObject),
                        Seconds      = expiresSeconds,
                        SetCondition = CacheWhen.Always
                    }
                }
            }).ConfigureAwait(false);
        }
Example #2
0
        public static AuthenticationBuilder AddUnityClientAuthentication(this IServiceCollection services, Action <UnityAuthenticationClientOption> optionConfiguration = null)
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }
            var clientOption = new UnityAuthenticationClientOption();

            #region 默认授权配置

            var unityAuthConfig = ContainerManager.Resolve <IOptions <UnityAuthClientConfig> >()?.Value;
            if (unityAuthConfig != null)
            {
                clientOption.CredentialVerifyUrl       = unityAuthConfig.CredentialVerifyUrl;
                clientOption.ClearDefaultInboundClaim  = unityAuthConfig.ClearDefaultInboundClaim;
                clientOption.ClearDefaultOutboundClaim = unityAuthConfig.ClearDefaultOutboundClaim;
            }
            var applicationConfig = ContainerManager.Resolve <IOptions <ApplicationConfig> >()?.Value;
            optionConfiguration?.Invoke(clientOption);
            var builder = services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultSignInScheme       = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = OpenIdConnectDefaults.AuthenticationScheme;
                clientOption?.AuthenticationConfiguration?.Invoke(options);
            });
            if (clientOption.ClearDefaultInboundClaim)
            {
                JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
            }
            if (clientOption.ClearDefaultOutboundClaim)
            {
                JwtSecurityTokenHandler.DefaultOutboundClaimTypeMap.Clear();
            }

            #endregion

            #region Cookie认证配置

            Action <CustomCookieOption> cookieDefaultConfiguration = options =>
            {
                options.ForceValidatePrincipal = true;
                options.ValidatePrincipalAsync = UnityAuthecticationClientUtil.VerifyCredentialAsync;
            };
            if (clientOption.CookieConfiguration != null)
            {
                cookieDefaultConfiguration += clientOption.CookieConfiguration;
            }
            builder.AddCookieAuthentication(cookieDefaultConfiguration);

            #endregion

            #region OpenIdConnect Authentication

            var sessionConfig = SessionConfig.GetSessionConfig();
            Action <OpenIdConnectOptions> defaultOpenIdConnectConfiguration = openIdOptions =>
            {
                openIdOptions.ClientId                                = applicationConfig?.Current?.AppCode ?? string.Empty;
                openIdOptions.ClientSecret                            = applicationConfig?.Current?.AppSecret ?? string.Empty;
                openIdOptions.Authority                               = unityAuthConfig?.UnityServer ?? string.Empty;
                openIdOptions.RequireHttpsMetadata                    = false;
                openIdOptions.ResponseType                            = OpenIdConnectResponseType.CodeIdTokenToken;
                openIdOptions.SaveTokens                              = true;
                openIdOptions.GetClaimsFromUserInfoEndpoint           = true;
                openIdOptions.TokenValidationParameters.NameClaimType = JwtClaimTypes.Name;
                openIdOptions.Scope.Add(sessionConfig.SessionClaimName);
                openIdOptions.ClaimActions.MapUniqueJsonKey(sessionConfig.SessionClaimName, sessionConfig.SessionClaimName);
            };
            if (clientOption.OpenIdConnectConfiguration != null)
            {
                defaultOpenIdConnectConfiguration += clientOption.OpenIdConnectConfiguration;
            }
            builder.AddOpenIdConnect(defaultOpenIdConnectConfiguration);

            #endregion

            if (optionConfiguration != null)
            {
                builder.Services.Configure(Constants.UnityAuthenticationScheme, optionConfiguration);
            }
            return(builder);
        }