Code Monkey home page Code Monkey logo

mvc5-mixedauth's Introduction

Important Announcement

This project is more of a proof of concept that makes mixed authentication appear as if its an external provider. I recommend using OWIN-MixedAuth, because its modular and works seamlessly with other authentication providers.

ASP.NET MVC 5 Mixed Authentication

Mixing Windows and Forms Authentication (Windows + Forms) Login

===========

Visual Studio Update 3

A new updated branch is available here. Also view this comparison for the list of changes required to add Mixed Authentication support.

How its done ?

The basic idea is to have a managed handler to perform windows authentication, then hand control over to the cookies authentication middleware.

It will appear as if its an external provider. Sample Screens

Running the solution locally

No special requirements! Visual Studio Express 2013 is all you need.

  • Clone the repository: git clone [email protected]:MohammadYounes/MVC5-MixedAuth.git

  • Open the solution using Visual Studio, build and run.

Enabling Windows Authentication on IIS Express.

  • From Solution Explorer, select MixedAuth project then press F4 to view Project Properties and Make sure "Windows Authentication" is enabled.

    IIS Express

Importing AD Groups as Role Claims:

All AD groups asscociated with the user windows account are available when you hit the WindowsLogin Action, you can fetch all of them by iterating over Request.LogonUserIdentity.Groups:

private void MapGroupsToRoleClaims(ApplicationUser user)
{
  foreach (var group in Request.LogonUserIdentity.Groups)  
    user.Claims.Add(new IdentityUserClaim()
    {
      ClaimType = ClaimTypes.Role,
      ClaimValue = new SecurityIdentifier(group.Value)
                         .Translate(typeof(NTAccount)).Value
    });
}
Flowchart of the Windows Login / Link code flow (Contributed by @ComboFusion)

mixedauth-windowsloginhandler


Please share any issues you may have.

mvc5-mixedauth's People

Contributors

macropus avatar mohammadyounes avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mvc5-mixedauth's Issues

Custom check for windows authintication

dear,
I want the place to get the current user identity and check if this user exist at my SQL database, if yes I want to prepare the claims at identity and if not I want to redirect to login page.

so where I must check this before redirect to login page , it always redirect me to login page

I appreciate your support

to authenticate request user

public async Task<ActionResult> WindowsLogin(string userName, string returnUrl)
{
      // can we call hander from MVC action, to authenticate request user?      
      var handler = new WindowsLoginHandler();
      var processAwait = await   handler.ProcessRequestAsync(System.Web.HttpContext.Current);
}

Question about the Code Flow (added a Flow Chart)

OK, I have a question.

I wanted to understand what exactly are you doing, because I need to modify this code so that I will be able to use an extern WCF service for authentication (still using mixed authentication of course). So I drew the code flow in order to really understand wht's happening here. At this point I apologize, because I is only sketched the flowchart on a piece of paper. :) When I'll have time will do it in Visio and share it here. So until then, please bear with me. :)

If you look the flow marked with "1.2", you'll see that after hitting the ProcessRequestAsync() method of the WindowsLoginHandler we basically have two branches, LEFT and RIGHT. But somehow I always fall into the LEFT branch of the flow chart and I can never reproduce the case where I would fall into the RIGHT branch where we save the user Id to Session.

So I was wondering if I am missing something here. When do I actually fall into the RIGHT branch (where we need to save the userId to Session)?

NOTE that I tried to login with username and password as well (which means I was using context.User.Identity... at least I guess).

cam00381
cam00382
cam00379

Where is "MVC5-MixedAuth.mdf" database file?

Hello Mohammad,

I just downloaded your solution ... I tried to run the application but I can not found MVC5-MixedAuth.mdf file to attach it and see your solution in action... could you please help out to generate this file?

Thanks,

ProcessRequestAsync() in the WindowsLoginHandler is never hit on my own project

Hi there. First of all I give you my compliments and great thanks for sharing this great POC project. However I have an issue when implementing your code in my own project. Just to be clear, your project works fine when I run it. It is in my own implementation of your code where I have problems.

My main problem is that when clicking the "Windows" button, I never hit the ProcessRequestAsync method in the WindowsLoginHandler class.

Thus I never fall into the RequestChallenge method where the fake status code is set. This means that I always end up with a 404 code instead of the fake 418 code. In other words... I would expect that before hitting the ApplyChallenge extention method (in the MixedAuthExtensions class) I would hit the ProcessRequestAsync method first. Which I never do! :(

I think I took care of everything so that the WindowsLoginHandler class is properly set, but somehow I never hit it.

Is there anything else I should set up in my project other than placing the <system.webServer> node in my global web.config file?

Now I have this in my web config:

< system.web >
< authentication mode="None" />
< compilation debug="true" targetFramework="4.5" />
< httpRuntime targetFramework="4.5" />
</ system.web>
< system.webServer>
< handlers>
< add name="Windows Login Handler" path="Login" verb="POST" type="Adacta.AdVelocity.SmartAdmin.Infrastructure.MixedAuth.WindowsLoginHandler" preCondition="integratedMode" />
</ handlers>
< modules>
< remove name="FormsAuthenticationModule" />
</ modules>
</ system.webServer>

Thank you in advance for any help!

unauthorized error

use WindowsFirst branch:
change HomeController#Contact, let it need a role

[Authorize(Roles="Admin")]
public ActionResult Contact()

then access the "~/Home/Contact" and got a 404 error

Supporting Web API?

First off, great work on putting this together. My issue is, I've merged this code into my project, and have everything working except Web API. What would I need to do to add Web API Support? With the solution as-is, when I try to make a Web API request, I get 302 redirected to the login page. I found some things online, per one suggestion I tried adding a Provider override for the UseCookieAuthentication() call in Startup.Auth, but that just resulted in a 401. I'm going to keep working at it, but was curious if you had any thoughts.

Handling Errors

I wanted to get your inputs on how to handle the 401 errors that are returned if you cancel out of the windows authentication login prompt or enter invalid credentials.

In the web.config I've added an section and created a new 401 error to have it redirect to a custom error page but it does not work as expected. When I have the set up and I click the 'windows' login button the page goes blank (I don't receive a login prompt). If I remove the Section i then I receive the login prompt and if I click cancel I get the typical ugly 'HTTP Error 401.2 - Unauthorized
You are not authorized to view this page due to invalid authentication headers.' error page.

I wasn't sure if this had anything to do with sending the fake status code of 418 when requesting a challenge or not.

Wanted to get you take on it and see what you thought.

Thanks

Works in IIS Express but not when deployed in localhost

First of all great article!!! I just tried your sample and it works great when i run under iis express. But when I run under local IIS (version 7.5) i get the following error:

HTTP Error 401.2 - Unauthorized
You are not authorized to view this page due to invalid authentication headers.
Detailed Error Information
Module global.asax
Notification EndRequest
Handler Windows Login Handler
Error Code 0x00000000
Requested URL http://localhost:80/MixedAuth/Windows/Login
Physical Path C:\DEV\ePOWER90\OWIN\MVC5-MixedAuth-master\MVC5-MixedAuth-master\src\Windows\Login
Logon Method Anonymous
Logon User Anonymous

The authentication settings of the virtual directory has Anonymous enabled and Windows Authentication enabled. Could help me with this please?

Auto windows login

Hi Mohammad,

This is a very good example of mixed authentication. Thanks for this. With this example, how would you go about automatically attempting to logon via Windows authentication (i.e., not having a "Windows" login button on the view), so when the application is loaded, it automatically attempts to login via Windows authentication, and if it fails, to display the Forms login view?

Default windows login

I am trying to set by default try windows login and if its fails redirect to forms login window. The default action to WindowsLogin is not working. Could you please let me know how I can make it work in the Update 3 sample.

Thanks
Paul

Logout not working

Hey, I am using chrome for mixed auth testing. When I use window authentication, it authenticates it fine. But when I logout and login again, it does not ask username /password. There is no 401 challenge. How to force a 401 challenge on logout and relogin ? I am only seeking a Windows Authentication solution.

Please note:
I am using MVC5 example.

The provided anti-forgery token was meant for user "", but the current user is

Hi Mohammad,
thank you for sharing this great work.
I am new to MVC so I need some help.
I have one question about this exception "The provided anti-forgery token was meant for user "", but the current user is "JoroPC\Joro". "
Everything worked fine on local machine but when try it on Server 2008 R2, after "Windows login" this exception is raised. Every machine has same IIS 7.5 with enabled "Windows Authentication". I tried to changing negotiate provider to NTLM but it do not help.
Tried also to disable the identity check in Application_Start method AntiForgeryConfig.SuppressIdentityHeuristicChecks = true but the result is the same.
Can you help?

Need to hide window authentication popup for outside domain users

HI Mohammad,

Thanks for great solution.

We are facing one issue in which when domain user make request to application it get successfully logged in but when request to comes from outside of domain it display "Window Credential" Popup window which required to cancel by user to allow application to redirect login page.

Would it possible to remove/hide or bypass window credential window in case of non-domain user.

Thanks

Application check for windows authentication

Hello,
I found this repository by chance and I think it can help me for what I want to design.
I comment on my idea:
I want to design a windows application that will connect to a web service through active directory. But also, i want to be able to access this web service through the browser through form authentication.
My question is:
To what path would I have to send the authentication request from my application?
Because I have been trying to send it to the login page but I always get a 500 error.

I appreciate your support

Latest MVC breaks authentication

The jump to MVC 5.1 (and 5.2) no longer are compatible with your solution. Since I am new to authentication, I am unable to patch the differences. I am using BeyondCompare to diff your solution with a vanilla MVC 5.2 solution, without success. Could you try updating your code pretty please? This seems to be the perfect solution to my needs.

User Credentials promted keeps coming back

I have implemented this app locally and everything works fine. When I deploy it to a webserver I keept getting promt for user credntials. When I login I keep have to enter my credentials and getting error 401: HTTP Error 401. The requested resource requires user authentication.

I have tried adding the website to Local intranet as wel as adding it tot Trusted sites. Both give same result. Some how it is not sending my windows account credentials to the server. I know my credentials are correct for my local computer because I log in with them every day.

I have tried many of the solutions for other issues but so far no luck.

IUSR when deploying to IIS 7.5

Hi,

First of all, thank you for your extension. It works great in Visual Studio :)

But when I'm publishing my website in IIS, I can't authenticate myself with NTLM.
I've got "IUSR" instead of "DOMAIN\Username" in the menu.

And when I disable Anonymous authentication, I get 404.15 HTTP Error Code with following URL :
http://localhost:47348/Windows/Login?ReturnUrl=%2FWindows%2FLogin%3FReturnUrl%3D%252FWindows%252FLogin%253FReturnUrl%253D%25252FWindows%25252FLogin%25253FReturnUrl%25253D%2525252FWindows%2525252FLogin%2525253FReturnUrl%2525253D%252525252FWindows%252525252FLogin%252525253FReturnUrl%252525253D%25252525252FWindows%25252525252FLogin%25252525253FReturnUrl%25252525253D%2525252525252FWindows%2525252525252FLogin%2525252525253FReturnUrl%2525252525253D%252525252525252FWindows%252525252525252FLogin%252525252525253FReturnUrl%252525252525253D%25252525252525252FWindows%25252525252525252FLogin%25252525252525253FReturnUrl%25252525252525253D%2525252525252525252FWindows%2525252525252525252FLogin%2525252525252525253FReturnUrl%2525252525252525253D%252525252525252525252FWindows%252525252525252525252FLogin%252525252525252525253FReturnUrl%252525252525252525253D%25252525252525252525252FWindows%25252525252525252525252FLogin%25252525252525252525253FReturnUrl%25252525252525252525253D%2525252525252525252525252FWindows%2525252525252525252525252FLogin%2525252525252525252525253FReturnUrl%2525252525252525252525253D%252525252525252525252525252FWindows%252525252525252525252525252FLogin%252525252525252525252525253FReturnUrl%252525252525252525252525253D%25252525252525252525252525252FWindows%25252525252525252525252525252FLogin%25252525252525252525252525253FReturnUrl%25252525252525252525252525253D%2525252525252525252525252525252FWindows%2525252525252525252525252525252FLogin%2525252525252525252525252525253FReturnUrl%2525252525252525252525252525253D%252525252525252525252525252525252FWindows%252525252525252525252525252525252FLogin%252525252525252525252525252525253FReturnUrl%252525252525252525252525252525253D%25252525252525252525252525252525252FWindows%25252525252525252525252525252525252FLogin%25252525252525252525252525252525253FReturnUrl%25252525252525252525252525252525253D%2525252525252525252525252525252525252FWindows%2525252525252525252525252525252525252FLogin%2525252525252525252525252525252525253FReturnUrl%2525252525252525252525252525252525253D%252525252525252525252525252525252525252FWindows%252525252525252525252525252525252525252FLogin%252525252525252525252525252525252525253FReturnUrl%252525252525252525252525252525252525253D%25252525252525252525252525252525252525252F

Can you help me please ? :)

401 on ajax requests

Getting a cookie and loading my mvc site and resources just fine, but subsequent ajax requests are failing with a 401. The cookie is in the request, but so is an Authorization: Negotiate header which I think is the cause of the 401 challenge. Thoughts on this?

WindowsAuth 404 on IIS 8.0

On my IIS express everything works fine but after publishing my application on IIS8 server i have 404 when try to login with windows authentication while login authentication works normal.

I should change something in code , or in IIS 8.0 settings?

Thank you

I just wanted to say thank you but I didn't know how to contact you.

Thank you very much Mohammad, this was very helpful for me.

Not working when on IIS 8.0

Hi,
This code is working fine on the visual studio but it gives me an error on doing "Windows" login when hosted in IIS.

Error Details:

URL: http://localhost:7000/Windows/Login

HTTP Error 401.2 - Unauthorized

You are not authorized to view this page due to invalid authentication headers.

Please let me know if you the solution for this.

Regards
Sharad

Getting started with the mvc5 mixed auth

<!-- Enable Mixed Auth -->
<location path="MixedAuth">
  <system.webServer>
    <security>
      <authentication>
        <windowsAuthentication enabled="true" />
      </authentication>
    </security>
  </system.webServer>
</location>

I am trying to use the code for the mixed mode with windows auth in my mvc5 application .
I am getting null when var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
i have set the environment as per the scren shot and it works fine ,what is this location tag and what is the value in path and await AuthenticationManager.GetExternalLoginInfoAsync() in the example return my current ad user info but when i use it my app its null

NullReferenceException right after project build

I downloaded the latest source code, and launched debugging from VS 2013 Community Edition (Update 4). After restoration of NuGet packages and compilation, the application launched in IIS express with the following error on the http://localhost:3314/ URL:

[NullReferenceException: Object reference not set to an instance of an object.]
   Microsoft.Owin.Security.Cookies.<AuthenticateCoreAsync>d__0.MoveNext() +664
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
   System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() +24
   Microsoft.Owin.Security.Infrastructure.<BaseInitializeAsync>d__2.MoveNext() +860
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
   System.Runtime.CompilerServices.TaskAwaiter.GetResult() +21
   Microsoft.Owin.Security.Infrastructure.<Invoke>d__0.MoveNext() +427
   System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +22
   Microsoft.Owin.Host.SystemWeb.Infrastructure.ErrorState.Rethrow() +33
   Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.StageAsyncResult.End(IAsyncResult ar) +150
   Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContext.EndFinalWork(IAsyncResult ar) +42
   System.Web.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +415
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

I did not make any changes to the code. How should I proceed to get the code working?

Series of questions regarding async http calls, standards, identity 2.0, AD, and OWIN

I apologize for making this an issue. I did not see anywhere else where I could post a question, so my apologies if I missed another section to do that. However, I wanted to post this here so people could read my question.

I feel you have a very good reason for implementing the windows handler as a handler, but given that MVC5 is focused on action filters, can you please tell us why you designed it as a handler and not an action filter for windows authentication (active directory)?

Thanks.

Authorizing Windows user instead of linking account.

Heyo

This project appears to be exactly what I need, however I have no forms authentication in my application in contrast to your examples.

What I'm doing

I have a website that uses windows authentication, mobile clients that use webapi token-based oauth security, and an integration api that uses a simliar api-key token-based security. The windows users accounts exist in a database which I need to query to check that the authenticated windows user has access to the application. This is preferred over using AD groups in Authorize attributes.

I'm considering splitting some of these back-end concerns up, but for now they're all serviced by one web server

Where I'm at

If request isn't successfully authenticated through the Owin pipeline, I get redirected to the virtual endpoint /Windows/Login, which seems to be where the WindowsLoginHandler comes into play. The flow works, triggering a 401 challenge. On successful authentication, I'm sent back through the WindowsLoginHandler. I have an authenticated LoginUserIdentity, but my session doesn't have a userId yet so I'm sent through WinLoginAsync which appears to be attempting to redirect to my Account/WindowsLogin endpoint.

Your flow here redirects them to a login form. I need to auto log them in if their account exists in my db. I'm attempting to just do this work in AccountController.Windows' WindowsLogin endpoint, but I never get there.

What I'm asking

I guess I'm wondering if this could be done in a simpler fashion since I don't need to redirect my users to login forms. Or, do you have any thoughts why ExecuteController may not be hitting my endpoint?

Thanks!

Where is the definition of GetWindowsLoginInfo?

Hi,

I have a query, where have you written definition of GetWindowsLoginInfo?

I have similar requirement where I want to get the user roles for authorisation but don't want to make LDAP call for that because it makes it slow.

Is there any better way to implement it?

Thanks,
Deepak

The code in Startup.cs isn't getting called

Hi Mohammad,

My ultimate aim is to achieve Auto Windows Login, and I have followed the steps you have mentioned in #6, but nothing happened. Upon investigating further, I realized that the original redirect to /Account/Login itself wan't happening and that the code inside Startup.cs isn't getting called at all.

I am using the Update 3 Branch code. (I originally tried this with the master branch code but with no luck there too)

Please help.

Windowslogoff not found

Hey,

I've implemented this branch on multiple projects and it works all the time.
But, in one of my customers, after inserting the domain account it gives an error about not finding Windowslogoff.

It's problably a Windows/IIS feature, but I can't simulate it on my DEV machine.

Any ideas? How may i be able do discover what's causing it?

Sign in as different Windows User

When I first go to the login page and click to log in through Windows Authentication, the page prompts me for my Windows credentials like this:

https://www.dropbox.com/s/9rn0j9b9hyaihfl/Screenshot%202014-12-01%2023.03.28.png?dl=0

After I log out of the application and later try to log in again, I am no longer prompted for my credentials. What should I do if I want to be prompted for credentials again? (e.g. I want to login as different Windows user)

I tried to setup Internet Options as following for all four security zones, and even rebooted my machine.

https://www.dropbox.com/s/5xnsxb0elvz68rz/Screenshot%202014-12-01%2023.08.06.png?dl=0

But still I am getting prompted for the credentials only first time. How should I switch to login as a different Windows user then?

Is it possible that the application isn't logging the Windows user out properly?

Importing AD groups as role claims

A quick question. When I iterate through claims as shown in MapGroupSidToRoleClaims, many of my AD groups are missing. Examples of missing groups are things like Domain Admins, Enterprise Admins and all of the groups that I have created. To test, I tried local, global and universal security groups and none seem to appear in claims. Meanwhile, the following do show up. Am I missing something simple? I looked through the identity objects in the debugger carefully, but don't see the sid's of interest anywhere. Puzzled.

        MyDomainName\Domain Users
        Everyone
        BUILTIN\Hyper-V Administrators
        BUILTIN\Performance Log Users
        BUILTIN\Users
        NT AUTHORITY\INTERACTIVE
        CONSOLE LOGON
        NT AUTHORITY\Authenticated Users
        NT AUTHORITY\This Organization
        LOCAL
        Authentication authority asserted identity
        MyDomainName\Denied RODC Password Replication Group
        MyDomainName\OLAP Administrators

Visual Studio 2013 Update 2

Originally posted by @AdamNaylor

Recently, I have upgraded my version of VS2013 to Update 2. I have been working on a solution whereby auto email verification/confirmations are sent if registering with an external account. I have got this working well. This uses Identity v2.

I have tried to merge in the MixedAuth code into the project to allow internal users to login automatically. However, I have had difficulty in merging in the code. Thus far, the Windows\Login method isn't auto called for some reason. If manually type in the Windows\Login path, the ProcessRequestAsync is called, but isn't run through the second time for the secondary request, like in the MixedAuth project. Instead, after running through the ProcessRequestAsync code once, it fails, reporting "The custom error module does not recognize this error.".

Long shot, but would you have any idea what this means? I can't even see where it is being generated from.

Additionally, since upgrading to Update 2, if I open the original MixedAuth project, the "DefaultConnection" database won't create when trying to register a new user. It states:
"Cannot attach the file 'C:\MVC5-MixedAuth-master\src\App_Data\MVC5-MixedAuth.mdf' as database 'MVC5-MixedAuth'. "


The project already uses Identity v2! But VS2013 Update 2 adds email requirement to the registration process, you can either disable it by setting UserValidator.RequireUniqueEmail = false (/App_Start/IdentityConfig.cs)

Or make it part of the windows login confirmation (/Views/WindowsLoginConfirmation.cshtml).

As for the database, (localdb)\v11.0 keeps the database, even if the file was moved or deleted and cannot attach a different file to the same database, you need to connect using SQL management studio and manually delete the database to be able to attach a different file with the same name.

Thanks.

WindowsFirst solution not working?

Hi Mohammed, I've downloaded the WindowsFirst branch and followed your instructions to run it but I am unable to do so. I'm using Visual Studio 2015 and enabled Windows Authentication in IIS Express but it results in a 500 error on start up. I can't seem to find where the error is occuring, After hitting breakpoints it the Global.asax.cs and Startup.cs, it just fails.

Are you able to replicate this?

Not going through ProcessRequestAsync

Hey,

I copied all the process to my project but when i try to login with windows it gives-me NT AUTHORITY\IUSR.

I think it happens because the handler WindowsLoginHandler declared in web.config is not getting called.

Any idea?

Thank you in advance,
Leandro Soares

Is it safe to upgrade to OWIN-MixedAuth?

Hey again,

I've been using this branch for a few months and everything is working.
But it seems that this branch will not receive updates anymore, so i want to start using OWIN-MixedAuth branch.

However, i made some modifications on my code and i know i need to merge them locally with your OWIN solution.

But, are there any MAIN differences that may break my application?

Automatic login with Windows Identity

Thanks for your work - this library is really handy!

I have just one question, hope you could give me an advice. Is it possible to make user automatically login using his Windows Identity, like it's happening with simple WindowsAuthentication scenario? The point that we still need Mixed Authentication, so that even if user was automatically logged in - he can logout and then login with a different account. Logout logic is already implemented, by setting a cookie like "ForcedLogout=1", that prevents user to re-login automatically again.
However we still struggling implementing the correct behavior for automatic login.

I suspect we need somehow to call "Windows/Login" action programmatically, or something similar. I feel I'm somewhere close to solve it, but it seems I'm missing something..

Edit:
My bad, it seems similar issue was already answered. Found it in "closed" issues. :)

Browser returns 418 error at windows login

Thank you for this project. It is very helpful. I am embarrassed to ask.this because I fear I am missing something simple. I used your guidance to update my small existing project to use mixed auth. When hitting the Windows login button I end up in the WindowsLoginHandler as expected, but after the call to context.RequestChallenge() the browser simply returns the fakeStatusCode, rather than ending up back in the handler again as it should. I've set IIS to Windows Authentication. I've checked my routes, config files. Could there be something simple I have missed?

Thanks!

Thanks for this solution, that's super-clever. Did you came up with it yourself or, did you follow some tutorial? :)

can't catch WindowsLoginHandler

I applied the sample exactly at my project but when I press windows button to login it gives
windows/login
HTTP Error 404.0 - Not Found
I am using local iis
and
when I debug the code it does not catch the CreateRouteData at MixedAuthExtensions

iis
webconfig

HTTP 404 on /Windows/Login after deploying to IIS

I hope that this question hasn't been answered somewhere else, but I'm having an issue with the getting the WindowsFirst branch to work.

First off, this is a terrific solution and is exactly what I was looking for! Implementation so far has gone very smooth except for 1 glitch.

I am a local user on the domain so I would expect to be automatically logged in and brought to my HomeController. I've gotten my project working locally in my development environment , my Startup.Auth.cs is pointing to "/Windows/Login". From IIS Express it works as expected, I am automatically logged in and get to the Home page.

However, after deploying my site to IIS 7.5 (on a Windows 2008 server on the local network) and try to pull up the site, I'm receiving the following error:

Server Error in '/' Application.

The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.

Requested URL: /Windows/Login


Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.34249

If I remove the "Windows/Login?ReturnUrl=%2F" from the query string and try to load the page two times in a row, it will allow me to get to my HomeController (which has [Authorize] enabled).

Is there some type of custom 404 handler that I might need to this scenario that you can help me with implementing?

Thank you very much!

How to SignIn the user (with username and password) in case I cannot use Identity?

Username and password login scenario.

Let's say I cannot use the following method to sign in the user, because I am not using the ASP.NET Identity database structure to handle my users.

private async Task SignInAsync(ApplicationUser user, bool isPersistent)
    {
      AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
      var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
      AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
    }

My users are handled with a WCF service client and the service response tells me if the username and password are valid (thus if the user is authenticated). How can I in this case achieve so that the [Authorize] attribute will let me through to the HomeController Index action?

I tried setting the authoriziation cookie, but somehow I had no luck. Also HttpContext.User.Identity.IsAuthenticated() always returns false! :(

Thank you in advance for any help, which I really need right now.

Does Not Allow AD Groups to Come Through

First off--VERY NICE! Good job on this!

I have a need to use Authorize attributes for the current user. It doesn't appear to work when logging in as any windows user. I used for instance:

[Authorize(Users=@"domain\user, user,domain\user2")]
or
[Authorize(Users=@"domain\user", Roles=@"domain\group1, group1"]

Notice that I tried with and without the domain. In all cases, the result was "Unauthorized".

I noticed that the WindowsLoginHandler does not pull anything more than the Session user name. It does not grab the groups associated with the user on the active directory domain. I sort of got it to start pulling the claims by making the and setting a property in the Application_Start, AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.WindowsAccountName;

This resulted in the claims, as type groupsid, to start populating, but that actually broke how your solution operates.

What would you recommend as far as integrating further to make WindowsLoginHandler more "aware" of the Windows Identity to store the "alternate" WindowsAccountName, domain and such. I don't recommend storing the AD groups (since they are dynamic and managed separately), but I do recommend that, upon logging in, that the claims should "flow through" and be visible or passed in the token.

v/r
BK

How would you go about initiating BeginWindowsAuthForm in code?

We're exploring this sample for use in our application. However, we want the application somewhere on initialization to get a windows user if available and then validate it in code.

Basically I'm trying to figure out how to simulate what happens when a user clicks on the Windows button.

Redirect Not Occurring on Windows 2012 IIS 8.5

On a Windows 2012 Server environment, I have an application acting as the Authentication service using your code. I have an ASP.NET WebForms app, using out of the box OWIN with a provider having OnApplyRedirect = ApplyRedirect going to your authentication portion. Everything works fine--but it never redirects and I can't seem to debug into it. If I navigate back to the webForms app, the cookie and claims are all present...

By the way, this all works, including the redirect with the same setup in Windows 8.1 and WIndows 2008R2 server! So, just strange that it doesn't on our test server and my newly created 2012 server VM.

I know it must be something simple that I'm missing...

405.0 - Method not allowed

Hi,

I am using your codes to mixed authentication, copied all the required codes, web.config settings etc, but when I click on the Windows login button I get 405.0 - Method not allowed. I am suffering from this now since 2 days, cannot find any explanation or help. Your source working perfectly, without any configuration.

EDIT1: In Firebug the _WindowsLoginPartial has the following code:

<form class="form-horizontal" method="post" role="form" action="/MyWeb.Site/Windows"><input name="__RequestVerificationToken" value="2oXRYnWK8zgWw...." type="hidden">
  <input name="returnUrl" type="hidden">        
  <input id="windowsLogin" value="Windows" class="btn btn-default" type="submit">
</form>

I think "/MyWeb.Site/Windows" a wrong link. In your project there is a "/Login" at the end. The code that generates this link is (as your code, I don't change anything):

public static MvcForm BeginWindowsAuthForm(this HtmlHelper htmlHelper, object htmlAttributes)
{
     return htmlHelper.BeginForm("Login", "Windows", FormMethod.Post, htmlAttributes);
}

If I change that link in FireBug to "/MyWeb.Site/Windows/Login", then I can log in as Windows user. But where did the "/Login" go? :)

Please help.

Thx,
Jon

Missing App_Data folder

Should the App_Data folder be checked in? When I launch and build the project I get the following error:

Cannot attach the file 'C:\Users\dev\Documents\Visual Studio 2013\Projects\MVC5-MixedAuth-master\src\App_Data\MVC5-MixedAuth.mdf' as database 'MVC5-MixedAuth'. There is no App_Data folder included in github

Not hitting handlers

<handlers>
      <!--register windows login managed handler.-->
      <add name="Windows Login Handler" path="Login" verb="POST" type="MixedAuth.WindowsLoginHandler" preCondition="integratedMode" />
    </handlers>

Automatic windows Authentication

Hi Mohammad . At first thank you for your fantastic mix Authentication system , it works fine and save time of my time. But is there any way to skip windows authentication window and use current user data?

Trouble linking accounts

I can login by creating an account and I can login using the Window's service but I can't link the two accounts.

Scenario
Login using Windows
Fill out Associate Form

This links the two accounts in the db but there is no password associated with the account so you can't log in.

I tried clicking my user name
Create Password
This seems to work because I can successfully use the Change password form but every time I try to log in with my email and password I receive an "Invalid login attempt"

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.