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

Make methods virtual so they can be redefined in derived classes. #13752

Merged
merged 1 commit into from Jan 31, 2023
Merged

Make methods virtual so they can be redefined in derived classes. #13752

merged 1 commit into from Jan 31, 2023

Conversation

jbreuer
Copy link
Contributor

@jbreuer jbreuer commented Jan 27, 2023

Prerequisites

Description

When you're using external login providers you sometimes want to override the MemberManager and MemberSignInManager classes with custom implementations. By making the methods of these classes virtual you can inherit from those classes and only override what you need to.

This is an example of the CustomMemberSignInManager where I override the virtual ExternalLoginSignInAsync method:

using System.Security.Claims;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Umbraco_OpenIdConnect_Example.Core.Extensions;
using Umbraco.Cms.Core.DependencyInjection;
using Umbraco.Cms.Core.Events;
using Umbraco.Cms.Core.Security;
using Umbraco.Cms.Web.Common.Security;

namespace Umbraco_OpenIdConnect_Example.Core.Member;

public class CustomMemberSignInManager : MemberSignInManager
{
    private readonly IMemberManager _memberManager;

    public CustomMemberSignInManager(
        UserManager<MemberIdentityUser> memberManager,
        IHttpContextAccessor contextAccessor,
        IUserClaimsPrincipalFactory<MemberIdentityUser> claimsFactory,
        IOptions<IdentityOptions> optionsAccessor,
        ILogger<SignInManager<MemberIdentityUser>> logger,
        IAuthenticationSchemeProvider schemes,
        IUserConfirmation<MemberIdentityUser> confirmation,
        IMemberExternalLoginProviders memberExternalLoginProviders,
        IEventAggregator eventAggregator)
        : base(memberManager, contextAccessor, claimsFactory, optionsAccessor, logger, schemes, confirmation)
    {
        _memberManager = (IMemberManager)memberManager;
    }

    [Obsolete("Use ctor with all params")]
    public CustomMemberSignInManager(
        UserManager<MemberIdentityUser> memberManager,
        IHttpContextAccessor contextAccessor,
        IUserClaimsPrincipalFactory<MemberIdentityUser> claimsFactory,
        IOptions<IdentityOptions> optionsAccessor,
        ILogger<SignInManager<MemberIdentityUser>> logger,
        IAuthenticationSchemeProvider schemes,
        IUserConfirmation<MemberIdentityUser> confirmation)
        : this(
            memberManager,
            contextAccessor,
            claimsFactory,
            optionsAccessor,
            logger,
            schemes,
            confirmation,
            StaticServiceProvider.Instance.GetRequiredService<IMemberExternalLoginProviders>(),
            StaticServiceProvider.Instance.GetRequiredService<IEventAggregator>())
    {
    }
    
    public override async Task<SignInResult> ExternalLoginSignInAsync(ExternalLoginInfo loginInfo, bool isPersistent, bool bypassTwoFactor = false)
    {
        // In the default implementation, the member is fetched from the database.
        // The default implementation also tries to create the member with the auto link feature if it doesn't exist.
        // The auto link feature has been removed here because the member is from an external login provider.
        // We just build a virtual member from the external login info.
        var claims = loginInfo.Principal.Claims;
        var id = claims.FirstOrDefault(x => x.Type == "sid")?.Value;
        var user = _memberManager.CreateVirtualUser(id, loginInfo.Principal.Claims);
        
        // For now hard code the role. These could be claims from the external login provider.
        user.Claims.Add(new IdentityUserClaim<string>() { ClaimType = ClaimTypes.Role, ClaimValue = "example-group" });

        return await SignInOrTwoFactorAsync(user, isPersistent, loginInfo.LoginProvider, bypassTwoFactor);
    }
}

@github-actions
Copy link

github-actions bot commented Jan 27, 2023

Hi there @jbreuer, thank you for this contribution! 👍

While we wait for one of the Core Collaborators team to have a look at your work, we wanted to let you know about that we have a checklist for some of the things we will consider during review:

  • It's clear what problem this is solving, there's a connected issue or a description of what the changes do and how to test them
  • The automated tests all pass (see "Checks" tab on this PR)
  • The level of security for this contribution is the same or improved
  • The level of performance for this contribution is the same or improved
  • Avoids creating breaking changes; note that behavioral changes might also be perceived as breaking
  • If this is a new feature, Umbraco HQ provided guidance on the implementation beforehand
  • 💡 The contribution looks original and the contributor is presumably allowed to share it

Don't worry if you got something wrong. We like to think of a pull request as the start of a conversation, we're happy to provide guidance on improving your contribution.

If you realize that you might want to make some changes then you can do that by adding new commits to the branch you created for this work and pushing new commits. They should then automatically show up as updates to this pull request.

Thanks, from your friendly Umbraco GitHub bot 🤖 🙂

@mikecp mikecp changed the base branch from v11/contrib to contrib January 29, 2023 19:31
@jbreuer
Copy link
Contributor Author

jbreuer commented Jan 30, 2023

@mikecp Thanks for approving this PR. Can this be merged before the 11.2 RC is out? Thanks.

@nul800sebastiaan
Copy link
Member

Currently discussing is this would be a breaking change - according to https://learn.microsoft.com/en-us/dotnet/core/compatibility/library-change-rules#members it is:

❌ DISALLOWED: Adding the virtual keyword to a member
While this often is not a breaking change because the C# compiler tends to emit callvirt Intermediate Language (IL) instructions to call non-virtual methods (callvirt performs a null check, while a normal call doesn't), this behavior is not invariable for several reasons:
C# is not the only language that .NET targets.
The C# compiler increasingly tries to optimize callvirt to a normal call whenever the target method is non-virtual and is probably not null (such as a method accessed through the ?. null propagation operator).
Making a method virtual means that the consumer code would often end up calling it non-virtually.

But not sure if we need to worry about that.

@mikecp
Copy link
Contributor

mikecp commented Jan 31, 2023

Thanks for the precision @nul800sebastiaan !
And apologies @jbreuer, I should have mentioned that breaking change questioning point earlier.

@nul800sebastiaan
Copy link
Member

After some testing, turns out it wouldn't affect us! 👍

Thanks @jbreuer!🎖️

jbreuer added a commit to jbreuer/Umbraco-OpenIdConnect-Example that referenced this pull request Feb 24, 2023
@nul800sebastiaan
Copy link
Member

Cherry picked for 10.5 in 815eb5b

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

3 participants