Skip to content

Commit

Permalink
Remove roles from IAuthenticationContext, API and IAuthorizationClient (
Browse files Browse the repository at this point in the history
  • Loading branch information
martinothamar authored Feb 24, 2025
1 parent e2df6b4 commit 999b431
Show file tree
Hide file tree
Showing 12 changed files with 6 additions and 546 deletions.
65 changes: 0 additions & 65 deletions src/Altinn.App.Api/Controllers/AuthorizationController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
using Altinn.App.Core.Configuration;
using Altinn.App.Core.Features.Auth;
using Altinn.App.Core.Internal.Auth;
using Authorization.Platform.Authorization.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
Expand Down Expand Up @@ -152,68 +151,4 @@ public async Task<IActionResult> ValidateSelectedParty(int userId, int partyId)
return StatusCode(500, $"Something went wrong when trying to validate party {partyId} for user {userId}");
}
}

/// <summary>
/// Fetches roles for current party.
/// </summary>
/// <returns>List of roles for the current user and party.</returns>
// [Authorize]
// [HttpGet("{org}/{app}/api/authorization/roles")]
// [ProducesResponseType(typeof(IEnumerable<Role), StatusCodes.Status200OK)]
// [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status400BadRequest)]
[Authorize]
[HttpGet("{org}/{app}/api/authorization/roles")]
[ProducesResponseType(typeof(IEnumerable<Role>), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> GetRolesForCurrentParty()
{
var context = _authenticationContext.Current;
switch (context)
{
case Authenticated.None:
return Unauthorized();
case Authenticated.User user:
{
var details = await user.LoadDetails(validateSelectedParty: true);
if (details.CanRepresent is not bool canRepresent)
throw new Exception("Couldn't validate selected party");
if (!canRepresent)
{
// automatically switch to the user's own party
var reportee = details.Profile.Party;
if (user.SelectedPartyId != reportee.PartyId)
{
// Setting cookie to partyID of logged in user if it varies from previus value.
Response.Cookies.Append(
_settings.GetAltinnPartyCookieName,
reportee.PartyId.ToString(CultureInfo.InvariantCulture),
new CookieOptions { Domain = _settings.HostName }
);
}
return Unauthorized();
}

return Ok(details.Roles);
}
case Authenticated.SelfIdentifiedUser:
{
return Ok(Array.Empty<Role>());
}
case Authenticated.Org:
{
return Ok(Array.Empty<Role>());
}
case Authenticated.ServiceOwner:
{
return Ok(Array.Empty<Role>());
}
case Authenticated.SystemUser:
{
// NOTE: system users can't have Altinn 2 roles, but they will get support for tilgangspakker, as of 26.01.2025
return Ok(Array.Empty<Role>());
}
default:
throw new Exception($"Unknown authentication context: {context.GetType().Name}");
}
}
}
17 changes: 2 additions & 15 deletions src/Altinn.App.Core/Features/Auth/Authenticated.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
using Altinn.Platform.Profile.Models;
using Altinn.Platform.Register.Models;
using AltinnCore.Authentication.Constants;
using Authorization.Platform.Authorization.Models;

namespace Altinn.App.Core.Features.Auth;

Expand Down Expand Up @@ -125,7 +124,6 @@ public sealed class User : Authenticated
private readonly Func<int, Task<Party?>> _lookupParty;
private readonly Func<int, Task<List<Party>?>> _getPartyList;
private readonly Func<int, int, Task<bool?>> _validateSelectedParty;
private readonly Func<int, int, Task<IEnumerable<Role>>> _getUserRoles;
private readonly ApplicationMetadata _appMetadata;

internal User(
Expand All @@ -143,7 +141,6 @@ internal User(
Func<int, Task<Party?>> lookupParty,
Func<int, Task<List<Party>?>> getPartyList,
Func<int, int, Task<bool?>> validateSelectedParty,
Func<int, int, Task<IEnumerable<Role>>> getUserRoles,
ApplicationMetadata appMetadata
)
: base(tokenIssuer, tokenIsExchanged, scopes, token)
Expand All @@ -158,7 +155,6 @@ ApplicationMetadata appMetadata
_lookupParty = lookupParty;
_getPartyList = getPartyList;
_validateSelectedParty = validateSelectedParty;
_getUserRoles = getUserRoles;
_appMetadata = appMetadata;
}

Expand All @@ -174,7 +170,6 @@ ApplicationMetadata appMetadata
/// <param name="RepresentsSelf">True if the user represents itself (user party will equal selected party)</param>
/// <param name="Parties">List of parties the user can represent</param>
/// <param name="PartiesAllowedToInstantiate">List of parties the user can instantiate as</param>
/// <param name="Roles">List of roles the user has</param>
/// <param name="CanRepresent">True if the user can represent the selected party. Only set if details were loaded with validateSelectedParty set to true</param>
public sealed record Details(
Party UserParty,
Expand All @@ -183,7 +178,6 @@ public sealed record Details(
bool RepresentsSelf,
IReadOnlyList<Party> Parties,
IReadOnlyList<Party> PartiesAllowedToInstantiate,
IReadOnlyList<Role> Roles,
bool? CanRepresent = null
)
{
Expand Down Expand Up @@ -305,8 +299,6 @@ await _getUserProfile(UserId)
canRepresent = await _validateSelectedParty(UserId, SelectedPartyId);
}

var roles = await _getUserRoles(UserId, SelectedPartyId);

var partiesAllowedToInstantiate = InstantiationHelper.FilterPartiesByAllowedPartyTypes(
parties,
_appMetadata.PartyTypesAllowed
Expand All @@ -319,7 +311,6 @@ await _getUserProfile(UserId)
representsSelf,
parties,
partiesAllowedToInstantiate,
roles.ToArray(),
canRepresent
);
return _extra;
Expand Down Expand Up @@ -706,8 +697,7 @@ internal static Authenticated FromLocalTest(
Func<int, Task<Party?>> lookupUserParty,
Func<string, Task<Party>> lookupOrgParty,
Func<int, Task<List<Party>?>> getPartyList,
Func<int, int, Task<bool?>> validateSelectedParty,
Func<int, int, Task<IEnumerable<Role>>> getUserRoles
Func<int, int, Task<bool?>> validateSelectedParty
)
{
if (string.IsNullOrWhiteSpace(tokenStr))
Expand Down Expand Up @@ -828,7 +818,6 @@ Func<int, int, Task<IEnumerable<Role>>> getUserRoles
lookupUserParty,
getPartyList,
validateSelectedParty,
getUserRoles,
appMetadata
);
}
Expand All @@ -842,8 +831,7 @@ internal static Authenticated From(
Func<int, Task<Party?>> lookupUserParty,
Func<string, Task<Party>> lookupOrgParty,
Func<int, Task<List<Party>?>> getPartyList,
Func<int, int, Task<bool?>> validateSelectedParty,
Func<int, int, Task<IEnumerable<Role>>> getUserRoles
Func<int, int, Task<bool?>> validateSelectedParty
)
{
if (string.IsNullOrWhiteSpace(tokenStr))
Expand Down Expand Up @@ -1056,7 +1044,6 @@ Func<int, int, Task<IEnumerable<Role>>> getUserRoles
lookupUserParty,
getPartyList,
validateSelectedParty,
getUserRoles,
appMetadata
);
}
Expand Down
6 changes: 2 additions & 4 deletions src/Altinn.App.Core/Features/Auth/AuthenticationContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,7 @@ public Authenticated Current
_altinnPartyClient.GetParty,
(string orgNr) => _altinnPartyClient.LookupParty(new PartyLookup { OrgNo = orgNr }),
_authorizationClient.GetPartyList,
_authorizationClient.ValidateSelectedParty,
_authorizationClient.GetUserRoles
_authorizationClient.ValidateSelectedParty
);
}
else
Expand All @@ -91,8 +90,7 @@ public Authenticated Current
_altinnPartyClient.GetParty,
(string orgNr) => _altinnPartyClient.LookupParty(new PartyLookup { OrgNo = orgNr }),
_authorizationClient.GetPartyList,
_authorizationClient.ValidateSelectedParty,
_authorizationClient.GetUserRoles
_authorizationClient.ValidateSelectedParty
);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,6 @@ partial class Telemetry
return activity;
}

internal Activity? StartClientGetPartyRoleListActivity(int userId, int partyId)
{
var activity = ActivitySource.StartActivity($"{Prefix}.GetUserRoles");
activity?.SetUserPartyId(partyId);
activity?.SetUserId(userId);

return activity;
}

internal Activity? StartClientValidateSelectedPartyActivity(int userId, int partyId)
{
var activity = ActivitySource.StartActivity($"{Prefix}.ValidateSelectedParty");
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
using System.Net;
using System.Net.Http.Headers;
using System.Security.Claims;
using Altinn.App.Core.Configuration;
Expand All @@ -14,7 +13,6 @@
using Altinn.Platform.Register.Models;
using Altinn.Platform.Storage.Interface.Models;
using AltinnCore.Authentication.Utils;
using Authorization.Platform.Authorization.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
Expand Down Expand Up @@ -181,52 +179,4 @@ List<string> actions
}
return MultiDecisionHelper.ValidatePdpMultiDecision(actionsResult, response.Response, user);
}

/// <summary>
/// Retrieves roles for a user on a specified party.
/// </summary>
/// <param name="userId">The user id.</param>
/// <param name="userPartyId">The user party id.</param>
/// <returns>A list of roles for the user on the specified party.</returns>
public async Task<IEnumerable<Role>> GetUserRoles(int userId, int userPartyId)
{
using var activity = _telemetry?.StartClientGetPartyRoleListActivity(userId, userPartyId);

List<Role> roles = new();
string apiUrl = $"roles?coveredByUserId={userId}&offeredByPartyId={userPartyId}";
string token = JwtTokenUtil.GetTokenFromContext(_httpContextAccessor.HttpContext, _settings.RuntimeCookieName);

try
{
HttpResponseMessage response = await _client.GetAsync(token, apiUrl);
if (response.StatusCode == HttpStatusCode.NotFound)
return roles;

if (response.IsSuccessStatusCode)
{
string responseContent = await response.Content.ReadAsStringAsync();
var deserialized = JsonConvert.DeserializeObject<List<Role>>(responseContent);
if (deserialized is not null)
{
roles = deserialized;
}
}
else
{
throw new Exception("Unexpected response from auth API:" + response.StatusCode);
}
}
catch (Exception ex)
{
_logger.LogError(
ex,
"An error occurred while retrieving roles for userId {UserId} and partyId {PartyId}",
userId,
userPartyId
);
throw;
}

return roles;
}
}
9 changes: 0 additions & 9 deletions src/Altinn.App.Core/Internal/Auth/IAuthorizationClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
using Altinn.App.Core.Models;
using Altinn.Platform.Register.Models;
using Altinn.Platform.Storage.Interface.Models;
using Authorization.Platform.Authorization.Models;

namespace Altinn.App.Core.Internal.Auth;

Expand Down Expand Up @@ -51,12 +50,4 @@ Task<bool> AuthorizeAction(
/// <param name="actions"></param>
/// <returns></returns>
Task<Dictionary<string, bool>> AuthorizeActions(Instance instance, ClaimsPrincipal user, List<string> actions);

/// <summary>
/// Retrieves roles for a user on a specified party.
/// </summary>
/// <param name="userId">The user id.</param>
/// <param name="userPartyId">The user party id.</param>
/// <returns>A list of roles for the user on the specified party.</returns>
Task<IEnumerable<Role>> GetUserRoles(int userId, int userPartyId);
}
13 changes: 0 additions & 13 deletions test/Altinn.App.Api.Tests/Mocks/AuthorizationMock.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
using Altinn.App.Core.Models;
using Altinn.Platform.Register.Models;
using Altinn.Platform.Storage.Interface.Models;
using Authorization.Platform.Authorization.Models;

namespace Altinn.App.Api.Tests.Mocks;

Expand Down Expand Up @@ -70,16 +69,4 @@ List<string> actions

return authorizedActions;
}

public async Task<IEnumerable<Role>> GetUserRoles(int userId, int userPartyId)
{
await Task.CompletedTask;
List<Role> roles = new List<Role>
{
new Role { Type = "altinn", Value = "bobet" },
new Role { Type = "altinn", Value = "bobes" },
};

return roles;
}
}
Loading

0 comments on commit 999b431

Please sign in to comment.