Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added tracing to the userprofile controller #1068

Merged
merged 2 commits into from
Oct 14, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 61 additions & 0 deletions Apps/Common/src/Utils/JsonClaimConverter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
//-------------------------------------------------------------------------
// Copyright © 2019 Province of British Columbia
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//-------------------------------------------------------------------------

namespace HealthGateway.Common.Utils
{
using System;
using System.Security.Claims;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

/// <summary>
/// JsonConvert implementation that can handle Claim objects.
/// </summary>
public class JsonClaimConverter : JsonConverter
{
/// <inheritdoc />
public override bool CanConvert(Type objectType)
{
return objectType == typeof(Claim);
}

/// <inheritdoc />
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var claim = (Claim)value;
JObject jo = new JObject();
jo.Add("Type", claim.Type);
jo.Add("Value", claim.Value);
jo.Add("ValueType", claim.ValueType);
jo.Add("Issuer", claim.Issuer);
jo.Add("OriginalIssuer", claim.OriginalIssuer);
jo.WriteTo(writer);
}

/// <inheritdoc />
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JObject jo = JObject.Load(reader);
string type = (string)jo["Type"];
JToken token = jo["Value"];
string value = token.Type == JTokenType.String ? (string)token : token.ToString(Formatting.None);
string valueType = (string)jo["ValueType"];
string issuer = (string)jo["Issuer"];
string originalIssuer = (string)jo["OriginalIssuer"];
return new Claim(type, value, valueType, issuer, originalIssuer);
}
}
}
68 changes: 68 additions & 0 deletions Apps/Common/src/Utils/JsonClaimsIdentityConverter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
//-------------------------------------------------------------------------
// Copyright © 2019 Province of British Columbia
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//-------------------------------------------------------------------------

namespace HealthGateway.Common.Utils
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

/// <summary>
/// JsonConvert implementation that can handle ClaimsIdentity objects.
/// </summary>
public class JsonClaimsIdentityConverter : JsonConverter
{
/// <inheritdoc />
public override bool CanConvert(Type objectType)
{
return typeof(ClaimsIdentity) == objectType;
}

/// <inheritdoc />
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var jObject = JObject.Load(reader);
var claims = jObject[nameof(ClaimsIdentity.Claims)].ToObject<IEnumerable<Claim>>(serializer);
var authenticationType = (string)jObject[nameof(ClaimsIdentity.AuthenticationType)];
var nameClaimType = (string)jObject[nameof(ClaimsIdentity.NameClaimType)];
var roleClaimType = (string)jObject[nameof(ClaimsIdentity.RoleClaimType)];
return new ClaimsIdentity(claims, authenticationType, nameClaimType, roleClaimType);
}

/// <inheritdoc />
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var claimsIdentity = (ClaimsIdentity)value;
var jObject = new JObject
{
{ nameof(ClaimsIdentity.AuthenticationType), claimsIdentity.AuthenticationType },
{ nameof(ClaimsIdentity.IsAuthenticated), claimsIdentity.IsAuthenticated },
{ nameof(ClaimsIdentity.Actor), claimsIdentity.Actor == null ? null : JObject.FromObject(claimsIdentity.Actor, serializer) },
{ nameof(ClaimsIdentity.BootstrapContext), claimsIdentity.BootstrapContext == null ? null : JObject.FromObject(claimsIdentity.BootstrapContext, serializer) },
{ nameof(ClaimsIdentity.Claims), new JArray(claimsIdentity.Claims.Select(x => JObject.FromObject(x, serializer))) },
{ nameof(ClaimsIdentity.Label), claimsIdentity.Label },
{ nameof(ClaimsIdentity.Name), claimsIdentity.Name },
{ nameof(ClaimsIdentity.NameClaimType), claimsIdentity.NameClaimType },
{ nameof(ClaimsIdentity.RoleClaimType), claimsIdentity.RoleClaimType },
};

jObject.WriteTo(writer);
}
}
}
57 changes: 57 additions & 0 deletions Apps/Common/src/Utils/JsonClaimsPrincipalConverter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
//-------------------------------------------------------------------------
// Copyright © 2019 Province of British Columbia
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//-------------------------------------------------------------------------

namespace HealthGateway.Common.Utils
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

/// <summary>
/// JsonConvert implementation that can handle ClaimsPrincipal objects.
/// </summary>
public class JsonClaimsPrincipalConverter : JsonConverter
{
/// <inheritdoc />
public override bool CanConvert(Type objectType)
{
return typeof(ClaimsPrincipal) == objectType;
}

/// <inheritdoc />
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var jObject = JObject.Load(reader);
var identities = jObject[nameof(ClaimsPrincipal.Identities)].ToObject<IEnumerable<ClaimsIdentity>>(serializer);
return new ClaimsPrincipal(identities);
}

/// <inheritdoc />
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var claimsPrincipal = (ClaimsPrincipal)value;
var jObject = new JObject
{
{ nameof(ClaimsPrincipal.Identities), new JArray(claimsPrincipal.Identities.Select(x => JObject.FromObject(x, serializer))) },
};

jObject.WriteTo(writer);
}
}
}
13 changes: 13 additions & 0 deletions Apps/WebClient/src/Server/Controllers/UserProfileController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,16 @@ namespace HealthGateway.WebClient.Controllers
using System.Threading.Tasks;
using HealthGateway.Common.AccessManagement.Authorization.Policy;
using HealthGateway.Common.Models;
using HealthGateway.Common.Utils;
using HealthGateway.Database.Models;
using HealthGateway.WebClient.Models;
using HealthGateway.WebClient.Services;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;

/// <summary>
/// Web API to handle user profile interactions.
Expand All @@ -39,6 +42,7 @@ namespace HealthGateway.WebClient.Controllers
[ApiController]
public class UserProfileController
{
private readonly ILogger logger;
private readonly IUserProfileService userProfileService;
private readonly IHttpContextAccessor httpContextAccessor;
private readonly IUserEmailService userEmailService;
Expand All @@ -47,16 +51,19 @@ public class UserProfileController
/// <summary>
/// Initializes a new instance of the <see cref="UserProfileController"/> class.
/// </summary>
/// <param name="logger">The service Logger.</param>
/// <param name="userProfileService">The injected user profile service.</param>
/// <param name="httpContextAccessor">The injected http context accessor provider.</param>
/// <param name="userEmailService">The injected user email service.</param>
/// <param name="userSMSService">The injected user sms service.</param>
public UserProfileController(
ILogger<UserProfileController> logger,
IUserProfileService userProfileService,
IHttpContextAccessor httpContextAccessor,
IUserEmailService userEmailService,
IUserSMSService userSMSService)
{
this.logger = logger;
this.userProfileService = userProfileService;
this.httpContextAccessor = httpContextAccessor;
this.userEmailService = userEmailService;
Expand Down Expand Up @@ -109,6 +116,12 @@ public async Task<IActionResult> CreateUserProfile(string hdid, [FromBody] Creat
public IActionResult GetUserProfile(string hdid)
{
ClaimsPrincipal user = this.httpContextAccessor.HttpContext.User;
var jsonSettings = new JsonSerializerSettings()
{
Converters = new List<JsonConverter>() { new JsonClaimConverter(), new JsonClaimsPrincipalConverter(), new JsonClaimsIdentityConverter() },
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So why do we need all of this?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

unfortunately the claims serialization is not done by default (no default converters can do it). So these custom converters do the job.

Similar issues: codekoenig/AspNetCore.Identity.DocumentDb#22

};

this.logger.LogTrace($"HTTP context user: {JsonConvert.SerializeObject(user, jsonSettings)}");
string rowAuthTime = user.FindFirst(c => c.Type == "auth_time").Value;

// Auth time at comes in the JWT as seconds after 1970-01-01
Expand Down