Using windows identity to check users custom role using the .IsInRole method - security

I have created an MVC application whereby the user is able to authenticate either via ADFS or Forms login and in both cases I have been able to use the User.IsInRole method to check my user table that has a roleID attribute which ties to a role table in my database. This is done by including the following section in my webconfig within :
<roleManager enabled="true" defaultProvider="DefaultRoleProvider" cacheRolesInCookie="true">
<providers>
<clear />
<add name="DefaultRoleProvider" type="MyInternal.Providers.MyProvider, MyInternal" connectionStringName="MyContext" />
</providers>
</roleManager>
I am now trying to implement windows authentication and have managed to get the users domain login name etc but when trying to follow same steps as with other two authentication types I am unable to get the IsInRole to work.
How can I tie the User from my repository to the authentication user. Is there some sort of casts or something required? I think that this may have been done by the authentication in ADFS and Forms.

I was able to solve this issue by using the following within my ViewModel:
this.UserName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
if (this.UserName.Contains("\\"))
{
string[] stringArray = this.UserName.Split(new Char[] { '\\' });
this.UserName = stringArray[1];
MyUser identity = userRepository.Get(u => u.Username == this.UserName).FirstOrDefault();
HttpContext.Current.User = identity;
}

Related

debugging or error log for UseWindowsAzureActiveDirectoryBearerAuthentication in a azure web site?

I have an asp.net azure web api site, say myapi.azuresites.net, and my custom domain is myapi.mycompany.net.
In my web api, I use owin middleware to validate incoming token
app.UseWindowsAzureActiveDirectoryBearerAuthentication(
new WindowsAzureActiveDirectoryBearerAuthenticationOptions
{
Tenant = Constants.AzureActiveDirectoryTenant,
TokenValidationParameters = new TokenValidationParameters
{
ValidateAudience = true,
// These values will be checked against what is received in the access token.
ValidAudiences = Constants.AzureActiveDirectoryValidAudiences
},
Provider = new OAuthBearerAuthenticationProviderEx()
});
I registered an app under azure AD and add some client secret in.
From postman, I can get an oauth2 token from Azure AD with the App id and the client secret.
I included this token in the header and sends to my azure web api.
My code uses owin middleware to validate the token
If I send the request to myapi.mycompany.net, the token validation works.
If I send the request to myapi.azuresites.net, the token validation fails.
I can't really figure out why the token validation fails when calling azure site directly. If I grab the azure site's web.config down to my local machine and it works there as well.
I suspected that my AD app didn't have the right redirect URLs, but verified that and can't see obvious issue.
So is there a way to log some information on why authentication fails? As it is a remote azure site, can I trap this failure as exception and throw some out?
Although not sure why my AD authentication works now, I did find a way to log owin failures for azure site.
Basically this will log owin information
<system.diagnostics>
<trace autoflush="true"/>
<sources>
<source name="Microsoft.Owin">
<listeners>
<add name="KatanaListener"/>
</listeners>
</source>
</sources>
<sharedListeners>
<add name="KatanaListener"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="d:\home\logfiles\Katana.trace.log"
traceOutputOptions="ProcessId, DateTime"/>
</sharedListeners>
<switches>
<add name="Microsoft.Owin" value="Verbose"/>
</switches>
</system.diagnostics>

ADALjs and Azure AD auth for Wep API project

I have a client app and Web API app hosted on different domains and want to utilize ADAL.js in my client app to login in my Web API app, but still getting Unauthorized error.
In web api web.config I've specified my AAD details:
<add key="ida:AudienceUri" value="http://clientappurl/" />
<add key="ida:FederationMetadataLocation" value="https://login.windows.net/...3596365/federationmetadata/2007-06/federationmetadata.xml" />
<add key="ida:ClientId" value=".....388ffcc3" />
<add key="ida:ClientSecret" value="....gBsD7o=" />
<add key="ida:Tenant" value="........onmicrosoft.com" />
<add key="ida:TenantId" value="........96365" />
<add key="ida:Auth" value="https://login.windows.net/" />
<add key="ida:GraphUrl" value="https://graph.windows.net" />
And updated Startup.Auth.cs with following:
app.UseWindowsAzureActiveDirectoryBearerAuthentication(
new WindowsAzureActiveDirectoryBearerAuthenticationOptions
{
Audience = "http://myclientapp",
Tenant = "developertenant.onmicrosoft.com",
AuthenticationType = "OAuth2Bearer",
});
On the client I've specified endpoints (my api url), tenant and clientId. ADALjs redirects user to microsoft login page and looks like after sucessfull login it writes some data to local storage. But API app still respondes with Unauthorized error.
Are there any tutorials on how properly configure wep api and client apps hosted on different domains to utilize AAD?
How can I read authorized user details like AAD user group from my Web API app?
Here is an example which shows how to read AAD group claims from a web app:
https://github.com/Azure-Samples/active-directory-dotnet-webapp-groupclaims
Once you have the tokens, you can then call a Web API, which is shown by this example:
https://github.com/Azure-Samples/active-directory-dotnet-webapp-webapi-openidconnect
There's a good list of AAD examples here:
https://azure.microsoft.com/en-us/documentation/articles/active-directory-authentication-scenarios/

Unauthenticated user redirection for a custom membership system mvc5

I am developing an erp system using mvc5. i have my own membership system built and user and his user permission is kept in a session variable once a user logged in. Authorization part is almost done i suppose. But for authentication now im trying to restrict access for unauthenticated users. I tried it like this
in my web.config
<authentication mode="Forms">
<forms loginUrl="~/Login/Login" timeout="2880" />
</authentication>
and on controllers i put [Authorize] attribute.
This works fine for unauthenticated users. They are redirected to login page. But this restricts the access of authenticated users as well.(This means neither unauthenticated nor authenticated user can access the controllers which has authorize attribute).
If i remove authorize attribute it gives me an error since there is no user to be assigned to session variable. This implies that without authorize attribute
unauthenticated user can access the controllers even-though the web.config has been modified.
I think this involves creating a custom attribute. But i don't know how to approach this. All help appreciated. Thanks in advance!
After a research i came up with the solution.
I created a custom authorize attribute.
public class CustomAuthorize : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var authroized = base.AuthorizeCore(httpContext);
// Now check the session:
var myvar = httpContext.Session["User"];
if (myvar == null)
{
// the session has expired
return false;
}
return true;
}
}
And on my controllers instead of [authorize] i put [CustomAuthorize].
In web.config
<authentication mode="Forms">
<forms loginUrl="~/Login/Login" timeout="2880" />
</authentication>

Custom provider in the url rewrite module

I am developing on a website which is currently hosted in Azure on a VM. Now I am changing this website to be able to run it as an Azure website.
Now my problem:
I am using the url rewrite module from IIS with the database provider, which works perfectly in the VM. With the database provider users of the website can create their own simple rewrite rules.
But when I upload my website as an Azure Website and I access a url that's specified in the database I get an error:
"The page cannot be displayed because an internal server error has occurred.".
This is the logging configuration I currently use:
<rewrite>
<rules configSource="RewriteInbound_Live.config" />
<outboundRules configSource="RewriteOutbound_Live.config" />
<providers>
<provider name="DB" type="DbProvider, Microsoft.Web.Iis.Rewrite.Providers, Version=7.1.761.0, Culture=neutral, PublicKeyToken=0545b0627da60a5f">
<settings>
<add key="ConnectionString" value="*****" />
<add key="StoredProcedure" value="sp_GetRewrittenUrl" />
<add key="CacheMinutesInterval" value="60" />
</settings>
</provider>
</providers>
</rewrite>
I've turned on web server logging which doesn't give me any information, and I've enabled application logging which also doesn't give me any information.
My question, is it possible to use custom providers for the url rewite module in Azure, of can this be achieved in another way?
I had the same problem: DbProvider not available in azure web app. So I left most of the url rewriting stuff in the web.config untouched and moved the database-based rules to the global.asax file's Application_BeginRequest method.
For redirect rules, just use a Response.Redirect or an adequate Redirect301 implementation. On the other hand, for the rewrites, use HttpContext.Current.RewritePath.
You should add a caching mechanism in order to reduce repetitive queries to the DB:
void Application_BeginRequest(Object sender, EventArgs e)
{
//TODO: Cache sql queries
string requestUrl = Request.FilePath;
using (DBConn conn = new DBConn("GetRedirectUrl"))
{
conn["input"] = requestUrl;
string res = conn.ExecuteScalar()?.ToString();
if (!string.IsNullOrEmpty(res))
{
Response.Redirect301(res);
}
}
//TODO: Cache sql queries
using (DBConn conn = new DBConn("GetRewrittenUrl"))
{
conn["input"] = requestUrl;
string res = conn.ExecuteScalar()?.ToString();
if (!string.IsNullOrEmpty(res))
{
HttpContext.Current.RewritePath(res);
}
}
}

I can retrieve all user names from active directory group on local server but on IIS showing exceptional error

I am new user for stachoverflow, I am developing one web application for intranet in which it authenticate user from active directory which works fine on IIS but I am getting problem to retrieve data(all user names) from group of active directory which works fine on local server.
on IIS it gives exceptiona error- System.DirectoryServices.DirectoryServicesCOMException: Logon failure: unknown user name or bad password.
in IIS windows authentication enabled and other are disabled
My code is:
Web.config file:
<authentication mode="Windows">
<forms loginUrl="~/TTracker/Login.aspx" timeout="600"></forms>
</authentication>
<authorization>
<deny users="?"/>
<allow users="*" />
</authorization>
<identity impersonate="true" />
Code for retrieving data:
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
using (HostingEnvironment.Impersonate())
{
DropDownList1.Items.Add(new ListItem("-Select-", ""));
string grpname = "Group1";
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "domain");
GroupPrincipal grp = GroupPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, grpname);
if (grp != null)
{
foreach (Principal p in grp.GetMembers(false))
{
DropDownList1.Items.Add(p.SamAccountName + "-" + p.DisplayName);
}
grp.Dispose();
ctx.Dispose();
Console.ReadLine();
}
else
{
Console.WriteLine("We did not find that group.");
Console.ReadLine();
}
}
this is my code for retrieving data from active directory which works fine locally but not works on IIS.
It will be great help if any one solve this issue.
Thanks in advance.
It's related to Impersonation.
Please check the following,
We can impersonate an account to process with AD.
ASP.NET Impersonation
http://msdn.microsoft.com/en-us/library/aa292118(VS.71).aspx
And read this document.
Howto: (Almost) Everything In Active Directory via C#
http://www.codeproject.com/KB/system/everythingInAD.aspx

Resources