abp icon indicating copy to clipboard operation
abp copied to clipboard

Setup external Identity with Identityserver 4 and azure active directory

Open rlavaud opened this issue 6 years ago • 4 comments

Hi all. I am trying to setup a simple project to use Azure active directory and I am hitting a road block. I got the button to show up in the login page, I can login on azure then I simply get redirected to the login page again. Upon further investigation I can see that the loginModel.OnGetExternalLoginCallbackAsync SignInManager.GetExternalLoginInfoAsync().ConfigureAwait(false) always return null.

I have a very simple setup in configure authentication

context.Services.AddAuthentication() .AddIdentityServerAuthentication(options => { options.Authority = configuration["AuthServer:Authority"]; options.RequireHttpsMetadata = false; options.ApiName = "TestAzAd"; }); context.Services .AddOpenIdConnect("Azure AD / Microsoft", "Azure AD / Microsoft", options => // Microsoft common { // https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration options.ClientId = "XXXXXXXXXXX"; options.ClientSecret = "YYYYYYYYYYYY"; options.SignInScheme = "Identity.External"; options.RemoteAuthenticationTimeout = TimeSpan.FromSeconds(30); options.Authority = "https://login.microsoftonline.com/ZZZZZZZZZZZ/v2.0/"; options.ResponseType = "code"; options.Scope.Add("profile"); options.Scope.Add("email"); options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = false, NameClaimType = "email", }; options.CallbackPath = "/signin-oidc"; options.Prompt = "login"; // login, consent });

I my mind this should work. What am I missing?

I also would like to auto provision my user in .netcore Identity. For example, once I login via Azure AD, create the local user to use abpuser throughout the application.

rlavaud avatar Jan 10 '20 12:01 rlavaud

I got it to work. For the benefit of everyone here is the cause of the issue and the solution (at least my solution)

When using Azure AD V2 openid connect we get a few claims back (sub, email, name) SignInManager.GetExternalLoginInfoAsyn looks the the ClaimTypes.NameIdentifier which is not returned by Azure AD Since the SignInManager cannot find the identifier in the claim list, it returns null.

My Solution is to map the claim ClaimTypes.NameIdentifier to the value of the sub claim in .AddOpenIdConnect

                 options.Events = new OpenIdConnectEvents
                 {
                     OnTokenValidated = async ctx =>
                     {
                         //Get user's immutable object id from claims that came from Azure AD
                         string sub = ctx.Principal.FindFirstValue("sub");

                         //Add claim if they are
                         var claims = new List<Claim>
                        {
                            new Claim(ClaimTypes.NameIdentifier, sub)
                        };
                         var appIdentity = new ClaimsIdentity(claims);

                         ctx.Principal.AddIdentity(appIdentity);
                     }
                 };


             });

Now you still need to create a local account and map the account with a login.

If someone has a more elegant solution please let me know.

rlavaud avatar Jan 12 '20 09:01 rlavaud

@rlavaud You can use mapping on .AddOpenIdConnect options after clearing the default mapping with JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); This post of leastprivilege might help if you didn't notice.

If you want to pass your Claims from ExternalIdentity to your localIdentity principal, you can use create a ClaimsPrincipalFactory by inheriting UserClaimsPrincipalFactory<TUser,TRole>.

Something like;

public class MyUserClaimsPrincipalFactory : UserClaimsPrincipalFactory<AppUser>
    {
        private readonly IServiceProvider _serviceProvider;
        private readonly ILogger _logger;

        public SsoUserClaimsPrincipalFactory(
            ILoggerFactory loggerFactory,
            UserManager<AppUser> userManager,
            IOptions<IdentityOptions> optionsAccessor,
            IServiceProvider serviceProvider
            )
            : base(userManager, optionsAccessor)
        {
            _logger = loggerFactory.CreateLogger<MyUserClaimsPrincipalFactory >();
            _serviceProvider = serviceProvider;
        }
        protected override async Task<ClaimsIdentity> GenerateClaimsAsync(AppUser user)
        {
            var signinManager = _serviceProvider.GetRequiredService<SignInManager<AppUser>>();
            var info = await signinManager.GetExternalLoginInfoAsync();
            try
            {
                _logger.LogInformation($"Generating claims for user {user.UserName}");
                var identity = await base.GenerateClaimsAsync(user);
                if (info == null)
                {
                      //Add claims from signinManager
                }
                else
                {
                     //Map and add claims
                }
                return identity;
            }
            catch (Exception)
            {
                _logger.LogError($"Error when creating user claims for user {user.UserName}");
                throw;
            }
        }
    }

You can inject any other service aswell.

gterdem avatar Jan 16 '20 10:01 gterdem

@rlavaud @gterdem Do any of you have a final working example on how to implement AAD into ABP? Thanks in advance

Znow avatar Feb 12 '20 16:02 Znow

@Znow It's pretty straight forward with AAD. If you stuck at some point, create a new issue explaining it, we'll try to help.

gterdem avatar Feb 12 '20 18:02 gterdem