40

I have a ASP .NET MVC5 application in which I am not using Windows Authentication.

Everything was working fine until I tried running the application outside of the Domain in which it was being developed and (for whatever reason) got a:

The trust relationship between this workstation and the primary domain failed.

when I'm trying to do User.IsInRole("Admin").

I am using custom Identity, Role, IdentityStore, RoleStore, etc. from .NET's Identity and I can see that the User and Role data is being retrieved from the (MongoDB) database correctly.

There are plenty of questions regarding this issue, but they're from people who want to use Windows Auth. and impersonation in their MVC applications:

So why exactly am I getting this SystemException if I'm not using Active Directory and (as far as I know) not doing anything that might depend on the PC's domain? Am I missing some configuration (either in my Web.config or IIS Express)?

EDIT:

Ok, so narrowing it down a bit...

My User.IsInRole("Admin") line is inside an if() statement in my _Layout.cshtml View (i.e., to know what to show in the nav. bar depending on the role).

I now know I only get the error above when no user is authenticated and I'm not in the domain I used for dev. If I place a breakpoint on that line, I can see that the User object is is a System.Security.Principal.WindowsIdentity and its underlying Identity is System.Security.Principal.WindowsIdentity.

On the other hand, if the user is authenticated, then the User object and ts Identity are System.Security.Claims.ClaimsPrincipal and System.Security.Claims.ClaimsIdentity.

Why is it using Windows Identity at all (when unauthenticated) and how can I disable it?

Community
  • 1
  • 1
user1987392
  • 3,921
  • 4
  • 34
  • 59
  • Somewhere, you're still attempting to connect to the domain. Is it possible that `` is in your web.config? – Steven V Mar 31 '14 at 15:42
  • I wish it was that, I've already CTRL+F'd for that and "windows". No luck. – user1987392 Mar 31 '14 at 15:42
  • Is there something in your role provider that depends on Active Directory? – Steven V Mar 31 '14 at 15:46
  • I don't think so. I'm using Microsoft.AspNet.Identity (which has IUser, IUserStore, etc...), Microsoft.Owin.Security, System.Security.Claims... – user1987392 Mar 31 '14 at 15:55
  • Added an EDIT to the question that might help narrowing down the problem. – user1987392 Mar 31 '14 at 16:21
  • Sadly, you're kind of on a wild goose chase. Check the global.asax, and heck the entire solution for any references to `WindowsIdentity` or `Windows` and see if that yields anything. – Steven V Mar 31 '14 at 16:33
  • For @user1987392, but mainly for others with this issue, searching for windows is not sufficient, as [windows is the default mode](http://msdn.microsoft.com/en-us/library/vstudio/532aee0e%28v=vs.100%29.aspx), at least in .Net 4. – R. Schreurs Nov 04 '14 at 12:24
  • FWIW, all of the sudden I found myself unable to log into my EPiServer site using windows credentials. When I switched from from forms authentication to windows, I got this error in the browser. It turned out something must have been corrupted because after re-adding my machine to our domain, it was fixed. – xr280xr Jun 19 '18 at 18:18

11 Answers11

34

So, based on my EDIT, I've modified my _Layout.cshtml so that instead of having

@if(User.IsInRole("Admin"))  {...}

I have

@if(User.Identity.IsAuthenticated && User.IsInRole("Admin")) {...}

which seems to solve the problem.

I believe the problem was that ASP .NET Identity uses an empty WindowsIdentity when no user is authenticated and when I try to check for the User.IsInRole, then it will try to check the roles of a WindowsIdentity against an Active Directory that I don't have. Obviously I should first check if the user is even logged in before attempting to check its roles, so mea culpa.

But, even though the change above seems to fix my code, I'd be very interested in knowing more about this behavior: why is it using an empty System.Security.Principal.WindowsIdentity when no user is authenticated. I'll accept any answer which explains that.

Community
  • 1
  • 1
user1987392
  • 3,921
  • 4
  • 34
  • 59
  • 1
    I ran into a similar issue regarding this. The trust relationship error results from calling `IsInRole('somerole')` when the Claims on the Identity does not contain that role, the Identity is Windows, and that group does not exist in the primary domain, and some trust issue between another domain exists. I never resolved my issue. http://stackoverflow.com/questions/22518243/user-isinrolefake-group-results-in-the-trust-relationship-between-the-prima – JoeBrockhaus Oct 22 '14 at 14:10
  • @JoeBrockhaus if I recall correctly, in my case the problem was that doing `User.IsInRole()` if the user wasn't authenticated would throw an error. I wasn't using Active Directory at all so unfortunately I don't really know how to help. – user1987392 Oct 24 '14 at 08:07
  • 1
    no worries. Was just providing the link back to the other question in case others found this one instead. – JoeBrockhaus Oct 27 '14 at 17:16
  • Yup, MVC5 seems to use a windows identity when the user is unauthenticated, checking for isAuthenticated fixes this – Dan Feb 26 '15 at 04:39
  • Didn't fix for me. – Daniel Jackson Apr 15 '19 at 16:51
12

I've had this issue - It failed for me if I tested an active directory group that didn't exist.

Make sure you're using a group that exists!

David McEleney
  • 3,397
  • 1
  • 26
  • 32
2

I was having this issue with Asp.Net Core 3.1 with Windows Authentication, but this thread came up first when searching the internet. I ended up resolving the issue by decorating the controller class declaration with the following:

using Microsoft.AspNetCore.Authorization;
[Authorize]
    public class SetupController : Controller

Hope this is helpful for someone that is using Windows Authentication and is having the same error.

jon.r
  • 896
  • 8
  • 16
1

We were having this same issue on a new production server. Using the Identity Framework and restricting access to a specific directory with a web.config file denying any unauthenticated users. When unauthenticated users tried to access a page in this directory that contained any User.IsInRole("RoleName") code, they were getting the "Trust relationship..." error.

None of the fixes mentioned in other SO answers worked for us.

Turns out we just had to enable Forms Authentication in IIS - problem solved.

Scotty
  • 1,127
  • 1
  • 7
  • 17
0

The "trust relationship between the primary domain and the workstation has failed" error message usaully requires that the computer be removed from the domain and then rejoined. Now there are a few ways to do this. As included in the link above, are instructions on how to do so either on the computer displaying the error or remotely. You can also do so in Active Directory and in PowerShell.

Laura
  • 1
  • I wasn't using Active Directory, but thanks for your answer - it may be useful for people who do and get here with the same error message. – user1987392 Nov 21 '14 at 08:28
  • For others ...this error seems to be a generic message that Microsoft uses it doesn't always mean it needs to be rejoined – Micah Armantrout Jan 22 '15 at 14:55
0
<authorization>
            <allow roles="pri\Domain Users" users="pri\domain_user" />
            <deny users="?" />
</authorization>
  • make sure that you have the above line in your web.config file and complete the user field with the correct user name.
0

I've just resolved this in our systems, unfortunately, none of the other suggestions worked for me. The issue was caused by an orphaned SID in a network folder the code was attempting to access. Once removed it started working again.

Jon
  • 610
  • 2
  • 6
  • 13
0

I had exactly the same scenario with custom Authentication Module and the same error when doing IsInRole. The highest ranking solution (User.Identity.IsAuthenticated && ...) did NOT help. So, I played quite a bit with it. Finally I found that I had to remove a (preCondition="managedHandler") attribute from my module declaration in web.config file. So, instead of:

  <system.webServer>
    ...
    <modules>
          ...
          <add name="CompanyAuthentication" type="Company.Authentication.AuthHttpHandler" preCondition="managedHandler" />
    </modules>

I would have to have:

  <system.webServer>
    ...
    <modules>
          ...
          <add name="CompanyAuthentication" type="Company.Authentication.AuthHttpHandler" />
    </modules>

That did the trick for me!

Greg Z.
  • 1,376
  • 14
  • 17
0

For me, the whole membership provider configuration tags were missing. After i copy those from one our previous apps, it worked fine.

  <system.web>
<authentication mode="Windows" />
<compilation debug="true" targetFramework="4.7.1" />
<httpRuntime targetFramework="4.7.1" />
<httpModules>
  <add name="TelemetryCorrelationHttpModule" type="Microsoft.AspNet.TelemetryCorrelation.TelemetryCorrelationHttpModule, Microsoft.AspNet.TelemetryCorrelation" />
  <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
</httpModules>
  <profile defaultProvider="DefaultProfileProvider">
  <providers>
    <add name="DefaultProfileProvider" type="System.Web.Providers.DefaultProfileProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/" />
  </providers>
</profile>
<membership defaultProvider="DefaultMembershipProvider">
  <providers>
    <add name="DefaultMembershipProvider" type="System.Web.Providers.DefaultMembershipProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
  </providers>
</membership>
<roleManager defaultProvider="CustomRoleProvider" enabled="true" cacheRolesInCookie="false">
  <providers>
    <add name="CustomRoleProvider" type="ABC.ABCModels.ABCRoleProvider" />
  </providers>
</roleManager>
<sessionState mode="InProc" customProvider="DefaultSessionProvider">
  <providers>
    <add name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" />
  </providers>
</sessionState>

venu
  • 147
  • 3
  • 15
0

On my case, I am not using User.Identity but rather Thread.CurrentPrincipal.Identity.Name

So when I approach this line of code:

Thread.CurrentPrincipal.IsInRole("admin");

That's where I will encounter the same error message of:

The trust relationship between this workstation and the primary domain failed.

There are two cases why I encountered the same issue and of course the fixes I made:

  • I was disconnected with my VPN. This will look for the role that doesn't exist since I am not connected with my VPN and not connecting with my AD accounts.
  • If I am connected with my VPN and the role admin doesn't exist based on my code above, it will certainly trigger the same error message.
Willy David Jr
  • 8,604
  • 6
  • 46
  • 57
0

I think it is worth sharing how I've fixed on my situation as these answers helped me to figure it out.

We were allowing/restricting access to pages via web.config and this was happening before touching any code (so it didn't matter where the breakpoint was, the error was coming).

Since this was not amazing too, I've decided to implement this validation in the code manually instead of using the web.config one.

our web.config used to look like this:

<configuration>
    <system.web>
        <authorization>
            <allow roles="10,5"/>
            <deny users="*"/>
        </authorization>
    </system.web>
</configuration>

We've changed to:

  • Created a page (called restricted page) that inherits from Page
  • This page has a protected variable called RequiredAccessLevel
  • The OnLoad of the page we check if the user is in the role of the RequiredAccessLevel and if it is not, we redirect to a custom AccessDenied page
  • Made the pages that should have this restriction inherit from RestrictedPage instead of Page
  • On the constructor of the pages that are inheriting from RestrictedPage we set the access level necessary

Like this:

RestrictedPage.cs

public class RestrictedPage : Page
{
    protected int[] RequiredAccessLevel { get; set; } = { };
   
    protected override void OnLoad(EventArgs e)
    {
        if (RequiredAccessLevel.Length > 0)
        {
            var allowed = false;
            foreach (var ral in RequiredAccessLevel)
            {
                if (Page.User.IsInRole(ral.ToString()))
                {
                    allowed = true;
                    break;
                }
            }
            if (!allowed)
            {
                Response.Redirect("~/AccessDenied.aspx");
            }
        }
       

        base.OnLoad(e);
    }

}

Example.cs

public partial class Example: RestrictedPage
{
    public Example()
    {
        RequiredAccessLevel = new[] {10};
    }
}
Daniel Maiochi
  • 607
  • 6
  • 16