Secure asp.net core 2.0 webapi with Identityserver3 - asp.net-core-2.0

I am completely new to Identityserver and authorization.
There is an authorization server build using Identityserver3. It works fine with asp.net mvc 5 application.
Now i am trying to use this authorization server to secure the new asp.net core 2.0 webapi.
I couldn't find any good document about how to do this. Can anyone help how to do achieve this?
Thanks

The same way as you will do it if you use IdentityServer 4. In your .NET Core 2.0 Web API, in the Startup.cs :
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMvcCore()
.AddAuthorization()
.AddJsonFormatters();
services.AddAuthentication("Bearer")
.AddIdentityServerAuthentication(options =>
{
options.Authority = "<identityserverurl>";
options.RequireHttpsMetadata = false;
options.ApiName = "mynetcoreapi";
});
}
public void Configure(IApplicationBuilder app)
{
app.UseAuthentication();
app.UseMvc();
}
}
and of course you need IdentityServer4.AccessTokenValidation package, but it is a .NET Core package, so you shouldn't have any problems.
PS: Don't forget to setup logging (if it is not already done) in your IdentityServer. Helps a lot

Related

How to acquire a token with Azure AD and MSAL in ASP.NET

I'm trying to authenticate a token using Azure AD. In a console application, I have no problem with this thanks to IConfidentialClientApplication:
static void Main(string[] args)
{
Console.WriteLine("Making the call...");
RunAsync().GetAwaiter().GetResult();
}
private static async Task RunAsync()
{
AuthConfig config = AuthConfig.ReadJsonFromFile("appsettings.json");
IConfidentialClientApplication app;
app = ConfidentialClientApplicationBuilder.Create(config.ClientId)
.WithClientSecret(config.ClientSecret)
.WithAuthority(new Uri(config.Authority))
.Build();
string[] ResourceIds = new string[] { config.ResourceId };
AuthenticationResult result = null;
try
{
result = await app.AcquireTokenForClient(ResourceIds).ExecuteAsync();
}
...
}
But in a Startup for an ASP.NET Core application, the app uses the standard IApplicationBuilder and the Configure(...) method can't take an IConfidentialClientApplicationBuilder as it doesn't exist.
In Microsoft's documentation, they create a PublicClientApplicationBuilder, but I don't want to start creating entirely new applications in my configuration.
Here is a sample of Startup for ASP.NET Core application for your reference. But as far as I know we can't get token directly in the Startup for ASP.NET Core application with "IApplicationBuilder". "IApplicationBuilder" and "IConfidentialClientApplicationBuilder" are two different concepts.
For your requirement, you can just import modules for msal and use the code you provided above or the code you mentioned in the Microsoft's documentation to get the token.

Use Azure AD B2C for WebApi auth in aspnetboilerplate from a SPA

I have a SPA web app written in Vue that is able to login to AADB2C directly without ABP and I get a good api token response for it.
For my backend WebApi project, I would like to use all of the nice features of ABP, but I would like to replace the authentication piece of ABP with AADB2C calls. To do this, I replaced the AddAuthentication() call in Startup like this … (.net core)
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
IdentityRegistrar.Register(services); // ABP generated
// I removed this code …
// AuthConfigurer.Configure(services, _appConfiguration); // ABP generated
// I added this code from a generated webapi project startup file that I know works separately …
services.AddAuthentication(AzureADB2CDefaults.BearerAuthenticationScheme)
.AddAzureADB2CBearer(options => Configuration.Bind("AzureAdB2C", options));
...
}
How do I get ABP to recognize this and validate an external jwt token and create a new AbpUser? It would be great to use all of the AbpAuthorize attributes on the abp app services this way.
I saw this advice, but it seems like I would need to call out to B2C myself this way …
https://aspnetboilerplate.com/Pages/Documents/Zero/User-Management?searchKey=authentication#external-authentication
Thanks
--Andy

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:

ASP.Net Core 2.0 Webapi set log4net

I am new to asp.net core 2.0. I creating a webapi and want to configure log4net as my logging provider.
I couldn't find some working example in net. Can anyone help me provide the right link or some sample code about how to properly setup log4net in asp.net core 2.0
Things i have done so far is as below and i am not sure how to proceed further.
installed log4net.Extensions.AspNetCore;
Startup.cs
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
loggerFactory.AddLog4Net();
// Enable CORS
app.UseCors(builder => builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
app.UseMvc();
}
Install nuget for Microsoft.Extensions.Logging.Log4Net.AspNetCore (https://www.nuget.org/packages/Microsoft.Extensions.Logging.Log4Net.AspNetCore/)
In Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) call loggerFactory.AddLog4Net();
Create log4net.config
More info -> https://github.com/huorswords/Microsoft.Extensions.Logging.Log4Net.AspNetCore

Using Owin in .Net Core for 3rd Party Authentication

I am trying to use third party sign on authentication in a .net core web application solution I am creating. I am trying to use the Owin package to do so. I have looked at an example of Owin in .net framework, I have been trying to translate this to the .net core application but I have been very unsuccessful.
If someone could point me to an example of a .net core web application that is using Owin for 3rd party authentication it would be greatly appreciated.
Here is the the startup file for a framework web application:
using Microsoft.AspNet.Identity;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.Facebook;
using Microsoft.Owin.Security.Google;
using Owin;
[assembly: OwinStartupAttribute(typeof(Identity.Startup))]
namespace Identity
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
}
}
public void ConfigureAuth(IAppBuilder app)
{
// Enable the application to use a cookie to store information for the signed in user
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login")
});
// Use a cookie to temporarily store information about a user logging in with a third party login provider
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
// Uncomment the following lines to enable logging in with third party login providers
//app.UseMicrosoftAccountAuthentication(
// clientId: "",
// clientSecret: "");
/* app.UseTwitterAuthentication(
consumerKey: "",
consumerSecret: "");*/
app.UseFacebookAuthentication(
appId: "myid",
appSecret: "mysecret");
//app.UseGoogleAuthentication();
}
}
I Want to replicate this in .net core now. However, I cannot reproduce the Microsoft.Owin.Security dependency. I have tried Microsoft.AspNetCore.Owin.Security and it does not resolve.

Resources