thilim9
thilim9

Reputation: 307

ASP.NET MVC Entra login Request.IsAuthenticated return false even after a successful login

I am using Microsoft owin cookie based authentication for ASP.NET form based authentication and it will return IsAuthenticated=true. But when I use owin authentication for get authenticated from Entra. When the authentication get success it will return the user details but still the IsAuthenticated value is returning false.

public partial class Startup
{
    private static string clientId = ConfigurationManager.AppSettings["AzureAd:ClientId"];
    private static string tenant = ConfigurationManager.AppSettings["AzureAd:TenantId"];
    private static string clientSecret = ConfigurationManager.AppSettings["AzureAd:ClientSecret"];
    private static string authority = $"https://login.microsoftonline.com/common/v2.0";

    private static string redirectUri = ConfigurationManager.AppSettings["AzureAd:RedirectUri"];

    private static string returnUri = ConfigurationManager.AppSettings["AzureAd:ReturnUri"];
    private static string graphScopes = ConfigurationManager.AppSettings["AzureAd:AppScope"];

    public void ConfigureAuth(IAppBuilder app)
    {
        try
        {
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new Microsoft.Owin.PathString("/Account/Login"),
                Provider = new CookieAuthenticationProvider
                {
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                }
            });

            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));
            app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);
            
            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                ClientId = clientId,
                Authority = authority,
                Scope = $"openid email profile offline_access User.Read Calendars.Read",
                RedirectUri = redirectUri,
                PostLogoutRedirectUri = redirectUri,
                
                TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true,
                    IssuerValidator = (issuer, token, tvp) =>
                    {
                        return issuer;
                    }
                },
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    AuthenticationFailed = OnAuthenticationFailedAsync,
                    AuthorizationCodeReceived = OnAuthorizationCodeReceivedAsync
                }
            });

            var cookieOptions = new CookieAuthenticationOptions();
            cookieOptions.CookieManager = new SystemWebCookieManager();
            app.UseCookieAuthentication(cookieOptions);
        }
        catch (Exception ex)
        {
            Logger.Log($"/Home/Error?debug={ex.Message}");
            throw ex;
        }
    }

    private async Task OnAuthorizationCodeReceivedAsync(AuthorizationCodeReceivedNotification notification)
    {
        notification.HandleCodeRedemption();

        var idClient = ConfidentialClientApplicationBuilder.Create(clientId)
            .WithRedirectUri(redirectUri)
            .WithClientSecret(clientSecret)
            .Build();

        var signedInUser = new ClaimsPrincipal(notification.AuthenticationTicket.Identity);
        HttpContext context = HttpContext.Current;
        var tokenStore = new SessionTokenStore(idClient.UserTokenCache, context, signedInUser);

        try
        {
            string[] scopes = graphScopes.Split(' ');

            var result = await idClient.AcquireTokenByAuthorizationCode(
                scopes, notification.Code).ExecuteAsync();

            var userDetails = await GraphHelper.GetUserDetailsAsync(result.AccessToken);

            tokenStore.SaveUserDetails(userDetails);
            notification.HandleCodeRedemption(null, result.IdToken);

        }
        catch (MsalException ex)
        {
            string message = "AcquireTokenByAuthorizationCodeAsync threw an exception";
            notification.HandleResponse();
            Logger.Log($"/Home/Error?message={message}&debug={ex.Message}");
            //notification.Response.Redirect($"/Home/Error?message={message}&debug={ex.Message}");
        }
        catch (Microsoft.Graph.ServiceException ex)
        {
            string message = "GetUserDetailsAsync threw an exception";
            notification.HandleResponse();
            Logger.Log($"/Home/Error?message={message}&debug={ex.Message}");
            //notification.Response.Redirect($"/Home/Error?message={message}&debug={ex.Message}");
        }
    }

    private static Task OnAuthenticationFailedAsync(AuthenticationFailedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> notification)
    {
        notification.HandleResponse();
        string redirect = $"/Home/Error?message={notification.Exception.Message}";

        if (notification.ProtocolMessage != null && 
            !string.IsNullOrEmpty(notification.ProtocolMessage.ErrorDescription))
        {
            redirect += $"&debug={notification.ProtocolMessage.ErrorDescription}";
        }

        notification.Response.Redirect(redirect);

        return Task.FromResult(0);
    }
}

Upvotes: 0

Views: 22

Answers (0)

Related Questions