Azure AD Auth against ProtectedWebWebi - azure

I downloaded the Azure examples for daemon app, and have a bearer token at the end of the debug code. The thing that I'm stuck on is calling the Web API with this token to Authenticate. This is in .NET Core 2.2
public void ConfigureServices(IServiceCollection services)
{
// This is required to be instantiated before the OpenIdConnectOptions starts getting configured.
// By default, the claims mapping will map claim names in the old format to accommodate older SAML applications.
// 'http://schemas.microsoft.com/ws/2008/06/identity/claims/role' instead of 'roles'
// This flag ensures that the ClaimsIdentity claims collection will be built from the claims in the token
JwtSecurityTokenHandler.DefaultMapInboundClaims = false;
services.AddProtectWebApiWithMicrosoftIdentityPlatformV2(Configuration);
services.Configure<JwtBearerOptions>(AzureADDefaults.JwtBearerAuthenticationScheme, options =>
{
//options.TokenValidationParameters.RoleClaimType = "roles";
});
//// Creating policies that wraps the authorization requirements
services.AddAuthorization(options =>
{
options.AddPolicy("AdminUsers", policy => policy.RequireRole("AdminUsers"));
});
services.AddControllers();
}
[HttpGet]
[Authorize]
public IActionResult Get()
{
return Ok(TodoStore.Values);
}
I took the roles out and just made it available to everyone, not sure if I need to put Group authorization on here for it to work. I can't get it to work out of the box. I'm thinking of modifying some of these to make it work. We only need to authenticate, then use their email to get roles base on which application they are in.
Thanks in advance.

Please refer this Microsoft documentation
For daemon apps, the web APIs that you call need to be pre-approved.
There's no incremental consent with daemon apps. (There's no user
interaction.) The tenant admin needs to provide consent in advance for
the application and all the API permissions.
and there is a GitHub sample for daemon application which consume Web Api and if you are trying to verify app roles in the APIs called by a Daemon apps please go through this documentation

Related

Is it possible to include groups in JWT token in case of implicit flow?

Hi I am working on Azure AD and .net core application. I am trying to implement authentication and authorization. I have swagger configured with my .net core application. I am able to do authentication using swagger. Currently I have about 100 groups where I am part of. I am using implicit grant flow for swagger authentication. As per documentations I have gone through,
If there are more than 5 groups then JWT token will include "hasgroups": "true" and - In my case I am able to see "hasgroups": "true" in JWT token.
If group is synchronized to Azure AD using Azure AD Connect, you can then display the group name - In my case synchronized to Azure AD using Azure AD Connect but I am not able to see ids nor names.
I have more than 100 groups so due to url restriction it is impossible to get groups when we are using implicit flow.
Also, If I have only back-end apis, In that case which authorization flow is recommended to use? API will know nothing of the calling app.
In implicit flow there will be only call to azure ad to get Access token and In authorization grant flow there will be two calls one for to get authorization code and then using authorization code to get access token. This is my understanding. I am not sure If I understood this correctly or not.
Can someone help me to understand above two points? I am having some confusion over the above two points. Any help would be appreciated in this regard. Thanks
Below is my swagger implementation.
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
c.AddSecurityDefinition("oauth2", new OAuth2Scheme
{
Type = "oauth2",
Flow = "implicit",
AuthorizationUrl = swaggerUIOptions.AuthorizationUrl,
TokenUrl = swaggerUIOptions.TokenUrl,
Scopes = new Dictionary<string, string>
{
{"Read", "guid/.default" }
}
});
c.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>>
{
{ "oauth2", new[] { "readAccess", "writeAccess" } }
});
});
In Configure,
app.UseSwaggerUI(c =>
{
c.OAuthClientId(swaggerUIOptions.ClientId);
c.OAuthClientSecret(swaggerUIOptions.ClientSecret);
c.OAuthRealm(azureActiveDirectoryOptions.ClientId);
c.OAuthAppName("Swagger");
c.OAuthAdditionalQueryStringParams(new { resource = azureActiveDirectoryOptions.ClientId });
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});
If a user has too many groups, they won't be in the access token.
The limit is smaller for implicit flow since the token is returned in the URL.
In those cases your back-end needs to check group memberships via Microsoft Graph API.

Identity Server 4 asp.net 2.1 - IProfileService or alternative

I will buy anyone a beer who can solve my problem!
As a piece of work I need to update our Identity Server to use an implicit login flow, it was currently using Bearer Token access only. As a part of our architecture we are using Multi-tenancy.
For security reaosns we need to check the tenant header to verify that the user is not impersonating another tenant. To do this from a client perspective we use a custom IProfileService. This gets triggered in the middleware of Identity Server, meaning all is good!
However if I was a user and I wanted to use some form of functionality on Identity Server itself and not an actual client of it, then IProfileService will not be triggered. An example of this would be to revoke access to clients, or even log out.
The GetProfileDataAsync Method on IProfileService is Invoked when the client request additional claims for the user.
germansak on Github Issue here had a similar issue and it was never quite answered (https://github.com/IdentityServer/IdentityServer4/issues/1643)
Leading to my question, how has anyone been able to verify a Tenant on Identity Server itself when they are not going through a Client, but instead Identity Server. If I can't trigger IProfileService I feel as if I'm beat!
Both logout and grants functionality is not part of the identity server 4 core package and they are simply implemented as ASP.NET Core razor views outside of the oauth2 flows.
There are few ways to validate headers therefore, I guess the easiest in my opinion would be to add another middleware.
public void Configure(IApplicationBuilder app)
{
app.UseMiddleware<TenantHeaderValidationMiddleware>();
...Your other config
}
public class TenantHeaderValidationMiddleware
{
private readonly RequestDelegate _next;
public RequestCultureMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
string tenantId = Request.Headers["YourTenantIdHeader"];
//do the checking
...Validation logic
//pass request further if correct
await _next(context);
}
}

How does [Authorize] attribute enhance Azure App Service (web app) authentication/authorization

I published a web app to Azures App Services. I used the App Service's Authentication/Authorization feature to provide security. I successfully added Active Directory features to my web service (and desktop client). It seemed to work very well. Couldn't access data from a browser or desktop client without signing in to the AD.
This was all before I added the [Authorize] attribute to any of the controllers in the API!
So, what will [Authorize] do (or add) to security in my web api. It seems to already be locked up by configuring the Authentication/Authorization features of the web app in Azure.
So, what will [Authorize] do (or add) to security in my web api.
Using ILSpy, you could check the source code about AuthorizeAttribute under System.Web.Mvc.dll. The core code for authorization check looks like this:
protected virtual bool AuthorizeCore(HttpContextBase httpContext)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
IPrincipal user = httpContext.User;
if (!user.Identity.IsAuthenticated)
{
return false;
}
if (_usersSplit.Length > 0 && !_usersSplit.Contains(user.Identity.Name, StringComparer.OrdinalIgnoreCase))
{
return false;
}
if (_rolesSplit.Length > 0)
{
string[] rolesSplit = _rolesSplit;
IPrincipal principal = user;
if (!rolesSplit.Any(principal.IsInRole))
{
return false;
}
}
return true;
}
The main process would check httpContext.User.Identity.IsAuthenticated, then check whether the current user name, user role is authorized or not when you specifying the allowed Users,Roles.
For Authentication and authorization in Azure App Service(Easy Auth) which is implemented as a native IIS module. Details you could follow Architecture of Azure App Service Authentication / Authorization.
It seemed to work very well. Couldn't access data from a browser or desktop client without signing in to the AD.
This was all before I added the [Authorize] attribute to any of the controllers in the API!
Based on your description, I assumed that you set Action to take when request is not authenticated to Log in with Azure Active Directory instead of Allow Anonymous requests (no action) under your Azure Web App Authentication/Authorization blade.
Per my understanding, you could just leverage App Service Authentication / Authorization which provides built-in authentication and authorization support for you without manually adding middleware in your code for authentication. App service authentication would validate the request before your code can process it. So, for additional custom authorization check in your code, you could define your custom authorize class which inherits from AuthorizeAttribute to implement your custom processing.
public class CustomAuthorize : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
//TODO:
}
protected override void HandleUnauthorizedRequest(System.Web.Mvc.AuthorizationContext filterContext)
{
//TODO:
}
}
Then, decorate the specific action(s) or controller(s) as follows:
[CustomAuthorize]
public class UsersController : Controller
{
//TODO:
}
App Service's Authentication/Authorization feature is Based on IIS Level. [Authorize] attribute is based on our code level. Both of this can do Authentication, if you used both of them, it means that there are two levels of authentication in your web app.
Here is a picture that helps you understand them:

Azure AD Claims in IdentityServer4

I have taken this sample from github to attempt to use IdentityServer4 and Azure AD for authentication.
While I have it working and returning a token, it seems that the claims that I would have expected to receive from Azure AD are not included in the token(s) issued through IdentityServer.
It could be that this is intentional and that I have misunderstood this flow, but I was hoping that the roles that a user is assigned through Azure AD (plus the tenant ID and other useful 'bits' from the Azure token) would be able to be included in the tokens issued to the client.
Would anyone be able to shed some light on this for me? I can paste code in here but the link to the github code is pretty much the same as what I am using.
I was trying to do the same thing, and managed to eventually piece bits together from looking at the IS4 docs, Github and StackOverflow.
You need to configure a new instance of IProfileService (Docs) in order to tell IdentityServer4 which additional claims for a user's identity (obtained from Azure AD in your case) you want to be passed back to the client.
An example might look like this:
public class CustomProfileService : IProfileService
{
public Task GetProfileDataAsync(ProfileDataRequestContext context)
{
// Get the 'upn' claim out from the identity token returned from Azure AD.
var upnClaim = context.Subject.FindFirst(c => c.Type == ClaimTypes.Upn);
// Get 'firstname' and 'givenname' claims from the identity token returned from Azure AD.
var givenNameClaim = context.Subject.FindFirst(c => c.Type == ClaimTypes.GivenName);
var surNameClaim = context.Subject.FindFirst(c => c.Type == ClaimTypes.Surname);
// Add the retrieved claims into the token sent from IdentityServer to the client.
context.IssuedClaims.Add(upnClaim);
context.IssuedClaims.Add(givenNameClaim);
context.IssuedClaims.Add(surNameClaim);
}
public Task IsActiveAsync(IsActiveContext context)
{
context.IsActive = true;
return Task.CompletedTask;
}
}
You will then need to register this service in Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddIdentityServer()
.AddDeveloperSigningCredential()
// Register the new profile service.
.AddProfileService<CustomProfileService>();
}
Finally, inside of your AccountController.cs (within the IdentityServer4 project - I'm assuming you already have this, see here for a starter setup if not), you need to add the following to ExternalLoginCallback():
[HttpGet]
public async Task<IActionResult> ExternalLoginCallback()
{
//...
// this allows us to collect any additonal claims or properties
// for the specific protocols used and store them in the local auth cookie.
// this is typically used to store data needed for signout from those protocols.
var additionalLocalClaims = new List<Claim>();
// ADD THIS LINE TO TELL IS4 TO ADD IN THE CLAIMS FROM AZURE AD OR ANOTHER EXTERNAL IDP.
additionalLocalClaims.AddRange(claims);
//...
}
Hope this helps.

Azure ACS, WIF 3.5, Asp.Net 3.5 Custom Membership Provider and IsAuthenticated

Following the steps in this guide Using Azure ACS I have a working Azure ACS service configured & authenticating via Facebook, redirecting back to a website running on my development server.
On authentication success Azure ACS redirects back to my local development website and the IsAuthenticated flag is true, however I want to set the IsAuthenticated flag to true only if the email from the claim also exists in my local database, via a check/call to a custom MembershipProvider. If the email from the claim does not exist I want to redirect the client to a register page. Once registered and authenticated I would like to set the IsAuthenticated flag to true.
Currently once authenticated with Facebook and AzureACS, a user can request a secure page such as ViewAccountBalance.aspx, even though the account does not exist since out of the box IsAuthenticated flag to true. Interested to hear what others have done and what the best practice is.
You'll need to make a clear difference between authentication and authorization. Since the user logged in through Facebook it means he's authenticated (you know who he is and where he comes from).
Now, if you want to restrict parts of the application based on a specific condition you're actually talking about authorization. You might consider combining roles with a simple HttpModule. Example: your HttpModule could verify which page the user is browsing. If the user accesses a page that requires an active profile, you could use the following code:
public class RequiresProfileHttpModule : IHttpModule
{
public void Dispose()
{
}
public void Init(HttpApplication context)
{
context.AuthorizeRequest += new EventHandler(OnAuthorize);
}
private void OnAuthorize(object sender, EventArgs e)
{
HttpApplication app = sender as HttpApplication;
if (app.Request.Url.ToString().Contains("bla") && !app.Context.User.IsInRole("UsersWithProfile"))
app.Response.Redirect("http://myapp/register.aspx");
}
}
The only thing you'll need to take care of is to update the principal to make sure it has the role UsersWithProfile if the user filled in his email address.
This is just one of many possible solutions. If you're using ASP.NET MVC you could achieve the same result with global ActionFilters. Or, you could also try to work with the IClaimsPrincipal (add a claim if the user has a profile).
Sandrino is correct. You can use role based authorization (or more generally, claim based authorization). By default, ACS simply returns the claims issued by the identity providers to your relying party. For Facebook, it will return an email claim. However, you can configure ACS to create additional rules. For example, you can map particular users to a role whose value is administrator. Then ACS will also return this role claim to your relying party. Then you can use Sandrino’s suggestion to use role based authorization. You can also refer to http://msdn.microsoft.com/en-us/library/windowsazure/gg185915.aspx for more information.

Resources