Comparing the backend for frontend (BFF) security architecture with an SPA UI using a public API

This article compares the security architecture of an application implemented using a public UI SPA with a trusted API backend and the same solution implemented using the backend for frontend (BFF) security architecture. The main difference is that the first solution is separated into two applications, implemented and deployed as two where as the second application is a single deployment and secured as a single application. The BFF has less risks and is a better security architecture but as always, no solution is perfect.

Setup BFF

The BFF solution is implemented and deployed as a single trusted application. All security is implemented in the trusted backend. The UI part of the application can only use the same domain APIs and cannot use APIs from separate domains. This architecture is the same as a standard ASP.NET Core Razor page UI confidential client. All APIs can be implemented in the same server part of the application. There is no requirement for downstream APIs. Due to this architecture, no sensitive data needs to be saved in the browser. This is effectively a trusted server rendered application. As with any server rendered application, this is protected using cookies with the required cookie protections and normally authenticates against an OIDC server using a trusted, confidential client with code flow and PKCE protection. Because the application is trusted, further protections can be added as required for example MTLS, further OIDC FAPI requirements and so on. If downstream APIs are required, these APIs do not need to be exposed in the public zone (internet) and can be implemented using a trusted client and with token binding between the client and the server. The XSS protection can be improved using a better CSP and all front-channel cross-domain calls can be completely blocked. Dynamic data (ie nonces) can be used to produce the CSP. The UI can be hosted using a server rendered page and dynamic meta data and settings can easily be added for the UI without further architecture or DevOps flows. I always host the UI part in a BFF using a server rendered file. A big win with the BFF architecture, is that the access tokens and the refresh tokens are not stored publicly in the browser. When using SignalR, the secure same site HTTP only cookie can be used and no token for authorization is required in the URL. This is an improvement as long as CSRF protection is applied. Extra CSRF protection is required for all server requests because cookies are used (as well as same site). This can be implemented using anti-forgery tokens or forcing CORS preflight using a custom header. This must be enforced on the backend for all HTTP requests where required. Because only a single application needs to be deployed, DevOPs is simpler and reduces complexity, this is my experience after using this in production with Blazor. Reduced complexity is reduced costs.

Setup SPA with public API

An SPA page solution is deployed as a separate UI application and a separate public API application. Two security flows are used in this setup and are two completely separate applications, even though the API and UI are “business” tightly coupled. The best and most productive solutions with this setup are where the backend APIs are made specifically and optimized for the UI. The API must be public if the SPA is public. The SPA has no backend which can be used for security, tokens and sensitive data are stored in the browser and needs to be accessed using Javascript. As XSS is very hard to protect against, this will always have security risks. When using SPAs, as the access tokens are shared around the browser or added to URLs for web sockets, it is really important to revoke the tokens on a logout. The refresh token requires specific protections for usage in SPAs. Access tokens cannot be revoked and reference tokens with introspection used in the API is the preferred security solution. A logout is possible with introspection and reference tokens using the revocation endpoint. It is very hard to implement a SSO logout when using an SPA. This is because only the front-channel logout is possible in an SPA and not a back-channel logout as with a server rendered application. This setup has performance advantages compared to the BFF architecture when using downstream APIs. The APIs from different domains can be used directly. Implementing UIs with PWA requirements is easier to implement compared to the BFF architecture. CSRF attacks are easier to secure against using tokens but has more risk with an XSS attack due to sensitive data in the public client.

Advantages using BFF

Single trusted application instead of two apps, public untrusted UI + public trusted API (reduced attack surface)
Trusted client protected with a secret or certificate
No access/reference tokens in the browser
No refresh token in the browser
Web sockets security improved (SignalR), no access/reference token in the URL
Backchannel logout, SSO logout possible
Improved CSP and security headers (can use dynamic data and block all other domains) => possible for better protection against XSS (depends on UI tech stack)
Can use MTLS, OIDC FAPI, client binding for all downstream API calls from trusted UI app, so much improved security possible for the downstream API calls.
No architecture requirement for public APIs outside same domain, downstream APIs can be deployed in a private trusted zone.
Easier to build, deploy (my experience so far), Easier for me means reduced costs.
Reduced maintenance due to reduced complexity. (This is my experience so far)

Disadvantages using BFF

Downstream APIs require redirect or second API call (YARP, OBO, •OAuth2 Resource Owner Credentials Flow, certificate auth )
PWA support not out of the box
Performance worse if downstream APIs required (i.e an API call not on the same domain)
All UI API POST, DELETE, PATCH, PUT HTTP requests must use anti-forgery token or force CORS preflight as well as same site protection.
Cookies are hard to invalidate, requires extra logic (Is this required for a secure HTTP only same site cookie? low risk)

Discussions

I have had some excellent discussions on this topic and very valid points and arguments against some of points above. I would recommend reading these (link below) to get a bigger picture. Thanks kevin_chalet for the great feedback and comments.

https://github.com/openiddict/openiddict-samples/issues/180

Notes

A lot of opinions exist with this setup and I am sure lots of people see this in a different way with very valid points. Others are following software tech religions which prevents them accessing, evaluating different solution architectures. Nothing is ever black or white. No one solution is best for everything and all solutions have problems, or future problems with any setup will always happen. I believe using the BFF architecture, I can increase the security for the solutions with less effort and reduce the security risks and costs, thus creating more value for my clients. I still use SPA with APIs and see this as a valuable and good security solution for some systems. The entry level for BFF architecture with some tech stacks is still very high.

Links

https://github.com/damienbod/Blazor.BFF.AzureAD.Template

https://github.com/damienbod/Blazor.BFF.AzureB2C.Template

https://github.com/damienbod/Blazor.BFF.OpenIDConnect.Template

https://github.com/DuendeSoftware/BFF

https://github.com/manfredsteyer/yarp-auth-proxy

https://docs.microsoft.com/en-us/aspnet/core/blazor/

https://docs.duendesoftware.com/identityserver/v5/bff/overview/

https://github.com/berhir/BlazorWebAssemblyCookieAuth

https://github.com/manfredsteyer/yarp-auth-proxy

OIDC FAPI

https://www.cloudflare.com/learning/access-management/what-is-mutual-tls/

https://csp-evaluator.withgoogle.com/

https://docs.microsoft.com/en-us/aspnet/signalr/overview/getting-started/introduction-to-signalr

https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-on-behalf-of-flow

https://microsoft.github.io/reverse-proxy/index.html

https://docs.microsoft.com/en-us/aspnet/core/security/authentication/certauth

https://github.com/openiddict/openiddict-samples/issues/180

https://www.w3.org/TR/CSP3/

https://content-security-policy.com/

https://csp.withgoogle.com/docs/strict-csp.html

https://github.com/manfredsteyer/angular-oauth2-oidc

https://github.com/damienbod/angular-auth-oidc-client

https://docs.microsoft.com/en-us/azure/active-directory/develop/msal-overview

https://github.com/AzureAD/microsoft-identity-web

https://github.com/damienbod/AspNetCoreOpeniddict

https://github.com/openiddict/openiddict-samples

Outreach Committee January 2020

New year, new you? If you’re passionate about .NET and are ready to help the .NET Foundation’s Outreach Committee achieve it’s goals, then it’s time to volunteer.

Our meetings are public and anyone can attend. The outreach committee is here to welcome developers of all backgrounds, education, and technology experience into the .NET ecosystem. We are here to help you organize and evangelize with your own .NET communities, opportunities, and events.

Please join us on January 11th at 3pm ET/noon PT/8pm GMT/7am AEDT on Teams at:

January 2020 Outreach Committee Meeting

TIA!

Shawn Wildermuth
.NET Foundation Outreach Committee

Announcing .NET MAUI Preview 11

Today we are pleased to share .NET Multi-platform App UI (MAUI) Preview 11. In this release we have added the first batch of Fluent UI control styling, multi-window implementations, control features, and another set of iOS type alignment. These ongoing .NET MAUI previews run on the latest preview of .NET 6 and are available with the new Visual Studio 2022 17.1 Preview 2 on Windows shipping today. We are on track to ship a release candidate in Q1 2022, and final release in Q2 2022.

The source for the .NET Podcast app showcased at .NET Conf 2021 has been published, and includes Blazor, .NET MAUI, and .NET MAUI Blazor Hybrid apps.

Let’s take a deeper look at the highlights in preview 11.

Windows Control Styling with the Fluent Design System

.NET MAUI provides platform-specific design and experience by default, so your apps get the right look and feel for each platform from a single code base without any additional effort. Windows 11 introduces new UI styling with the updated Fluent Design System, and .NET MAUI styles all controls to use the latest. Subsequent previews will build upon this, adding more controls and support for themes. In Preview 11 you will see initial updates to:

Button
Editor
Entry

Multi-window Apps

One of the major updates to .NET MAUI compared to Xamarin.Forms is introducing multiple windows. Application.Current.Windows holds references to all windows you have created. To open a new window, it’s as simple as:

var secondWindow = new Window {
Page = new MySecondPage {
// …
}
};

Application.Current.OpenWindow(secondWindow);

To try this today targeting macOS and iPadOS, add a SceneDelegate to each respective platform folder and update your info.plist to enable scenes.

Did you know? This image is an iPad simulator running on Windows using the Remoted iOS Simulator available when you connect to a Mac build host. Alternatively, you can debug any .NET MAUI app on a device running iPadOS (or iOS) directly from Visual Studio 2022 on Windows using Hot Restart.

The Windows App SDK implementation of multi-window will be in an experimental release until release in v1.1 (see roadmap).

Templates and C# 10

Simplification is one of the main goals of .NET MAUI, to make it easier for everyone to build great apps. Going from multiple projects per platform to a single project is just one example of how we are doing that. In this release we have updated the templates using C# 10 patterns such as implicit usings and file-scoped namespaces, and added item templates for ContentPage and ContentView. Now when your project opts-in to using ImplicitUsings you’ll see a cleaner project file like our template’s MauiProgram.cs.

namespace Preview11;

public static class MauiProgram
{
public static MauiApp CreateMauiApp()
{
var builder = MauiApp.CreateBuilder();
builder
.UseMauiApp<App>()
.ConfigureFonts(fonts =>
{
fonts.AddFont(“OpenSans-Regular.ttf”, “OpenSansRegular”);
});

return builder.Build();
}
}

So, where did all the using statements go? We use implicit global usings to gather them dynamically so you don’t need to worry about it.

iOS, macOS, and tvOS Type Alignment

As part of unifying Xamarin SDKs with .NET 6, we have been working through updating our Apple related SDKs to use the native nint and nuint types in .NET 6 rather than System.nint and System.nuint. This impacts existing libraries built for iOS, macOS, and tvOS using .NET 6. To adopt this change you must recompile your code against .NET 6, and if you explicitly use the types above you should update your .NET 6 code to use the C# types.

Read the issue for this change on GitHub for more details.

New .NET MAUI Documentation

We have published a new batch of documentation for .NET MAUI including new guides for Accessibility, BlazorWebView, Border, GraphicsView, Maui.Graphics, Shadows, Splash Screen, multi-targeting, and how you can invoke platform code. Xamarin.Forms documentation is in the process of being ported and updated to .NET MAUI, and we’ll be publishing regularly from here on out. Anytime you cannot find the .NET MAUI documentation you need, check to see if there’s a Xamarin.Forms doc available since most of the concepts all apply to .NET MAUI as well.

Get Started Today

Before installing Visual Studio 2022 Preview, we highly recommend starting from a clean slate by uninstalling all .NET 6 previews and Visual Studio 2022 previews.

Now, install Visual Studio 2022 Preview (17.1 Preview 2) and confirm .NET MAUI (preview) is checked under the “Mobile Development with .NET workload”. If you already have 17.1 installed, then you can just perform an update from the Visual Studio installer.

Ready? Open Visual Studio 2022 and create a new project. Search for and select .NET MAUI.

Preview 11 release notes are on GitHub and we have captured the top changes in a migration guide in the wiki. For additional information about getting started with .NET MAUI, refer to our documentation.

Feedback Welcome

Please let us know about your experiences using .NET MAUI to create new applications by engaging with us on GitHub at dotnet/maui.

For a look at what is coming in future releases, visit our product roadmap, and for a status of feature completeness visit our status wiki.

The post Announcing .NET MAUI Preview 11 appeared first on .NET Blog.

349: With Olivia

Olivia Ng has done loads of wonderful work here on CodePen and off (check out her super cool travel bucket list site) She got started just out of pure desire to build things. “I just really like the internet” she told me. Hear hear! Her eye for design takes all her work to the next level. She had a particular focus on grid for a while there, and used those interesting designs to teach it. Also find her on Twitter and on her personal website.

Time Jumps

00:25 Guest introduction

02:00 How did you get into coding?

05:45 Design as a way into code

07:01 Sponsor: Jetpack

08:59 Blogging interesting designs

12:07 Deciding on what features to use

14:58 Designing toggles

16:19 Makeup color grid

20:03 Working in one sitting vs over a longer period of time

22:25 What was your employment story?

26:56 Working in 3D on CSS

29:05 Is work fun enough or do side projects help to be creative?

31:02 Rotalics

Sponsor: Jetpack

There are lots of reasons to look at Jetpack for your self-hosted WordPress site. One of which is the powerful search upgrade you get just by flipping a switch. Say you run a lot of WordPress sites, perhaps for clients as an agency would, now Jetpack offers a Licesning Dashboard for managing all the Jetpack subscriptions so that becomes a lot easier.

The post 349: With Olivia appeared first on CodePen Blog.

Top 8 React Bootstrap Templates for Enthusiasts and Pros

Introduction
What You Need to Know About Bootstrap
Pros
Cons
React Bootstrap Templates to Pay Attention To
How to Create your React Dashboard Template
Conclusion

Introduction

Beauty is the purgation of superfluities. This statement by Michelangelo isn’t only about aesthetics. Masters of various professions have made similar statements. And the ones who didn’t often showed a similar attitude to their craft and life. Empty spaces in a painting give weight to the parts that aren’t empty. Mechanisms with fewer moving parts break less. Fewer components in software mean fewer things can go wrong.

In this article, we’ll talk about the best React Bootstrap templates. Both React and Bootstrap are frameworks that let you use existing functionality in your web applications. Using them is the software analogy of fewer moving parts in a mechanism. By using Bootstrap templates, you trade some versatility for speed and reliable operation. If you need components not supported by Bootstrap, you’ll want to use other solutions. But when used right, Bootstrap saves time and helps avoid potential compatibility issues. To know what templates to choose and how to use them, keep reading!

What You Need to Know About Bootstrap

We’ve written so much about React it’s hard to find an article in our blog that doesn’t have a paragraph on it. Today, we’ll pay more attention to Bootstrap. So, what is Bootstrap? In short, Bootstrap is a FOSS (Free and Open-Source Software) CSS framework. It serves to develop a responsive cross-platform front-end with an emphasis on mobile platforms. It also serves as a design templates library for interface components like typography, forms, navigation, and more. Bootstrap helps front-end developers create gorgeous integration-ready interfaces that are also design-conscious. But it has other uses besides building web apps from scratch. Like integrating new design elements into your ReactJS project. Bootstrap’s ready-made kit packages help you integrate these elements into your project.

Bootstrap Pros

Integrating Bootstrap into your project has many advantages:

1. Time Efficiency

Have you ever tried coding the traditional way, using Notepad or a similar text editor? If you have, try and see the size of the files you wrote by hand. Now compare that with the weight of a complete piece of software. Now imagine how much time writing every line of code by hand will take. Bootstrap libraries have functions and components you don’t have to create from scratch. Bootstrap doesn’t need programming skills beyond the basics of HTML-CSS-JavaScript tandem. If you know basic website design, adding Bootstrap will be easy. Additionally, Bootstrap documents every component it contains.

2. Consistency

Twitter programmers Mark Otto and Jacob Thornton developed Bootstrap in 2011. Their goal was a framework that eliminated any consistency issues. If you create a project with Bootstrap, it looks the way you intend on any platform and browser. This fact helped Bootstrap become one of the top front-end frameworks on the market today.

3. Conducive to Teamwork

Bootstrap is what you would call beginner-friendly. It is easy to learn and needs minimal training. The detailed documentation that we have mentioned helps avoid any ambiguity. If a new person joins your project’s team, they’ll have no issue learning this framework and seamlessly joining the work process.

4. The Grid System

When creating a page layout, a good grid is necessary. Bootstrap is divided into 12 fluent and responsive website content columns. It allows developers to create desktop-specific elements by hiding them in the mobile version and vice-versa. And the predefined classes each component possesses also make the grid much easier and faster to understand.

5. Responsiveness

As nowadays all the initial searches are run through mobile devices, the website’s responsiveness is as important as it ever was. And guess which framework is all about creating mobile-friendly websites? That’s right – Bootstrap is. Add that to the Grid System and you’ll get a website that passes the required level of responsiveness, with little effort.

Bootstrap Cons

Of course, Bootstrap has its downsides. Let’s make a rundown of all the things about Bootstrap you’ll want to avoid.

1. It creates similar websites

Websites and interfaces built with Bootstrap usually look fine, with little that can go wrong or look out of place. But Bootstrap’s creators aimed for consistency above versatility and it shows. Creating standardized interfaces is a different task from creating recognizable website designs. Bootstrap’s consistency comes at a cost of end results looking alike. The more you use Bootstrap the more Bootstrap-y everything will look. It is possible to override and change style sheets manually but it kills a big part of why we use Bootstrap.

2. It can be heavy

We’re used to devices getting thinner and lighter. Perhaps that’s why it’s hard to wrap our heads around how heavy software has grown. Bootstrap-based projects are no exception. Using Bootstrap often causes your web app to grow too heavy for casual mobile browsing. This issue can be manually resolved, but, again, this messes with the purpose of Bootstrap.

3. Learning Curve

Bootstrap’s learning curve is less steep than, for example, Angular’s. Still, it is there, especially in the Grid and the component attribution department. A beginner usually spends quite some time studying those before using Bootstrap casually. Luckily, it’s a one-time investment of your time. Bootstrap’s documentation covers the newer version adaptation once you’re familiar with it.

The Best Bootstrap Has to Offer

Bootstrap’s best sides are, of course, the quickness and seamlessness of web development. Especially for mobile devices. On the other hand, Bootstrap inflates the websites’ weight and makes any attempts at originality harder. Should you use Bootstrap? As is often the case, the short answer is ‘it varies’. Bootstrap has its pluses and minuses. And it’s your usage of it that determines which outweighs the other. To give you a better idea of where to start, we’ve picked eight of our favorite React Bootstrap templates. They vary in design and functions but we believe each one can be of interest. Let us dive in!

Top React Bootstrap Templates

Coming up are our list of the best React Bootstrap Templates. No particular order.

Material Dashboard 2 React

Link
Live Preview
Pro Version Price – 69$

Coming in at number one on our list is Material Dashboard 2 React by Creative Tim. As you can deduct from the name, Material Dashboard 2 React is not just a template but a fully functional Admin Dashboard with lots of cool features. Let’s give them a quick rundown:

Google’s Material Design inspired design;
Over 70 individual elements for your front-end: like buttons, inputs, navbars, nav tabs, cards, alerts, and many more. Each of the elements mentioned above is customizable in color;
Example Pages to get inspired by, show to the potential clients, or get a jump-start on your development;
Full documentation built by the developers.

So, all in all, we can describe Material Dashboard 2 React as a reliable and beautifully made Bootstrap template. If you want to lighten the process of web project creation, give it a go!

Argon Dashboard React

Link
Live Preview
Pro Version Price – 89$

At number two, we have the Argon Dashboard React by Creative Tim. This open-source Bootstrap Dashboard contains over a hundred different components. Choose and combine them as you wish! Argon Dashboard React’s every component has plenty of color variations that you can adjust with SASS files. Many hover and focus variations are yours to experiment with.

At the same time, there are example pages and thorough documentation. It provides enough guidance for you to learn the ropes. So, despite the hundred-something components, the Argon is easy to navigate. Give it a try, and see this balance of simplicity and versatility for yourself!

Shards Dashboards Lite React

Link
Live Demo
Price – Free

The third entry on our list is Shards Dashboard Lite React by design revision. Consider it a little treat we would like to add for all the lovers of free templates. The first good thing about Shards Dashboard Lite is that it’s free of charge, but that’s the first of many things. Shards Lite is responsive and lightning-fast. It’s built from scratch but follows all the best modern development practices. That stands true for every template within the Shards Dashboard Lite React. It has over a dozen custom components and more than a thousand and a half icons from FontAwesome and Material icon packs. If you want to start with a free React Dashboard Template and see where to go next, try Shards Dashboard Lite React. It will probably be a while before you have to upgrade.

Light Blue React Template

Link
Live Preview
Price – 99$

We take pride in the product that comes next. The Light Blue React Template is Flatlogic’s product, and it’s quite a heavy hitter. Admin dashboards are our specialty, and we spared no effort this time. The Light Blue React can cover you as an admin dashboard, a booking management system, or an app for promo deals. We paid a lot of attention to design, too. Light Blue’s visuals are unobtrusive and, well, light. If you plan to work with an interface for hours on end, you want a subtle design that you barely notice is there. Add customizable stylings, and you’ll have an idea of why you should try the Light Blue.

CoreUI Bootstrap Admin Template

Link
Live Preview
Pro Version Price – 69 to 249$

The next React Bootstrap Template for you to check out is CoreUI Bootstrap Admin Template. Built on Bootstrap 5 and React.js, CoreUI is a simple template to handle. CoreUI boasts mobile and cross-browser compatibility. But we can say the same about other templates on this list. Likewise, for the long-term support. What sets it apart is the dedicated support from developers. If you face issues with CoreUI, you can get qualified guidance from the people who wrote the damned thing.
CoreUI is a responsive, cross-browser template with lots of features and no requirements for your design skills. Give it a try!

BizLand

Link
Live Preview
Price – Free to 34$

Now we get to sixth place on our list, which means we are about to talk about BizLand. BizLand is a Bootstrap template that is most fitting for business and corporate projects. BizLand helps manage consulting, finance, tax information, insurance, and more. It has a slick “it’s all about business” design and vibe. BizLand comes with all the features and components a good React Bootstrap template needs. But the thing that made us love BizLand was the way it works. React components improve the speed of development but often make the website slower. That’s not the case with BizLand. The interface is fast and smooth, so the user experience will be fantastic. BizLand is responsive and functional, comes with well-commented code and its file structure is easy to deal with. A definite catch of a Bootstrap template.

Creative

Link
Live Preview
Price – Free to 29$

One might nitpick and say that calling a template Creative can be ironically uncreative. Nonetheless, Creative more than deserves the seventh spot on our list, as it is stylish and quite practical. Creative contains a bunch of features. SB Forms-based working contact form and UX-friendly navigation contribute to the consistent experience. And the HTML markup and custom SASS layout make things intuitive. Creative will be a great fit for your next Bootstrap-based, especially if it is a small business or a creative agency.

Coming Sssoon Page

Link
Live Preview
Price – Free

And now it is time to wrap up this list. But we cannot do it without mentioning the last, eighth, entry, which is Coming Sssoon Page. Let’s use your deductive abilities once again and with their help we can come to the conclusion that this light, easy to use Bootstrap 3 template is going to be most fitting when it comes to a project that is going to launch in some time in the future. With the help of Coming Sssoon Page you can create a beautiful and engaging page of this kind that can help you establish a following even before your project actually starts its life.

Wrapping Up

Of course, we can’t say that this list is fully complete, as there are hundreds, if not thousands, more templates that deserve your attention, but we believe that the ones that are on that list are most deserving of it due to the way they look and operate. But, if after all, none of them made an impression on you, we have a solution – creating your own! Don’t worry, it will not be either hard, nor time consuming. Follow us to the next part of this article to get tot know what we are talking about.

How to Create your React Dashboard Template

Let’s not keep the intrigue and get straight to the heart of the matter: you can create your own React-based Bootstrap-looking template with the help of Flatlogic’s Full-Stack Web Application Platform! Here’s how you do it:

Step #1. Choose a name for your project. Despite perceived simplicity, this step might as well be the hardest one, as you will have to think of a name that can befit your project. And also, the other steps are even easier.

Step #2. Choose a stack for your project. As we are creating a React-based template, we need to choose the React option for the front-end. Backend and database can be entirely of your choosing.

Step #3. Choose a design for your project. Here, we should say, it is better to choose the Transparent variant, as it is Bootstrap-based.

Step #4. Choose a schema for your project. That is right, you don’t even have to spend time creating a schema yourself, as there are ready-made variants for you to choose from.

Step #5. Review and generate your project. Just assure yourself of your choices and press the «Create Project» button.

And what you will have on your hands is a brand-new beautiful React-based Bootstrap-looking template. Give yourself a round of applause on a job well-done!

Conclusion

Bootstrap is a tool that you should definitely try, if you haven’t already, as you will find it greatly simplifies the not-so-easy process of web projects creation. And simplifying the hard processes that life has is never a bad thing.

And that’s it for today! We hope that you’ve enjoyed it as much as we did. And, as always, have a nice day and feel free to read more of our articles!

The post Top 8 React Bootstrap Templates for Enthusiasts and Pros appeared first on Flatlogic Blog.

Enriched Web API Documentation using Swagger/OpenAPI in ASP.NET Core

Introduction

Before selecting or attempting any integration with an API, most developers check out its API documentation. Keeping the API documentation up to date to reflect the software changes is challenging and requires time and effort. In the case of Web APIs, we would like to document the following:

Authorization Types (e.g., API Key, Bearer token, Authorization code, etc.)

Action Methods: The endpoints, HTTP Methods, Headers, etc.

Data Contracts: The description of the data to be exchanged between the service and a client. We can show each parameter’s name, type, restrictions, etc.

Examples that use the Web API to help consumers start quickly.

It would be nice to have a standardized way of describing Web APIs, to allow both humans and computers to generate, discover and understand its capabilities without requiring access to the source code. Good news, 🎉 this standard exists and is called OpenAPI Specification (OAS), based initially on the Swagger Specification.

A Web API documentation provides the necessary information (e.g., endpoints, data contracts, etc.) to describe our Web API to our consumers. In addition, however, we may want to provide documentation for our source code to help developers improve and maintain it. Therefore, a Code documentation will provide information about our projects, classes, constructors, methods, etc. To automatically generate code documentation from comments, start by reading Wagner and Warren’s (2021) article.

In this article, we will learn about Web API documentation, how we can automatically generate it in ASP .NET Core and how to provide enriched information by offering examples, documentation per different versions, and many more 😉.

OpenAPI in .NET Core

In practice, in an ASP .NET Core project, we use specific Attributes and XML comments to define all the needed information (e.g., HTTP response codes, information messages, etc.) directly to our source code. We can automatically generate a JSON or YAML document (or set of documents) that describes our API by using this information. This generated document(s) is known as OpenAPI definition, which can be used by:

API Documentation generation tools (e.g., Swagger UI, Redoc, etc.) to render our OpenAPI definition (e.g., as a web page).
Code generation tools (NSwag, Swagger Codegen, etc.) to automatically generate the consumer’s source code in various programming languages.

Testing tools to execute API requests and validate responses on the fly.

Mock Server tools to provide a mock-fake server to return static or dynamically generated example responses.

So, by using OpenAPI in our Web API projects, we can automatically generate our documentation directly from or source code by maintaining the data annotations, XML comments and examples based on our actual data transfer classes. The two main OpenAPI implementations for .NET are Swashbuckle and NSwag. In the examples of the following sections, we will use the Swashbuckle tools.

Create a New Web API in .NET 6.0 with OpenAPI Enabled

Since the ASP.NET Core 5.0, the Web API templates enable the OpenAPI support by default. The template contains a NuGet dependency on Swashbuckle, register services, and add the necessary middlewares to generate a basic OpenAPI definition file and serve it in a Web UI (via the Swagger UI tool). In the following instructions, we will see how to create a new Web API project with enabled OpenAPI support.

That’s a great start! With only a few clicks, our new API projects support OpenAPI. However, there are things that we can configure and improve to provide more information to our API consumers. For example, we could perform the actions shown in the following figure and list. However, we will see more ways to enrich our API documentation in the following sections.

Set the appropriate response media type (e.g., application/json).
Provide examples with real-life data (not auto-generated with dummy data).
Include additional HTTP status codes. For example, to inform about the possible error HTTP status codes (4xx and 5xx).

Figure 1. – Possible actions to improve the default OpenAPI documentation.

Provide OpenAPI Documentation in Existing Project

Let’s assume that our current project serves API with multiple versions, and we would like to provide OpenAPI Documentation for all versions. For that purpose, we will use the project that we created in .NET Nakama (2021, December).

To provide OpenAPI Documentation, we would start by installing the Swashbuckle.AspNetCore NuGet package. To support API documentation for multiple versions, we need to install the Microsoft.AspNetCore.Mvc.Versioning.ApiExplorer NuGet package.

Figure 2. – Installing the Microsoft.AspNetCore.Mvc.Versioning.ApiExplorer NuGet package.

Our next step is to register some services and add some middlewares. I have created some extension methods that group all the necessary actions for that purpose. You can find the source code of the extensions and examples in GitHub.

So, we can download, modify and use the following extensions in our Program.cs (or in the System.cs in previous .NET versions). In addition, we can see an example of the Program.cs file here.

The AddApiVersioningConfigured extension (can be found in ConfigureApiVersioning.cs) has been updated (in comparison with the one provided in article .NET Nakama (2021, December) to support versioning on our documentation.

// Configure the API versioning properties of the project.

builder.Services.AddApiVersioningConfigured();

Then, we should use the AddSwaggerSwashbuckleConfigured extension (found in ConfigureSwaggerSwashbuckle.cs file) in our Program.cs file to configure the Swagger generator based on our needs. In the following sections, we will see in detail several enrichment scenarios.

// Add a Swagger generator and Automatic Request and Response annotations:

builder.Services.AddSwaggerSwashbuckleConfigured();

In the ConfigureSwaggerSwashbuckleOptions.cs file, we can configure the basic information (e.g., title, description, license, etc.) about our API (see Figure 3).

var info = new OpenApiInfo()
{
Title = “Web API Documentation Tutorial”,
Version = description.ApiVersion.ToString(),
Description = “A tutorial project to provide documentation for our existing APIs.”,
Contact = new OpenApiContact() { Name = “Ioannis Kyriakidis”, Email = [email protected] },
License = new OpenApiLicense() { Name = “MIT License”, Url = new Uri(“https://opensource.org/licenses/MIT”) }
};

Add the UseSwagger() middleware in our Program.cs file to serve the generated OpenAPI definition(s) as JSON files and the UseSwaggerUI() middleware to server the Swagger-UI for all discovered API versions. In the following example, we serve the API documentation only in the development environment. However, we can decide which environments to provide the documentation based on our API audience. Remember that we could only generate the JSON files and serve them (e.g., with Swagger UI) in a separate project.

if (app.Environment.IsDevelopment())
{
// Enable middleware to serve the generated OpenAPI definition as JSON files.

app.UseSwagger();

// Enable middleware to serve Swagger-UI (HTML, JS, CSS, etc.) by specifying the Swagger JSON endpoint(s).

var descriptionProvider = app.Services.GetRequiredService<IApiVersionDescriptionProvider>();
app.UseSwaggerUI(options =>
{
// Build a swagger endpoint for each discovered API version

foreach (var description in descriptionProvider.ApiVersionDescriptions)
{
options.SwaggerEndpoint($”{description.GroupName}/swagger.json”, description.GroupName.ToUpperInvariant());
}
});
}

Finally, if we want to see the SwaggerUI when start debugging, we will have to set the “launchUrl”: “swagger” in the launchSettings.json file.

“TutorialWebApiDocumentation”: {
“commandName”: “Project”,
“dotnetRunMessages”: true,
“launchBrowser”: true,
“launchUrl”: “swagger”,
“applicationUrl”: “https://localhost:44351;http://localhost:34885”,
“environmentVariables”: {
“ASPNETCORE_ENVIRONMENT”: “Development”
}
},

The following figure shows a Swagger UI example for an API with two versions containing essential information.

Figure 3. – A Swagger UI example with essential information.

Enrich Documentation via XML Comments and Attributes

The structure of the extracted XML documentation is defined in C# by using XML documentation comments. The documentation comments support several XML tags, such as summary, return description, exceptions, list of information, etc. In this article, we will use some of them. For more information about the recommended XML tags for C#, read Wagner B., et al. (2021) article.

Generate and Read Documentation Comments (XML)

To enable the documentation file generation, we should set the GenerateDocumentationFile option to True. Then, the compiler will find all comment fields with XML tags in our source code and create an XML document.

However, when this option is enabled, the compiler will generate CS1591 warnings for any public members in our project without XML documentation comments. We can exclude these warnings by including them in the NoWarn option.

So, to enable the GenerateDocumentationFile option and stop the CS1591 warnings we should:

Right-click the project in Solution Explorer and select Edit Project File.
Add the following PropertyGroup section (or include the options in an existing PropertyGroup).

<PropertyGroup>
<GenerateDocumentationFile>True</GenerateDocumentationFile>
<NoWarn>$(NoWarn);1591</NoWarn>
</PropertyGroup>

Next, we need to include the XML documentation comments in the OpenAPI definition file. For that purpose, we should use the IncludeXmlComments method in the ConfigureSwaggerSwashbuckle.cs file as shown in the following code.

// Set the comments path for the XmlComments file.

string xmlFile = $”{Assembly.GetExecutingAssembly().GetName().Name}.xml”;
string xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
options.IncludeXmlComments(xmlPath);

Finally, we should include the XML comments in our controller actions using triple slashes. For example, we can add a summary section to describe the performed action. Figure 4 presents a part of the Swagger UI that shows the API endpoint summary.

/// <summary>

/// Get a list with all “<see cref=”SampleResponse”/>” items.

/// </summary>

[HttpGet]
public IEnumerable<SampleResponse> Get()
{
// …action code

}

Figure 4. – Example of the Swagger UI with XML comments (summary tag).

API Responses (HTTP Codes and Types)

Any consumer would need beneficial information, such as the possible HTTP status codes and their response body. In Figure 5, we can see an example where the API endpoint could return its five possible HTTP status codes (200, 400, 409, 500, and 503). To enrich the response metadata for a given action method, we should:

Install the Swashbuckle.AspNetCore.Annotations NuGet package.
Update the controller actions to specify the possible response codes and their response types (if any) by using the response tag and the SwaggerResponse attribute.

In the following code example, we set the response description of the success HTTP status code in the response tag. In addition, we are setting all possible HTTP status codes and response types (e.g., IEnumerable<SampleResponse>) for the successful response.

/// <summary>

/// Get a list with all “<see cref=”SampleResponse”/>” items.

/// </summary>

/// <response code=”200″>Returns a list with the available sample responses.</response>

[HttpGet]
[SwaggerResponse(StatusCodes.Status200OK, Type = typeof(IEnumerable<SampleResponse>))]
[SwaggerResponse(StatusCodes.Status400BadRequest)]
[SwaggerResponse(StatusCodes.Status409Conflict)]
[SwaggerResponse(StatusCodes.Status500InternalServerError)]
[SwaggerResponse(StatusCodes.Status503ServiceUnavailable)]
public IEnumerable<SampleResponse> Get()
{
// …

}

Figure 5. – Swagger UI example with multiple response HTTP status codes.

Define Media Types (Consumed and Produced)

To define the appropriate consume and produce media types, we can decorate our controller with the [Consumes] and [Produces] attributes. For example, if we use the application/json, we can use the aforementioned attributes to decorate our controller, as shown in the following code example. Figure 6 shows the effect of the [Produces] attribute in Swagger UI.

[ApiController]
// …other attributes

[Consumes(“application/json”)]
[Produces(“application/json”)]
public class HelloWorldController : ControllerBase
{
// …controller’s code

}

Figure 6. – The effect of using the [Produces] attribute in Swagger UI.

Enrich Documentation via Filters

The Swashbuckle.AspNetCore.Filters NuGet package provides several functionalities that significantly improve our API documentation. For example, we can create valuable request and response examples with valid data, including security requirements, custom request and response headers, etc. In addition, we can manually test our API using these features just by using the Swagger UI without modifying the auto-generated request.

API Examples (Request and Response)

To provide request and response examples with valuable and valid data, we should:

Install the Swashbuckle.AspNetCore.Filters NuGet package.
Enable the automatic annotation of the [SwaggerRequestExample] and [SwaggerResponseExample] in the ConfigureSwaggerSwashbuckle.cs file. For that purpose, we should:

Use the options.ExampleFilters(); in the AddSwaggerGen(options).
Read the examples for the current assembly by registering the AddSwaggerExamplesFromAssemblies.

services.AddSwaggerGen(options => {
options.ExampleFilters();
// … other stuff

});
services.AddSwaggerExamplesFromAssemblies(Assembly.GetEntryAssembly());

Then we can implement the IExamplesProvider interface for our data transfer classes (request and response). In the following source code example, we return an example for the SampleRequest class, shown in Figure 7.

using Swashbuckle.AspNetCore.Filters;
using TutorialWebApiDocumentation.V1.DTOs;

namespace TutorialWebApiDocumentation.V1.Examples
{
public class SampleRequestExample : IExamplesProvider<SampleRequest>
{
public SampleRequest GetExamples()
{
return new SampleRequest()
{
Id = 2,
Name = “Hello DotNetNakama”,
};
}
}
}

Figure 7. – Swagger UI example for a request DTO.

Figure 8. – Swagger UI example for a response DTO.

Input-Validation in API Documentation (Data Annotations and Fluent)

If we use System.ComponentModel.DataAnnotations attributes to validate our DTOs, then the validations are recognized and automatically included in the API documentation. However, we should perform the following steps if we are using FluentValidation for our DTOs.

Install the MicroElements.Swashbuckle.FluentValidation NuGet package.
Register the following service in the ConfigureSwaggerSwashbuckle.cs to add the fluent validation rules to the swagger generator.

services.AddFluentValidationRulesToSwagger();

Figure 9. – Swagger UI example when using DataAnnotations VS FluentValidation.

Security Information Scheme

To provide security information about the authorization scheme we are using (e.g., JWT Bearer), we can define it by using the following source code in the ConfigureSwaggerSwashbuckle.cs file. In this way, the Authorize button will be shown (Figure 10), and we can use it to specify the appropriate values (e.g., the bearer token in Figure 11).

options.OperationFilter<SecurityRequirementsOperationFilter>(true, “Bearer”);
options.AddSecurityDefinition(“Bearer”, new OpenApiSecurityScheme
{
Description = “Standard Authorization header using the Bearer scheme (JWT). Example: “bearer {token}””,
Name = “Authorization”,
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey,
Scheme = “Bearer”
});

Figure 10. – Swagger UI example with an Authorize button.

Figure 11. – Swagger UI example to set the JWT bearer token.

Mark Endpoints that Require Authorization

Our API endpoints may require authorization (using the [Authorize] attribute) or allow anonymous requests. As we can understand, it would be helpful to distinguish these cases in our Swagger UI. For that purpose, we can show the (Auth) text next to the endpoint’s summary to quickly see which of them require authorization (Figure 12). We can perform that by using the following OperationFilter in the ConfigureSwaggerSwashbuckle.cs file as shown below:

options.OperationFilter<AppendAuthorizeToSummaryOperationFilter>();

Figure 12. – Swagger UI example with authorization indicator.

Summary

An Web API documentation provides the necessary information (e.g., endpoints, data contracts, etc.) to describe our Web API to our consumers. However, keeping an up to date Web API documentation is challenging and requires time and effort. Therefore, an easy and automatic process as much as possible would be a great help.

The OpenAPI Specification provides a standardized way of describing Web APIs to allow both humans and computers to generate, discover and understand the API capabilities. In an ASP .NET Core project, we use specific Attributes and XML comments to define all the needed information (e.g., HTTP response codes, information messages, etc.) directly to our source code. Thus, we can provide up-to-date documentation easily as we keep our code up to date.

The essential OpenAPI tools that we would need are a) a tool to generate the OpenAPI definition and b) a tool to generate the API documentation (as a web page, PDF, etc.). This article showed how to use the Swashbuckle tools to create API documentation in an ASP.NET Core project (new or existing) with enriched information.

When creating a Web API Documentation, our goal should be to provide all the information that a consumer would need to communicate with our Web API (without having access to our code). This way, we would reduce the time to a first hello world (TTFHW) call (i.e., the time to integrate with our Web API). So let’s think about our consumers and create beautiful and valuable Web API documentation for them.

References

.NET Nakama (2021, December 4). All about Web API Versioning in ASP.NET Core. https://www.dotnetnakama.com/blog/all-about-web-api-versioning-in-asp-dotnet-core/

Roth D. (2021, August 10). ASP.NET Core updates in .NET 6 Preview 7. https://devblogs.microsoft.com/dotnet/asp-net-core-updates-in-net-6-preview-7/#minimal-host-and-template-improvements

Wagner B. and Warren G. (2021, November 29). XML documentation comments. https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/xmldoc/

Wagner B., et al. (2021, November 30). Recommended XML tags for C# documentation comments. https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/xmldoc/recommended-tags

A Comprehensive Guide to Port from EF6 to EF Core

EF6 was officially released nearly a decade ago in October 2013. The next major Entity Framework release was in June of 2016 when EF Core 1.0 was introduced as a complete rewrite for the modern .NET Core platform. One final, major update to EF6 happened with the release of a new version compatible with .NET Core. The latest version, capable of running on both the .NET Framework and .NET Core, was intended to make it easier for customers to transition to the .NET Core platform. With the option of EF6 on .NET Core, customers can move their existing EF6 codebase onto .NET Core first before migrating their EF6 code to EF Core. Although the initial versions of EF Core lacked support for many popular EF6 capabilities, the gap has narrowed significantly with every release.

EF6 to EF Core Porting

There are now more reasons than ever before to make the EF Core upgrade. With EF Core, you can:

Take advantage of dozens of features exclusive to EF Core, like support for constructors with parameters, mapped types with no keys, alternate keys, simple logging configuration, minimal API support, split queries and “shadow” properties. For the full list of features compared to EF6, see Compare EF6 and EF Core.
Centralize business logic and support scenarios like multi-tenancy and “soft delete” with global query filters.
Give your apps a performance boost by taking advantage of the ongoing performance improvements to EF Core, including the 92% improvement in requests per second for EF Core 6 on .NET 6 compared to EF Core 5 on .NET 5 based on the industry standard TechEmpower Fortunes benchmark.
Connect to a variety of different database backends from Sqlite and MySQL to SQL Server and Azure Cosmos DB.

The Entity Framework team understands that porting your apps from EF6 to EF Core is not always straightforward. To make it easier to successfully plan and execute the upgrade to EF Core, we completely rewrote our guidance for Porting from EF6 to EF Core.

The new guide recognizes that there are many approaches to using and integrating EF6 that must be addressed for a port to be successful. For example, there are different steps provided for customers who prefer to reverse engineer their database compared to customers who follow a code-first approach. The guide breaks down differences in support for connection strings, explains how model building and change tracking work in EF Core, and lays out the general steps you’ll follow to port your code.

Did you know it is possible to run EF6 and EF Core side-by-side, and that you can port sections of your app over time rather than planning for an “all-or-nothing” transition?
Are you aware that you can visualize your models despite the lack of EDMX designer support and even manage migrations from within Visual Studio using free open source community tools?
Do you understand the differences in how inheritance is configured and used between versions?

The answers to these questions and many more are all available in the comprehensive guide to Porting from EF6 to EF Core.

We are here to help. If you encounter an issue during your upgrade, find issues in the guide or have questions and/or suggestions, simply file an issue in our documentation repo and the Entity Framework team will respond!

The post A Comprehensive Guide to Port from EF6 to EF Core appeared first on .NET Blog.

Secure a Blazor WASM ASP.NET Core hosted APP using BFF and OpenIddict

This article shows how to implement authentication and secure a Blazor WASM application hosted in ASP.NET Core using the backend for frontend (BFF) security architecture to authenticate. All security is implemented in the backend and the Blazor WASM is a view of the ASP.NET Core application, no security is implemented in the public client. The application is a trusted client and a secret is used to authenticate the application as well as the identity. The Blazor WASM UI can only use the hosted APIs on the same domain.

Code https://github.com/damienbod/AspNetCoreOpeniddict

Setup

The Blazor WASM and the ASP.NET Core host application is implemented as a single application and deployed as one. The server part implements the authentication using OpenID Connect. OpenIddict is used to implement the OpenID Connect server application. The code flow with PKCE and a user secret is used for authentication.

Open ID Connect Server setup

The OpenID Connect server is implemented using OpenIddict. The is standard implementation as like the documentation. The worker class implements the IHostService interface and is used to add the code flow client used by the Blazor ASP.NET Core application. PKCE is added as well as a client secret.

static async Task RegisterApplicationsAsync(IServiceProvider provider)
{
var manager = provider.GetRequiredService<IOpenIddictApplicationManager>();

// Blazor Hosted
if (await manager.FindByClientIdAsync(“blazorcodeflowpkceclient”) is null)
{
await manager.CreateAsync(new OpenIddictApplicationDescriptor
{
ClientId = “blazorcodeflowpkceclient”,
ConsentType = ConsentTypes.Explicit,
DisplayName = “Blazor code PKCE”,
DisplayNames =
{
[CultureInfo.GetCultureInfo(“fr-FR”)] = “Application cliente MVC”
},
PostLogoutRedirectUris =
{
new Uri(“https://localhost:44348/signout-callback-oidc”),
new Uri(“https://localhost:5001/signout-callback-oidc”)
},
RedirectUris =
{
new Uri(“https://localhost:44348/signin-oidc”),
new Uri(“https://localhost:5001/signin-oidc”)
},
ClientSecret = “codeflow_pkce_client_secret”,
Permissions =
{
Permissions.Endpoints.Authorization,
Permissions.Endpoints.Logout,
Permissions.Endpoints.Token,
Permissions.Endpoints.Revocation,
Permissions.GrantTypes.AuthorizationCode,
Permissions.GrantTypes.RefreshToken,
Permissions.ResponseTypes.Code,
Permissions.Scopes.Email,
Permissions.Scopes.Profile,
Permissions.Scopes.Roles,
Permissions.Prefixes.Scope + “dataEventRecords”
},
Requirements =
{
Requirements.Features.ProofKeyForCodeExchange
}
});
}
}

Blazor client Application

The client application was created using the Blazor.BFF.OpenIDConnect.Template Nuget template package. The configuration is read from the app settings using the OpenIDConnectSettings section. You could add more configurations if required. This is otherwise a standard OpenID Connect client and will work with any OIDC compatible server. PKCE is required and also a secret to validate the application. The AddAntiforgery method is used so that API calls can be forced to validate anti-forgery token to protect against CSRF as well as the same site cookie protection.

public void ConfigureServices(IServiceCollection services)
{
services.AddAntiforgery(options =>
{
options.HeaderName = “X-XSRF-TOKEN”;
options.Cookie.Name = “__Host-X-XSRF-TOKEN”;
options.Cookie.SameSite = Microsoft.AspNetCore.Http.SameSiteMode.Strict;
options.Cookie.SecurePolicy = Microsoft.AspNetCore.Http.CookieSecurePolicy.Always;
});

services.AddHttpClient();
services.AddOptions();
;
var openIDConnectSettings = Configuration.GetSection(“OpenIDConnectSettings”);

services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie()
.AddOpenIdConnect(options =>
{
options.SignInScheme = “Cookies”;
options.Authority = openIDConnectSettings[“Authority”];
options.ClientId = openIDConnectSettings[“ClientId”];
options.ClientSecret = openIDConnectSettings[“ClientSecret”];
options.RequireHttpsMetadata = true;
options.ResponseType = “code”;
options.UsePkce = true;
options.Scope.Add(“profile”);
options.Scope.Add(“offline_access”);
options.SaveTokens = true;
options.GetClaimsFromUserInfoEndpoint = true;
//options.ClaimActions.MapUniqueJsonKey(“preferred_username”, “preferred_username”);
});

services.AddControllersWithViews(options =>
options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute()));

services.AddRazorPages().AddMvcOptions(options =>
{
//var policy = new AuthorizationPolicyBuilder()
// .RequireAuthenticatedUser()
// .Build();
//options.Filters.Add(new AuthorizeFilter(policy));
});
}

The OIDC configuration settings are read from the OpenIDConnectSettings section. This can be extended if further specific settings are required.

“OpenIDConnectSettings”: {
“Authority”: “https://localhost:44395”,
“ClientId”: “blazorcodeflowpkceclient”,
“ClientSecret”: “codeflow_pkce_client_secret”
},

The NetEscapades.AspNetCore.SecurityHeaders Nuget package is used to add security headers to the application to protect the session. The configuration is setup for Blazor.

public static HeaderPolicyCollection GetHeaderPolicyCollection(bool isDev, string idpHost)
{
var policy = new HeaderPolicyCollection()
.AddFrameOptionsDeny()
.AddXssProtectionBlock()
.AddContentTypeOptionsNoSniff()
.AddReferrerPolicyStrictOriginWhenCrossOrigin()
.AddCrossOriginOpenerPolicy(builder =>
{
builder.SameOrigin();
})
.AddCrossOriginResourcePolicy(builder =>
{
builder.SameOrigin();
})
.AddCrossOriginEmbedderPolicy(builder => // remove for dev if using hot reload
{
builder.RequireCorp();
})
.AddContentSecurityPolicy(builder =>
{
builder.AddObjectSrc().None();
builder.AddBlockAllMixedContent();
builder.AddImgSrc().Self().From(“data:”);
builder.AddFormAction().Self().From(idpHost);
builder.AddFontSrc().Self();
builder.AddStyleSrc().Self();
builder.AddBaseUri().Self();
builder.AddFrameAncestors().None();

// due to Blazor
builder.AddScriptSrc()
.Self()
.WithHash256(“v8v3RKRPmN4odZ1CWM5gw80QKPCCWMcpNeOmimNL2AA=”)
.UnsafeEval();

// due to Blazor hot reload requires you to disable script and style CSP protection
// if using hot reload, DO NOT deploy an with an insecure CSP
})
.RemoveServerHeader()
.AddPermissionsPolicy(builder =>
{
builder.AddAccelerometer().None();
builder.AddAutoplay().None();
builder.AddCamera().None();
builder.AddEncryptedMedia().None();
builder.AddFullscreen().All();
builder.AddGeolocation().None();
builder.AddGyroscope().None();
builder.AddMagnetometer().None();
builder.AddMicrophone().None();
builder.AddMidi().None();
builder.AddPayment().None();
builder.AddPictureInPicture().None();
builder.AddSyncXHR().None();
builder.AddUsb().None();
});

if (!isDev)
{
// maxage = one year in seconds
policy.AddStrictTransportSecurityMaxAgeIncludeSubDomains(maxAgeInSeconds: 60 * 60 * 24 * 365);
}

return policy;
}

The APIs used by the Blazor UI are protected by the ValidateAntiForgeryToken and the Authorize attribute. You could add authorization as well if required. Cookies are used for this API with same site protection.

[ValidateAntiForgeryToken]
[Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)]
[ApiController]
[Route(“api/[controller]”)]
public class DirectApiController : ControllerBase
{
[HttpGet]
public IEnumerable<string> Get()
{
return new List<string> { “some data”, “more data”, “loads of data” };
}
}

When the application is started, the user can sign-in and authenticate using OpenIddict.

The setup keeps all the security implementation in the trusted backend. This setup can work against any OpenID Connect conform server. By having a trusted application, it is now possible to implement access to downstream APIs in a number of ways and possible to add further protections as required. The downstream API does not need to be public either. You should only use a downstream API if required. If a software architecture forces you to use APIs from separate domains, then a YARP reverse proxy can be used to access to API, or a service to service API call, ie trusted client with a trusted server, or an on behalf flow (OBO) flow can be used.

Links

https://documentation.openiddict.com/

https://github.com/damienbod/Blazor.BFF.OpenIDConnect.Template

https://github.com/andrewlock/NetEscapades.AspNetCore.SecurityHeaders