asp.net c# MVC 5-Log off the active directory user - active-directory

I have my application(with individual user account authentication type)to use active directory login in my custom login screen using the LDAP connection with System.Web.Security.ActiveDirectoryMembershipProvider
I can login into the application, but I am not able to logout from the application.
Here is my logoff code:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult LogOff()
{
AuthenticationManager.SignOut();
return RedirectToAction("Index", "Home");
}
My web.config file is:
<authentication mode="Forms">
<forms name=".ADAuthCookie" loginUrl="~/Account/Login" timeout="45" slidingExpiration="false" protection="All" />
</authentication>
<membership defaultProvider="ADMembershipProvider">
<providers>
<clear />
<add name="ADMembershipProvider" type="System.Web.Security.ActiveDirectoryMembershipProvider" connectionStringName="ADConnectionString" attributeMapUsername="sAMAccountName" connectionUsername="ldapnew" connectionPassword="abcd123!" />
</providers>
</membership>
</system.web>
<connectionStrings>
<add name="ADConnectionString" connectionString="LDAP://10.0.1.10:379/ou=General,dc=abc,dc=local" />
</connectionStrings>
Please help me to resolve this code?

We're doing this different, you have to redirect to the ADFS signout page it self...

Related

IIS Reverse Proxy with OpenIdConnect going to wrong Identity provider

OpenIdConnect (Azure) Settings
// COOKIES: Tells it to use cookies for authentication.
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
CookieManager = new SystemWebCookieManager()
});
// OPEN-ID: Authenticate via Azure AD using OpenIdConnect.
//https://azure.microsoft.com/en-us/resources/samples/active-directory-dotnet-webapp-webapi-openidconnect/
app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions()
{
ClientId = ClientID,
Authority = Authority,
PostLogoutRedirectUri = PostLogoutRedirectUri,
Notifications = new OpenIdConnectAuthenticationNotifications()
{
AuthenticationFailed = PrincipalService.OnAzureAuthenticationFailure,
// REFERENCE: https://russellyoung.net/2015/09/05/mvc-role-based-authorization-with-azure-active-directory-aad/
AuthorizationCodeReceived = (AuthorizationCodeReceivedNotification notification) =>
{
var username = notification.AuthenticationTicket.Identity.Name.Split('#').LastOrDefault();
Logger.Log(Level.Auth, "Azure login success! Username: '" + username + "'.");
return Task.FromResult(0);
}
}
});
ARR Url Rewrite Settings
<rewrite>
<outboundRules>
<preConditions>
<preCondition name="ResponseIsHtml1">
<add input="{RESPONSE_CONTENT_TYPE}" pattern="^text/html" />
</preCondition>
</preConditions>
</outboundRules>
<rules>
<rule name="Secondary Server" stopProcessing="true">
<match url="(.*)" />
<conditions>
<add input="{CACHE_URL}" pattern="^(https?)://" />
</conditions>
<action type="Rewrite" url="https://qa2mobile.auntmillies.com/{R:1}" />
<serverVariables>
</serverVariables>
</rule>
</rules>
</rewrite>
Problem
Azure AD authentication works just fine normally, but once I setup a reverse-proxy it starts taking me to my own domain as if it's the identity provider.
e.g. https://my.domain.com/<guid>/oauth2/authorize?client_id=<guid>&etc
From this point, if I manually change my.domain.com to login.microsoftonline.com it'll log me in and proceed to work normally.
If I remove the reverse proxy and set the server up normally, it goes directly to login.microsoftonline.com instead of my domain.
What is causing this? I mean, obviously the reverse proxy, but how do I fix it without removing the reverse proxy?
What is causing this? I mean, obviously the reverse proxy, but how do I fix it without removing the reverse proxy?
As far as I know, if you use url rewirte rule in the web.config, it will rewrite all the request to the https://my.domain.com/ domain which is include the login.microsoftonline.com.
I suggest you could write a new rule which is used to match the /oauth2 request url to directly rediret to the login.microsoftonline.com instead of the https://my.domain.com/. Then it will work well.
More details, you could refer to below url rewrite rule.
<rewrite>
<rules>
<rule name="rule2" stopProcessing="true">
<match url="<talentid>/oauth2/(.*)" />
<action type="Redirect" url="https://login.microsoftonline.com/{R:0}" />
</rule>
<rule name="ReverseProxyInboundRule1" stopProcessing="true">
<match url="(.*)" />
<action type="Rewrite" url="https://<domain>.com/{R:1}" />
</rule>
</rules>
<outboundRules>
<preConditions>
<preCondition name="ResponseIsHtml1">
<add input="{RESPONSE_CONTENT_TYPE}" pattern="^text/html" />
</preCondition>
</preConditions>
</outboundRules>
</rewrite>

Login RedirectUrl with AngularJS & ASP.NET MVC

I have an angular website that is served using MVC pages with ASP.NET Identity cookies. There is an MVC page for the login, and then an MVC page for the index.html which has the [Authorize] attribute on the controller.
It works fine, except for one thing: When I am not logged in, and I go to www.site.com/restricterurl, I would like to have the page redirect me to www.site.com/login?ReturnUrl=%2Frestrictedurl. Then on logging in, I can redirect to the originally requested url. This is a typical login requirement.
However, no matter what URL I try access when logged out, I always get sent to /login?ReturnUrl=%2F, i.e. a ReturnUrl that will redirect to the home (index) page. I suspect this is because I have a UrlRewrite in web.config that rewrites /restrictedurl to / so that (if you're already logged in and access that url) the index page would be served and angular would initialize to the correct restrictedurl route/url. I.e. that UrlRewrite handles the case where you get logged in with the cookie, and the original Url takes you to the route / page where you wanted to be.
So how do I get the authentication, angular, the url rewrite and MVC to play nicely for both these cases:
when logged in and starting at a url, to serve index.html and let angular set the correct route.
when not logged in and starting at a url, to redirect to the login url with the requested url as a querystring parameter.
Some code:
In my startup I have:
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/login"),
//....
My web.config has:
<rule name="Index" stopProcessing="true">
<match url=".*" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_URI}" pattern="^/login" negate="true" />
<add input="{REQUEST_URI}" pattern="^/logout" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
</conditions>
<action type="Rewrite" url="/" />
</rule>

Angular post, put, delete returns 405

I am new to angular.
I cant invoke POST, PUT and DELETE methods using angular (GETs working fine)
I have a .NET WebApi server which all methods and all resources URLs works and tested using Advanced Rest Client.
This is the code:
$scope.updateUser = function() {
var url = 'http://localhost/api/users/' + $scope.selectedId;
$http.put(url, $scope.user,{'content-type' : 'application/json'})
.then(
function(response) {
alert("1");
},
function(errResponse) {
alert("2");
}
);
};
I tried with 'content-type':'application/x-www-form-urlencoded', I tried with no config at all, I tried the one with success and error and I tried the one whith command and data attributes.
I get nothing back and while debugging, errResponse contains only the request data. Checked the network tab in the developer tools, and I found that 405 returned.
Again, all URLs are valid and tested using a third party REST client app.
Can any one help?
EDIT:
web.config:
<system.webServer>
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
<modules runAllManagedModulesForAllRequests="true">
<remove name="WebDAVModule" />
</modules>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
</customHeaders>
</httpProtocol>
</system.webServer>
PUT example:
[HttpPut]
[Route("api/users/{id}")]
public IHttpActionResult updateUser(int id, User user)
Regards,
Ido
adding this snippet to web.config should resolve problem :
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<remove name="WebDAVModule" />
</modules>
</system.webServer>

MVC 6, .NET Core RC2 Rewrite to index.html on non /api urls

I am using MVC 6 with .NET Core RC2
In my startup.cs I have the following (as most people suggest):
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseMvc();
}
In my wwwroot/web.config file I have:
<configuration>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
<handlers>
<add name="httpPlatformHandler" path="*" verb="*" modules="httpPlatformHandler" resourceType="Unspecified"/>
</handlers>
<httpPlatform processPath="%DNX_PATH%" arguments="%DNX_ARGS%" stdoutLogEnabled="false" startupTimeLimit="3600"/>
<rewrite>
<rules>
<rule name="IndexHomeRule" stopProcessing="true">
<match url=".*" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true"/>
<add input="{REQUEST_URI}" matchType="Pattern" pattern="^/api/" negate="true" />
</conditions>
<action type="Rewrite" url="/index.html" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
My goal is that all non /api urls will be rewritten to index.html for Angularjs to handle the routing with html5mode. The main directory will load index.html but other than that I get 404 errors for every other url. How can I set up rewriting if not through web.config?
The only controller I have right now is api/BuyersController.cs which routes using [Route("api/[controller]")]
The URL rewriting for ASP.NET CORE RC2 through to RTM is currently broken as it exists in your question.
The ASP.NET team is currently working on some middleware as a direct ASP.NET solution to this problem. The github issue tracking this is located below.
https://github.com/aspnet/BasicMiddleware/issues/43
There are some solutions in this other issue thread that could be of help to you in the interim.
https://github.com/aspnet/IISIntegration/issues/192

health monitoring in mvc3

I want to do a health monitoring in mvc3 application.
I am doing with eventviewer. But I want to save these events and errors to store into Sql server database.
<healthMonitoring enabled="true" heartbeatInterval="10">
<providers>
<clear/>
<add name="EventLogProvider" type="System.Web.Management.EventLogWebEventProvider,System.Web,Version=4.0.0.0,Culture=neutral,PublicKeyToken=b03f5f7f11d50a3a" />
<add connectionStringName="LocalSqlServer" maxEventDetailsLength="1073741823"
buffer="false" bufferMode="Notification" name="SqlWebEventProviderlane"
type="System.Web.Management.SqlWebEventProvider,System.Web,Version=4.0.0.0,Culture=neutral,PublicKeyToken=b03f5f7f11d50a3a" />
</providers>
<profiles>
<add name="Default" minInstances="1" maxLimit="Infinite" minInterval="00:01:00"
custom="" />
<add name="Critical" minInstances="1" maxLimit="Infinite" minInterval="00:00:00"
custom="" />
</profiles>
<rules>
<clear/>
<add name="All Errors Default" eventName="All Events" provider="EventLogProvider"
profile="Default" minInstances="1" maxLimit="Infinite" minInterval="00:01:00"
custom="" />
<add name="Failure Audits Default" eventName="Failure Audits"
provider="EventLogProvider" profile="Default" minInstances="1"
maxLimit="Infinite" minInterval="00:01:00" custom="" />
</rules>
<eventMappings>
<clear/>
<add name="All Events" type="System.Web.Management.WebBaseEvent,System.Web,Version=4.0.0.0,Culture=neutral,PublicKeyToken=b03f5f7f11d50a3a"
startEventCode="0" endEventCode="2147483647" />
<add name="All Errors" type="System.Web.Management.WebBaseErrorEvent,System.Web,Version=4.0.0.0,Culture=neutral,PublicKeyToken=b03f5f7f11d50a3a"
startEventCode="0" endEventCode="2147483647" />
</eventMappings>
</healthMonitoring>
How to do this?
In the rules section, you have to refer to the provider with the name 'SqlWebEventProviderlane':
<add name="All Errors Default" eventName="All Events" provider="SqlWebEventProviderlane"
profile="Default" minInstances="1" maxLimit="Infinite" minInterval="00:01:00"
custom="" />
Then you have to provide a connection string with the name 'LocalSqlServer' in the section, which points to your database.
<connectionStrings>
<add name="LocalSqlServer" connectionString="data source=serverName;initial catalog=yourDataBase;..."/>
</connectionStrings>
And you have to prepare your database with the tool aspnet_regsql.

Resources