protected async Task <HttpResponseMessage> CreateItemAsync <TValidator>(HttpRequestMessage httpRequestMessage)
            where TValidator : AbstractValidator <T>, new()
        {
            _ = httpRequestMessage ?? throw new ArgumentNullException(nameof(httpRequestMessage));

            var claimsPrincipal = await tokenValidator.ValidateTokenAsync(httpRequestMessage.Headers.Authorization);

            if (claimsPrincipal == null)
            {
                return(new HttpResponseMessage(HttpStatusCode.Unauthorized));
            }

            var jsonValidationResult = await jsonHttpContentValidator.ValidateJsonAsync <T, TValidator>(httpRequestMessage.Content);

            if (!jsonValidationResult.IsValid)
            {
                return(jsonValidationResult.Message);
            }

            var createdItem = await dataRepository.CreateItemAsync(jsonValidationResult.Item);

            var content = new StringContent(JsonSerializer.Serialize(createdItem), Encoding.UTF8, ContentTypes.Application.Json);

            return(new HttpResponseMessage(HttpStatusCode.Created)
            {
                Content = content
            });
        }
示例#2
0
        public async Task <HttpResponseMessage> CreateCustomer([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "customers")] HttpRequestMessage req, ILogger log)
        {
            _ = req ?? throw new ArgumentNullException(nameof(req));

            log.LogInformation(CustomerDataResources.CreateCustomerStartLog);

            var claimsPrincipal = await tokenValidator.ValidateTokenAsync(req.Headers.Authorization);

            if (claimsPrincipal == null)
            {
                return(new HttpResponseMessage(HttpStatusCode.Unauthorized));
            }

            var jsonValidationResult = await jsonHttpContentValidator.ValidateJsonAsync <Customer, CustomerValidator>(req.Content);

            if (!jsonValidationResult.IsValid)
            {
                return(jsonValidationResult.Message);
            }

            var customer = await customerRepository.CreateItemAsync(jsonValidationResult.Item);

            var content = new StringContent(JsonSerializer.Serialize(customer), Encoding.UTF8, ContentTypes.Application.Json);

            log.LogInformation(CustomerDataResources.CreateCustomerEndLog);
            return(new HttpResponseMessage(HttpStatusCode.Created)
            {
                Content = content
            });
        }
        public async Task <HttpResponseMessage> CreateConferenceCall([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "calls")] HttpRequestMessage req, ILogger log)
        {
            _ = req ?? throw new ArgumentNullException(nameof(req));

            var claimsPrincipal = await tokenValidator.ValidateTokenAsync(req.Headers.Authorization);

            if (claimsPrincipal == null)
            {
                return(new HttpResponseMessage(HttpStatusCode.Unauthorized));
            }

            log.LogInformation("Creating call");
            var contentStream = await req.Content.ReadAsStreamAsync();

            var jsonResult = await jsonTextSerializer.DeserializeObjectAsync <User>(contentStream);

            var onlineMeeting = await microsoftGraphRepository.CreateOnlineMeetingAsync(req.Headers.Authorization);

            jsonResult.MeetingUrl = onlineMeeting.JoinWebUrl;

            var content = new StringContent(JsonSerializer.Serialize(jsonResult), Encoding.UTF8, "application/json");

            log.LogInformation("Created call");
            return(new HttpResponseMessage(HttpStatusCode.Created)
            {
                Content = content
            });;
        }
        public Task <List <KeyValuePair <string, string> > > ProcessAsync(ref TokenExchangeRequest tokenExchangeRequest)
        {
            var header  = new JwtHeader();
            var handler = new JwtSecurityTokenHandler();

            foreach (var tokenWithScheme in tokenExchangeRequest.Tokens)
            {
                var principal = _tokenValidator.ValidateTokenAsync(new TokenDescriptor
                {
                    TokenScheme = tokenWithScheme.TokenScheme,
                    Token       = tokenWithScheme.Token
                }).GetAwaiter().GetResult();

                var token = handler.ReadJwtToken(tokenWithScheme.Token);
                var unsignedSecurityToken = new JwtSecurityToken(header, token.Payload);
                tokenWithScheme.Token = handler.WriteToken(unsignedSecurityToken);
            }
            return(Task.FromResult(new List <KeyValuePair <string, string> >()));
        }
示例#5
0
        public async Task <HttpResponseMessage> CheckAccess([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "checkAccess")] HttpRequestMessage req, ILogger log)
        {
            _ = req ?? throw new ArgumentNullException(nameof(req));

            log.LogInformation(PolicyManagerResources.CheckAccessStartLog);

            var claimsPrincipal = await tokenValidator.ValidateTokenAsync(req.Headers.Authorization);

            if (claimsPrincipal == null)
            {
                return(new HttpResponseMessage(HttpStatusCode.Unauthorized));
            }

            var jsonValidationResult = await jsonHttpContentValidator.ValidateJsonAsync <CheckAccessRequest, CheckAccessRequestValidator>(req.Content);

            if (!jsonValidationResult.IsValid)
            {
                return(jsonValidationResult.Message);
            }

            var groups = await microsoftGraphRepository.FetchMyGroupsAsync(req.Headers.Authorization);

            var initialState = new InitialState <Group>()
            {
                ClaimsPrincipal = claimsPrincipal,
                Identifier      = jsonValidationResult.Item.RequestIdentifier,
                Groups          = groups,
            };

            var policyResults = await authorizationRepository.EvaluateAsync(req.Headers.Authorization, initialState);

            log.LogInformation(PolicyManagerResources.CheckAccessEndLog);

            var content = new StringContent(JsonSerializer.Serialize(policyResults), Encoding.UTF8, ContentTypes.Application.Json);

            return(new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = content
            });
        }
        public async Task <List <TokenExchangeResponse> > ProcessExchangeAsync(TokenExchangeRequest tokenExchangeRequest)
        {
            if (tokenExchangeRequest.Extras == null || tokenExchangeRequest.Extras.Count == 0)
            {
                throw new Exception($"{Name}: We require that extras be populated!");
            }

            List <ValidatedToken> validatedIdentityTokens = new List <ValidatedToken>();

            foreach (var item in tokenExchangeRequest.Tokens)
            {
                var prince = await _tokenValidator.ValidateTokenAsync(new TokenDescriptor
                {
                    TokenScheme = item.TokenScheme,
                    Token       = item.Token
                });

                var sub = prince.GetSubjectFromPincipal();
                if (string.IsNullOrEmpty(sub))
                {
                    _summaryLogger.Add("subject", "A subject was not found in the ClaimsPrincipal object!");
                    throw new Exception("A subject was not found in the ClaimsPrincipal object!");
                }
                validatedIdentityTokens.Add(new ValidatedToken
                {
                    Token       = item.Token,
                    TokenScheme = item.TokenScheme,
                    Principal   = prince
                });
            }

            // for this demo, lets assume all the extras are roles.
            var roles = tokenExchangeRequest.Extras;

            roles.Add("user");


            ResourceOwnerTokenRequest resourceOwnerTokenRequest = new ResourceOwnerTokenRequest()
            {
                AccessTokenLifetime = 3600,
                ArbitraryClaims     = new Dictionary <string, List <string> >()
                {
                    { "role", roles }
                },
                Scope    = "offline_access graphQLPlay",
                Subject  = validatedIdentityTokens[0].Principal.GetSubjectFromPincipal(),
                ClientId = "arbitrary-resource-owner-client"
            };
            var response = await _tokenMintingService.MintResourceOwnerTokenAsync(resourceOwnerTokenRequest);

            if (response.IsError)
            {
                throw new Exception(response.Error);
            }

            var tokenExchangeResponse = new TokenExchangeResponse()
            {
                accessToken = new AccessTokenResponse()
                {
                    access_token  = response.AccessToken,
                    refresh_token = response.RefreshToken,
                    expires_in    = response.ExpiresIn,
                    token_type    = response.TokenType,
                    authority     =
                        $"{_httpContextAssessor.HttpContext.Request.Scheme}://{_httpContextAssessor.HttpContext.Request.Host}",
                    HttpHeaders = new List <HttpHeader>
                    {
                        new HttpHeader()
                        {
                            Name = "x-authScheme", Value = response.Scheme
                        }
                    }
                }
            };

            return(new List <TokenExchangeResponse> {
                tokenExchangeResponse
            });
        }
示例#7
0
        public async Task IssueAsync(OioIdwsMatchEndpointContext context)
        {
            if (string.IsNullOrEmpty(context.Request.ContentType))
            {
                SetInvalidRequest(context, "No content type was specified");
                return;
            }

            var ct = new System.Net.Mime.ContentType(context.Request.ContentType);

            var validContentType = "application/x-www-form-urlencoded";

            if (!ct.MediaType.Equals(validContentType, StringComparison.InvariantCultureIgnoreCase))
            {
                SetInvalidRequest(context, $"Content type '{validContentType}' is required.");
                return;
            }

            var form = await context.Request.ReadFormAsync();

            var tokenValueBase64 = form["saml-token"];

            if (string.IsNullOrEmpty(tokenValueBase64))
            {
                SetInvalidRequest(context, "saml-token was missing");
                return;
            }

            string tokenValue;

            try
            {
                var bytes = Convert.FromBase64String(tokenValueBase64);
                using (var stream = new MemoryStream(bytes))
                {
                    using (var reader = new StreamReader(stream))
                    {
                        tokenValue = await reader.ReadToEndAsync();
                    }
                }
            }
            catch (Exception)
            {
                SetInvalidRequest(context, "saml-token must be in base64");
                return;
            }

            var clientCertificate = context.ClientCertificate();

            _logger.WriteEntry(Log.StartingTokenValidation());
            var samlTokenValidation = await _tokenValidator.ValidateTokenAsync(tokenValue, clientCertificate, context.Options);

            if (!samlTokenValidation.Success)
            {
                _logger.WriteEntry(Log.IssuingTokenDenied(samlTokenValidation.ErrorDescription, samlTokenValidation.ValidationException));

                // Scheme is mandatory and Holder-Of-Key is currently the only supportede scheme at NemLog-in STS. Hence, we specify Holder-Of-Key.
                context.Response.SetAuthenticationFailed(AccessTokenType.HolderOfKey, AuthenticationErrorCodes.InvalidToken, samlTokenValidation.ErrorDescription);
                context.RequestCompleted();
                return;
            }

            _logger.WriteEntry(Log.TokenValidationCompleted());

            var expiresIn = context.Options.AccessTokenExpiration;

            int requestedExpiration;

            if (int.TryParse(form["should-expire-in"], out requestedExpiration))
            {
                var tmp = TimeSpan.FromSeconds(requestedExpiration);

                if (tmp < expiresIn)
                {
                    //if the client wants a lower expiration, that's ok. Never to increase it.
                    expiresIn = tmp;
                }
            }

            var storedToken = new OioIdwsToken
            {
                CertificateThumbprint = samlTokenValidation.AccessTokenType == AccessTokenType.HolderOfKey
                    ? clientCertificate?.Thumbprint?.ToLowerInvariant()
                    : null,
                Type       = samlTokenValidation.AccessTokenType,
                ExpiresUtc = context.Options.SystemClock.UtcNow + expiresIn,
                Claims     = samlTokenValidation.ClaimsIdentity.Claims.Select(x => new OioIdwsClaim
                {
                    Type      = x.Type,
                    Value     = x.Value,
                    Issuer    = x.Issuer,
                    ValueType = x.ValueType
                }).ToList(),
            };

            var accessToken = await GenerateAccessTokenAsync(context, storedToken);

            await WriteAccessTokenAsync(context.Response, accessToken, samlTokenValidation.AccessTokenType, expiresIn);

            _logger.WriteEntry(Log.TokenIssuedWithExpiration(accessToken, expiresIn));

            context.RequestCompleted();
        }
示例#8
0
 public async Task <JsonResult> ValidateToken([FromBody] TokenValidationRequest request)
 {
     return(Json(await authenticator.ValidateTokenAsync(request.token)));
 }