MVC 4, Framework, Custom Authorize Roles, Hybrid Authentication - Authorize Not working

Marlo Hutchinson 26 Reputation points
2022-08-03T16:27:27.373+00:00

Hi there,

I tried to research this on my own and I can't find a solution. I have a web application that authenticates against Azure AD. See startup below. I have created a customAuthorize that's worked until I updated my Nuget references. I don't understand how to troubleshoot from here. Can someone help? Thanks! I feel like a totally newbie again.

Here's what I know

  1. I'm prompted and able to successfully log into the application; (see homecontroller).
  2. In CUSTOMAUTHORIZE, currentUser = user.Identity.Name; returns an empty string.
  3. In CUSTOMAUTHORIZE, if I comment out, if (!user.Identity.IsAuthenticated), in the HOME VIEW, captures all my logged-in attributes, e.g., my name, preferred_username, (see HOME VIEW in how it's aquired).
  4. Since I see that I am authenticated, I'm just unsure, and don't understand enough to research, or back out certain updates.

** HOME VIEW**
@if (!Request.IsAuthenticated)
{
<!-- If the user is not authenticated, display the sign-in button -->
<a href="@URL .Action("SignIn", "Home")" style="text-decoration: none;">
<svg xmlns="" xml:space="preserve" width="300px" height="50px" viewBox="0 0 3278 522" class="SignInButton">
<style type="text/css">
.fil0:hover {
fill: #4B4B4B;
}

        .fnt0 {  
            font-size: 260px;  
            font-family: 'Segoe UI Semibold', 'Segoe UI';  
            text-decoration: none;  
        }  

</style>
<rect class="fil0" x="2" y="2" width="3174" height="517" fill="black" />
<rect x="150" y="129" width="122" height="122" fill="#F35325" />
<rect x="284" y="129" width="122" height="122" fill="#81BC06" />
<rect x="150" y="263" width="122" height="122" fill="#05A6F0" />
<rect x="284" y="263" width="122" height="122" fill="#FFBA08" />
<text x="470" y="357" fill="white" class="fnt0">Sign in with Microsoft</text>
</svg>
</a>
}
else
{
<div id="content_wrapper">
<div id="content" class="w1000">
<div class="patient-section k-content">
<div style="clear: both;">

                <span><br />Hello @System.Security.Claims.ClaimsPrincipal.Current.FindFirst("name").Value</span><br />  
                <label><strong>User Account:</strong> </label> @ViewBag.AuthenticatedUser <br />  
                <label><strong>Assigned Role:</strong> </label> @ViewBag.CurrentRole<br />  
                <label><strong>Assigned Clinic Name:</strong> </label> @ViewBag.ClinicName (@ViewBag.AssignedClinicID)  

            </div>  
        </div>  
    </div>  
</div>  

**HOMECONTROLLER **
public class HomeController : Controller
{

    public ActionResult Index()  
    {  
        return View();  
    }  

    /// <summary>  
    /// Send an OpenID Connect sign-in request.  
    /// Alternatively, you can just decorate the SignIn method with the [Authorize] attribute  
    /// </summary>  
    public void SignIn()  
    {  
        if (!Request.IsAuthenticated)  
        {  
            HttpContext.GetOwinContext().Authentication.Challenge(  
                new AuthenticationProperties { RedirectUri = "/" },  
                OpenIdConnectAuthenticationDefaults.AuthenticationType);  
        }  
    }  
    /// <summary>  
    /// Send an OpenID Connect sign-out request.  
    /// </summary>  
    public void SignOut()  
    {  
        HttpContext.GetOwinContext().Authentication.SignOut(  
            OpenIdConnectAuthenticationDefaults.AuthenticationType,  
            CookieAuthenticationDefaults.AuthenticationType);  
    }  

CUSTOMAUTHORIZE
using System;
using System.Configuration;
using System.Threading.Tasks;
using Microsoft.IdentityModel.Logging;
using Microsoft.Owin;
using Owin;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OpenIdConnect;
using Microsoft.Owin.Security.Notifications;
using SaveRecapture.Utils;
public class CustomAuthorize : AuthorizeAttribute
{

    private readonly string[] _allowedRoles;  
    private readonly PatientModel _patientModel = new PatientModel();  
      
      
    public CustomAuthorize(params string[] roles)  
    {  
        this._allowedRoles = roles;  
        }  

     
    protected override bool AuthorizeCore(HttpContextBase httpContext)  
    {  
          
        bool isAuthorized = false;  
          
        string currentUserRole = string.Empty;  

        var  user = httpContext.User;  
        string currentUser = user.Identity.Name;  
   
        Utility.SetHttpCookie("currentUser", currentUser);  


        if (!user.Identity.IsAuthenticated)  
            return false;  
         
        Utility.SetHttpCookie("Roles", string.Join(",", _allowedRoles));  
          
        //get user role  
        currentUserRole = GetRolesByUserName(currentUser);  
        if (string.IsNullOrEmpty(currentUserRole))  
        {  
            Utility.SetHttpCookie("CurrentUserRole", "You have not been assigned a role.");  
            Utility.SetHttpCookie("ClinicName", "You have not been assigned a clinic.");  
            return isAuthorized;  
        }  
        
        Utility.SetHttpCookie("CurrentUserRole", currentUserRole);  

STARTUP
public partial class Startup
{
private static readonly string ClientId = ConfigurationManager.AppSettings["ida:ClientId"];

    private static readonly string RedirectUri = ConfigurationManager.AppSettings["ida:RedirectUri"];  

    static readonly string TenantId = ConfigurationManager.AppSettings["ida:TenantId"];  

    readonly string _authority = String.Format(System.Globalization.CultureInfo.InvariantCulture, ConfigurationManager.AppSettings["Authority"], TenantId);  

    /// <summary>  
    ///   
    /// </summary>  
    /// <param name="app"></param>  
    public void ConfigureAuth(IAppBuilder app)  
    {  
        IdentityModelEventSource.ShowPII = true;  

        //shows the authentication error  
        //IdentityModelEventSource.ShowPII = true;  
        app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);  
        app.UseCookieAuthentication(new CookieAuthenticationOptions());  
        app.UseOpenIdConnectAuthentication(  
            new OpenIdConnectAuthenticationOptions  
            {  
                ClientId = ClientId,  
                Authority = _authority,  
                RedirectUri = RedirectUri,  

                PostLogoutRedirectUri = RedirectUri,  
                Scope = OpenIdConnectScope.OpenIdProfile,  
                ResponseType = OpenIdConnectResponseType.CodeIdToken,  
                Notifications = new OpenIdConnectAuthenticationNotifications  
                {  
                    AuthenticationFailed = OnAuthenticationFailedAsync,  
                },  
            }  
        );  
    }  


    private Task OnAuthenticationFailedAsync(AuthenticationFailedNotification<OpenIdConnectMessage,  
      OpenIdConnectAuthenticationOptions> context)  
    {  
        context.HandleResponse();  
        context.Response.Redirect("/Error?message=" + context.Exception.Message);  
        return Task.FromResult(0);  
    }  
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,289 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Marlo Hutchinson 26 Reputation points
    2022-08-03T20:52:52.27+00:00

    I figured it out. I needed to enable authentication under App Services; followed the directions to the attached link, and then it worked.
    https://learn.microsoft.com/en-us/azure/app-service/configure-authentication-provider-aad

    0 comments No comments