/// <summary>
        /// Authenticate for the specified authentication scheme.
        /// </summary>
        /// <param name="context">The <see cref="HttpContext"/>.</param>
        /// <param name="scheme">The name of the authentication scheme.</param>
        /// <returns>The result.</returns>
        public virtual async Task <AuthenticateResult> AuthenticateAsync(ClaimsPrincipal principal)
        {
            var sid = principal.FindFirst(claim => claim.Type == ClaimTypes.Sid).Value;
            //根据sid恢复ticket
            var ticket = await Store.RetrieveAsync(sid);

            //如果没有,则失败
            if (ticket == null)
            {
                return(AuthenticateResult.Fail("Identity missing in session store"));
            }

            var currentUtc = Clock.UtcNow;
            var expiresUtc = ticket.Properties.ExpiresUtc;

            if (expiresUtc != null && expiresUtc.Value < currentUtc)
            {
                //过期。。认证失败
                await Store.RemoveAsync(sid);

                return(AuthenticateResult.Fail("Ticket expired"));
            }

            //刷新ticket
            await CheckForRefresh(sid, ticket);

            // Finally we have a valid ticket
            return(AuthenticateResult.Success(ticket));
        }
        public async Task Invoke(HttpContext context)
        {
            if (context.Request.Method.Equals(HttpMethod.Post.Method, StringComparison.OrdinalIgnoreCase))
            {
                var formData = await context.Request.ReadFormAsync(context.RequestAborted).ConfigureAwait(false);

                var logOutRequest = formData.FirstOrDefault(x => x.Key == "logoutRequest").Value[0];
                if (!string.IsNullOrEmpty(logOutRequest))
                {
                    logger.LogDebug($"logoutRequest: {logOutRequest}");
                    var serviceTicket = ExtractSingleSignOutTicketFromSamlResponse(logOutRequest);
                    if (!string.IsNullOrEmpty(serviceTicket))
                    {
                        logger.LogInformation($"remove serviceTicket: {serviceTicket} ...");
                        await store.RemoveAsync(serviceTicket);
                    }
                }
            }
            await next.Invoke(context);
        }
Example #3
0
        public async Task <GrantedToken> Execute(GetTokenViaTicketIdParameter parameter, AuthenticationHeaderValue authenticationHeaderValue, X509Certificate2 certificate, string issuerName)
        {
            // 1. Check parameters.
            if (parameter == null)
            {
                throw new ArgumentNullException(nameof(parameter));
            }

            if (string.IsNullOrWhiteSpace(parameter.Ticket))
            {
                throw new BaseUmaException(ErrorCodes.InvalidRequestCode, string.Format(ErrorDescriptions.TheParameterNeedsToBeSpecified, PostAuthorizationNames.TicketId));
            }

            if (string.IsNullOrWhiteSpace(parameter.Ticket))
            {
                throw new ArgumentNullException(nameof(parameter.Ticket));
            }

            // 2. Try to authenticate the client.
            var instruction = CreateAuthenticateInstruction(parameter, authenticationHeaderValue, certificate);
            var authResult  = await _authenticateClient.AuthenticateAsync(instruction, issuerName);

            var client = authResult.Client;

            if (client == null)
            {
                throw new BaseUmaException(ErrorCodes.InvalidClient, authResult.ErrorMessage);
            }

            if (client.GrantTypes == null || !client.GrantTypes.Contains(GrantType.uma_ticket))
            {
                throw new BaseUmaException(ErrorCodes.InvalidGrant, string.Format(ErrorDescriptions.TheClientDoesntSupportTheGrantType, client.ClientId, GrantType.uma_ticket));
            }

            // 3. Retrieve the ticket.
            var json = JsonConvert.SerializeObject(parameter);

            _umaServerEventSource.StartGettingAuthorization(json);
            var ticket = await _ticketStore.GetAsync(parameter.Ticket);

            if (ticket == null)
            {
                throw new BaseUmaException(ErrorCodes.InvalidTicket, string.Format(ErrorDescriptions.TheTicketDoesntExist, parameter.Ticket));
            }

            // 4. Check the ticket.
            if (ticket.ExpirationDateTime < DateTime.UtcNow)
            {
                throw new BaseUmaException(ErrorCodes.ExpiredTicket, ErrorDescriptions.TheTicketIsExpired);
            }

            _umaServerEventSource.CheckAuthorizationPolicy(json);
            var claimTokenParameter = new ClaimTokenParameter
            {
                Token  = parameter.ClaimToken,
                Format = parameter.ClaimTokenFormat
            };

            // 4. Check the authorization.
            var authorizationResult = await _authorizationPolicyValidator.IsAuthorized(ticket, client.ClientId, claimTokenParameter);

            if (authorizationResult.Type != AuthorizationPolicyResultEnum.Authorized)
            {
                _umaServerEventSource.RequestIsNotAuthorized(json);
                throw new BaseUmaException(ErrorCodes.InvalidGrant, ErrorDescriptions.TheAuthorizationPolicyIsNotSatisfied);
            }

            // 5. Generate a granted token.
            var grantedToken = await GenerateTokenAsync(client, ticket.Lines, "openid", issuerName);

            await _tokenStore.AddToken(grantedToken);

            await _ticketStore.RemoveAsync(ticket.Id);

            return(grantedToken);
        }
        public async Task <GetTokenByTicketIdResponse> Execute(GetTokenViaTicketIdParameter parameter, string openidProvider, string issuerName)
        {
            // 1. Check parameters.
            if (parameter == null)
            {
                throw new ArgumentNullException(nameof(parameter));
            }

            if (string.IsNullOrWhiteSpace(parameter.Ticket))
            {
                throw new BaseUmaException(ErrorCodes.InvalidRequestCode, string.Format(ErrorDescriptions.TheParameterNeedsToBeSpecified, PostAuthorizationNames.TicketId));
            }

            if (string.IsNullOrWhiteSpace(parameter.Ticket))
            {
                throw new ArgumentNullException(nameof(parameter.Ticket));
            }

            if (string.IsNullOrWhiteSpace(openidProvider))
            {
                throw new ArgumentNullException(nameof(openidProvider));
            }

            // 2. Retrieve the ticket.
            var json = JsonConvert.SerializeObject(parameter);

            _umaServerEventSource.StartGettingAuthorization(json);
            var ticket = await _ticketStore.GetAsync(parameter.Ticket).ConfigureAwait(false);

            if (ticket == null)
            {
                throw new BaseUmaException(ErrorCodes.InvalidTicket, string.Format(ErrorDescriptions.TheTicketDoesntExist, parameter.Ticket));
            }

            // 3. Check the ticket.
            if (ticket.ExpirationDateTime < DateTime.UtcNow)
            {
                throw new BaseUmaException(ErrorCodes.ExpiredTicket, ErrorDescriptions.TheTicketIsExpired);
            }

            _umaServerEventSource.CheckAuthorizationPolicy(json);
            var claimTokenParameter = new ClaimTokenParameter
            {
                Token  = parameter.ClaimToken,
                Format = parameter.ClaimTokenFormat
            };

            // 4. Check the authorization.
            var authorizationResult = await _authorizationPolicyValidator.IsAuthorized(openidProvider, ticket, claimTokenParameter).ConfigureAwait(false);

            if (!authorizationResult.IsValid)
            {
                _umaServerEventSource.RequestIsNotAuthorized(json);
                return(new GetTokenByTicketIdResponse
                {
                    IsValid = false,
                    ResourceValidationResult = authorizationResult
                });
            }

            // 5. Generate a granted token.
            var grantedToken = await GenerateTokenAsync(ticket.Audiences, ticket.Lines, "openid", issuerName).ConfigureAwait(false);

            await _tokenStore.AddToken(grantedToken);

            await _ticketStore.RemoveAsync(ticket.Id);

            return(new GetTokenByTicketIdResponse
            {
                IsValid = true,
                GrantedToken = grantedToken
            });
        }