简体   繁体   中英

Adding claims with profile service in Identity server causing looping in the authentication process

I have a custom Profile service to add the claim to the access_token as below

public class ProfileService : IProfileService
    {
        private readonly IUserClaimsPrincipalFactory<ApplicationUser> _claimsFactory;
        private readonly UserManager<ApplicationUser> _userManager;

        public ProfileService(UserManager<ApplicationUser> userManager,
            IUserClaimsPrincipalFactory<ApplicationUser> claimsFactory)
        {
            _userManager = userManager;
            _claimsFactory = claimsFactory;
        }

        public async Task GetProfileDataAsync(ProfileDataRequestContext context)
        {
            var sub = context.Subject.GetSubjectId();
        var user = await _userManager.FindByIdAsync(sub);
        
        var claims = new List<Claim>();
        
        var userClaims = await _userManager.GetClaimsAsync(user);
        foreach(var userClaim in userClaims)
        {
            claims.Add(new Claim(userClaim.Type, userClaim.Value));
        }
        context.IssuedClaims.AddRange(claims);
        }

        public async Task IsActiveAsync(IsActiveContext context)
        {
            var sub = context.Subject.GetSubjectId();
            var user = await _userManager.FindByIdAsync(sub);
            context.IsActive = user != null;
        }
    }

With the below code I am registering the profile server in Identity server 4/4.1.1

services.AddIdentityServer(options =>
                {
                    options.Events.RaiseErrorEvents = true;
                    options.Events.RaiseInformationEvents = true;
                    options.Events.RaiseFailureEvents = true;
                    options.Events.RaiseSuccessEvents = true;
                    options.EmitStaticAudienceClaim = true;
                }) .AddProfileService<ProfileService>()

When I register a ProfileService the UI is looping, I am using PCKE with authorization flow.If I remove the ProfileService everything works fine.

I need the profile service because I am adding a custom claim to the access_token

app.UseRouting();

    app.UseAuthentication();
    app.UseIdentityServer();
    app.UseAuthorization();
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller}/{action=Index}/{id?}");
        endpoints.MapRazorPages();
    });

One thing is that you should not add app.UseAuthentication(); in your startup class, instead it should look like this:

app.UseIdentityServer(); app.UseAuthorization();

UseIdentityServer adds UseAthentication when called, so no need to call it twice.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM