Open Closed

Single Sign On with Azure AD in Angular #5851


User avatar
0
bhasinp created
  • ABP Framework version: v7.2.2
  • UI type: Angular
  • DB provider: EF Core
  • Tiered (MVC) or Identity Server Separated (Angular): yes
  • Exception message and stack trace:
  • Steps to reproduce the issue:"

Hi Team, I have integrated the AzureOpenId auth login.

Using following config in HostModule Registration

.AddOpenIdConnect("AzureOpenId", "Azure AD OpenId", options => { options.Authority = "https://login.microsoftonline.com/" + configuration["AzureAd:TenantId"] + "/v2.0/"; options.ClientId = configuration["AzureAd:ClientId"]; options.ResponseType = OpenIdConnectResponseType.CodeIdToken; options.CallbackPath = configuration["AzureAd:CallbackPath"]; options.ClientSecret = configuration["AzureAd:ClientSecret"]; options.RequireHttpsMetadata = false; options.SaveTokens = true; options.GetClaimsFromUserInfoEndpoint = true; options.Scope.Add("email"); options.ClaimActions.MapJsonKey(ClaimTypes.NameIdentifier, "sub"); options.TokenValidationParameters.ValidateIssuer = false; })

Firstly the "Azure AD OpenId" login button is appearing in backend controller, not in Angular UI.

So I proceed with Backend Api Login page and click on Ad Login, User get signed in correctly and token are validated as well everything looks good. But I want this to be redirected back to angular UI and user should be logged in.

Please help me in configuring the angular in such a way that I can use AD token in angular login.


If I try to use environment config as, responseType: 'code', it always throwing

error:invalid_request error_description:The specified 'redirect_uri' is not valid for this client application. error_uri:https://documentation.openiddict.com/errors/ID204

Thanks


21 Answer(s)
  • User Avatar
    0
    Anjali_Musmade created
    Support Team Support Team Member

    Hello bhasinp, We need to register the app in Azure under "App registration" . then in Authentication under "App registration" tab need to add the Redirect URL

  • User Avatar
    0
    bhasinp created

    I have already configured this,

    Please correct me if I am doing something wrong

  • User Avatar
    0
    Anjali_Musmade created
    Support Team Support Team Member

    We have to configured it at 2 places:

    1. Web redirect URI
    2. Single-page application redirect URI

    In angular environment.ts & environment.prod.ts file. Do you have same url in baseuri which you want to get redirected that should be present in both enviroment.ts & azure ad

  • User Avatar
    0
    bhasinp created

    Here you go

  • User Avatar
    0
    Anjali_Musmade created
    Support Team Support Team Member

    Hello Can you please add url's here without **/redirect **exactly same as your baserUrl in environment.ts & environment.prod.ts files

  • User Avatar
    0
    bhasinp created

    Here is the updated url on azure

    opening the angular app directly redirecting me to following url https://motrv2.com:44368/connect/authorize?response_type=code&client_id=motr_App&state=S0ItQlpicU9MaHZDNUZBdlJjbnF5WEZzdGozR2pQU2NZTW56Znc1Rl81dlZj%3B%252F&redirect_uri=https%3A%2F%2Fmotrv2.com%3A4200&scope=openid%20offline_access%20motr&code_challenge=U3NCIINsueF5kL1NJnM1wOTzVQb9pzg9_9awwybElSo&code_challenge_method=S256&nonce=S0ItQlpicU9MaHZDNUZBdlJjbnF5WEZzdGozR2pQU2NZTW56Znc1Rl81dlZj&culture=en&ui-culture=en&returnUrl=%2F

    giving error

  • User Avatar
    0
    bhasinp created

    We can connect in a remote session if your want.

  • User Avatar
    0
    Anjali_Musmade created
    Support Team Support Team Member

    Can you please try to add that url in RedirectAllowedUrls in appsetting.json of Auth Server

  • User Avatar
    0
    bhasinp created

    Verified this as well and same issue.

  • User Avatar
    0
    Anjali_Musmade created
    Support Team Support Team Member

    Hello can you please add this in redirectUrl of azureAD (Single-page application redirect URI) & in RedirectAllowedUrls in appsetting.json of Auth Server as well https://motrv2.com:44368

  • User Avatar
    0
    bhasinp created

    Just tried this as well, But same issue.

    When we enabled responseType: 'code', does it directly target the azure ad ? or it will first try to go to local api end point ?

    I think its getting stuck at local api redirection not on AD because the api which is throwing error is local not azure ad.

  • User Avatar
    0
    bhasinp created

    If you can join me on a call that could help us to resolve this issue quickly

  • User Avatar
    0
    Anjali_Musmade created
    Support Team Support Team Member

    If you can join me on a call that could help us to resolve this issue quickly

    Apologies but online support is not available. Can you please check this url https://support.abp.io/QA/Questions/5185 And you can cross check this also (admin login) url/4200/openiddict/Applications - edit and can check this url Try to make requireHttps to false in evnroment

  • User Avatar
    0
    bhasinp created

    Hi team, This resolved the issue, Thanks

    But when I navigated back to angular it doesn't load automatically, i.e url/4200 is navigated correctly and is authenticated But I need to click on browser refresh for angular to load correctly.

  • User Avatar
    0
    Anjali_Musmade created
    Support Team Support Team Member

    Hi

    your angular app is authenticated by the authserver not the azure ad the auth server get's the token by azure ad and then azure ad redirects it back to authserver and then authserver redirect is back to angular this is the default working.

    in azure ad you have to add authserver url as a redirect url not the angular one

    if you want the azure ad token in angular app you can save the token inside the cookie

    please see this ticket for more details https://support.abp.io/QA/Questions/5720/PowerBI-Embed-access-token-issue-with-ABP#answer-3a0d816c-f911-fb7f-703b-e50b0c54a4be

    you have to modify Login.cshtml.cs and then get the token from cookie in angular side

  • User Avatar
    0
    bhasinp created

    Thanks for quick reply

    Yes I totally agree its authenticated by authserver, and my authserver is configured with ad, all token related things working well, my local registered users and ad both are getting logged in correclty.

    But the issue is when I get navigated back to angular with either local user auth token or by AD auth token in both of the cases my angular app show blank page, When I hit the browser refresh page then it loads the actual angular app correctly

    Is there anything which I am missing in angular side ?

  • User Avatar
    0
    bhasinp created

    Also when I directly open the authserver login page (not via angular redirection) it show the login page without any client info in url. After auth it navigate me to swagger UI, I changes the redirect Urls for swagger client in openiddict/Applications but still loads the /swagger/index.html after auth, how can I force it to navigate to angular app always in any of the case

  • User Avatar
    0
    Anjali_Musmade created
    Support Team Support Team Member

    Hi

    you can override https://github.com/abpframework/abp/blob/dev/modules/account/src/Volo.Abp.Account.Web/Pages/Account/Login.cshtml.cs and redirect manually to angular

  • User Avatar
    0
    bhasinp created

    Manual redirection to url:4200 is resulting the 4200 redirect back to login screen as 4200 will require auth token as well url:4200/?code=Z7wwL72n7QA2VteW90GLPRCbqm16Fxek6aAAKCDrEi0&state=S0huNWk5QWJaVUhqMVc4aVRmOW5sWWN-NG5kQnJOa3pHb3NXWmxvUUhGeHpW;%252F&iss=https%3A%2F%2Furl.com%3A44368%2F

  • User Avatar
    0
    bhasinp created

    But firstly give me some suggestions why angular route is not loading,

    when app get redirected to angular the app.component.ts file get invoked and I am able to fetch the user information as well, But after that route is not selected and angular end up with blank page.

    I have registered the '' empty route as well but not invoked

  • User Avatar
    0
    Anjali_Musmade created
    Support Team Support Team Member

    Hi

    you can use azure ad token in angular by storing it in the cookie. see the implementation and steps you have to do in this ticket. https://support.abp.io/QA/Questions/5720/PowerBI-Embed-access-token-issue-with-ABP#answer-3a0d816c-f911-fb7f-703b-e50b0c54a4be

    Also in azure ad please specify AuthServer url as Redirect URL not the angular one.

    please override OnGetExternalLoginCallbackAsync the login.cshtml.cs

    and write below code, and the when you are back from login inside angular app just get the token for cookie

    using Jupiter.Web;
    using Microsoft.AspNetCore.Authentication;
    using Microsoft.AspNetCore.Identity;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.Options;
    using Owl.reCAPTCHA;
    using System;
    using System.Linq;
    using System.Threading.Tasks;
    using Volo.Abp.Account.ExternalProviders;
    using Volo.Abp.Account.Public.Web;
    using Volo.Abp.Account.Public.Web.Pages.Account;
    using Volo.Abp.Account.Security.Recaptcha;
    using Volo.Abp.DependencyInjection;
    using Volo.Abp.Security.Claims;
    
    namespace Jupiter.Web.Pages.Account
    {
        [ExposeServices(typeof(LoginModel))]
        [Dependency(ReplaceServices = true)]
        public class AppLoginModel : LoginModel
        {
            private readonly IConfiguration _configuration;
            public AppLoginModel(IAuthenticationSchemeProvider schemeProvider, IOptions< AbpAccountOptions > accountOptions, IAbpRecaptchaValidatorFactory recaptchaValidatorFactory, IAccountExternalProviderAppService accountExternalProviderAppService, ICurrentPrincipalAccessor currentPrincipalAccessor, IOptions< IdentityOptions > identityOptions, IOptionsSnapshot< reCAPTCHAOptions > reCaptchaOptions, IConfiguration configuration) : base(schemeProvider, accountOptions, recaptchaValidatorFactory, accountExternalProviderAppService, currentPrincipalAccessor, identityOptions, reCaptchaOptions)
            {
                _configuration = configuration;
            }
    
            public override async Task< IActionResult > OnGetExternalLoginCallbackAsync(string returnUrl = "", string returnUrlHash = "", string remoteError = null)
            {
                var token = await SignInManager.GetExternalLoginInfoAsync();
                var accessToken = token?.AuthenticationTokens?.FirstOrDefault(x => x.Name == "access_token");
                var powerbi = new PowerBiServiceApi(_configuration, accessToken?.Value ?? string.Empty);
                HttpContext.Response.Cookies.Append("AuthToken", accessToken?.Value ?? string.Empty);
                var report = await powerbi.GetReport(Guid.Parse("workspaceid"), Guid.Parse("reportid"));
                return await base.OnGetExternalLoginCallbackAsync(returnUrl, returnUrlHash, remoteError);
            }
        }
    }
    
    
Made with ❤️ on ABP v9.1.0-preview. Updated on December 13, 2024, 06:09