#identityserver4
Explore tagged Tumblr posts
Text
Configure IdentityServer for Xamarin Forms
In this new post, I explain how to configure IdentityServer for Xamarin Forms to integrate Web Authenticator using Xamarin Essentials.
First, I wrote a post about how to implement the authentication in Xamarin Forms with IdentityServer. So, my focus was only on the Xamarin side. Here I want to explain what the IdentityServer configuration is in order to succeed in the login.
Create a new client
Have you ever wondered how hard it would be to set up a minimal viable authentication server that uses industry standards and usable from your mobile Xamarin application? Well, I have, and I believe in having found a solution that can be a great starting point and will allow you to expand the answer should you ever need to do so.
One common industry standard is OpenID / OAuth2, which provides a standardized authentication mechanism that allows user identification securely and reliably. You can think of the identity service as a web server that identifies a user and provides the client (website/mobile app, etc.) to authenticate itself with another application server that said client uses.
The recommended flow for a mobile app
While the OAuth standard is open to anyone with a computer and an internet connection, I generally do not recommend writing your own implementation. My go-to solution for setting up an identity provider is the IdentityServer.
IdentityServer4 is built based on the OAuth spec. It is built on the trusted ASP.NET Core but requires quite some know-how to get the configurations and other settings ready for use. Luckily, there is a quickstart template that you can install via the dotnet command line and then make your server. You can find the repository here on GitHub. After following the install instructions, we can create a server with the following command:
dotnet new sts -n XamarinIdentity.Auth
The solution is pretty much ready to go but let’s look at the configuration of the IdentityServer in Config.cs and make some adjustments in the GetClients method.
Add a client
Based on the template, let’s make some changes that leave us with the following final configuration:
public static IEnumerable<Client> GetClients(IConfigurationSection stsConfig) { return new List<Client> { // mobile client new Client { ClientName = "mobileclient-name-shown-in-logs", ClientId = "the-mobileclient-id-of-your-choice", AllowedGrantTypes = GrantTypes.Code, AllowOfflineAccess = true, // allow refresh tokens RequireClientSecret = false, RedirectUris = new List<string> { "oidcxamarin101:/authorized" }, PostLogoutRedirectUris = new List<string> { "oidcxamarin101:/unauthorized", }, AllowedScopes = new List<string> { "openid", "role", "profile", "email" } } }; }
Generally, you can set the ClientName, ClientId, RedirectUris and PostLogoutRedirectUris to values of your choosing. The scopes represent the defaults. Further note that by setting AllowOfflineAccess to true, the user can request refresh tokens which means that as long as the refresh token is valid, the user will not have to log in but can use said refresh token to request a new access token. In mobile apps, this is generally the prefered behaviour since users usually have their personal device and therefore expect the app to “store” their login.
As you can see, The RedirectUris and PostLogoutRedirectUris are using a custom URL oidcxamarin101:/ that identifies my app.
IdentityServer Admin
So, very often we have to create the front-end to manage users, integrate the authentication with external services suck as Facebook and Twitter, make API calls secure. IdentityServer offers a nice UI for administration but it is quite expensive. Now, I found a very nice work on GitHub: Skoruba.IdentityServer4.Admin.
This is cool! The application is written in ASP.NET Core MVC using .NET5.
Skoruba IdentityServer4 Admin UI
Add a new client
So, adding a new client with this UI is quite easy. In the IdentityServer Admin website, create a new Client. Then, the important configuration are:
Under Basic
Add this RedirectUris : oidcxamarin101:/authenticated
Allowed Grant Types: authorization_code
Under Authenticaton/Logout
Add Post Logout Redirect Uris: oidcxamarin101:/signout-callback-oidc
Basic configuration
Authentication/Logout configuration
I hope this is useful! Do you know Microsoft is releasing .NET MAUI that will replace Xamarin? Here how to test it with Visual Studio 2022.
If you have any questions, please use the Forum. Happy coding!
The post Configure IdentityServer for Xamarin Forms appeared first on PureSourceCode.
from WordPress https://www.puresourcecode.com/dotnet/xamarin/configure-identityserver-for-xamarin-forms/
1 note
·
View note
Video
youtube
Create token | Identity Server 4 | ASP.Net Core
0 notes
Video
youtube
Create token | Identity Server 4 | ASP.Net Core
0 notes
Text
ASP.NET Core 3 and Angular 9 - Terza Edizione
Con grande orgoglio e soddisfazione posso finalmente annunciare che il libro ASP.NET Core 3 and Angular 9 è disponibile per l'acquisto in edizione cartacea e digitale su tutte le principali piattaforme di distribuzione, tra cui: Packt Publishing Amazon.com | it | uk | in |de | fr Google Play Barnes & Noble Mondadori Rakuten Kobo Booktopia ... e molte altre! Ecco un'immagine della copertina aggiornata:
Ordinando il libro direttamente sul sito dell'editore Packt Publishing sarà possibile ottenere il 25% di sconto utilizzando il codice promozionale RYADEL25. Come si può evincere dal titolo, il libro è una guida dettagliata all'utilizzo dei framework di programmazione ASP.NET Core (versione 3.1) e Angular (versione 9) per sviluppare applicazioni moderne per il web. Come già nelle passate edizioni la metodologia seguita è quella dell'approccio full-stack, in base al quale lo sviluppatore potrà imparare a cimentarsi con tutti i principali aspetti legati allo sviluppo di un applicativo: dalla configurazione dell'ambiente di lavoro al data modeling; dall'analisi funzionale al processo di implementazione; dal design delle interfacce alla user experience; dallo sviluppo dei web service REST in back-end all'utilizzo degli stessi in ambiente front-end; dalle attività di debug e test fino al deployment in produzione. Tutti questi aspetti vengono trattati nei 12 capitoli di cui si compone il libro, sviluppati in 732 pagine e diverse migliaia di linee di codice sorgente disponibili su GitHub. Spero che il lavoro svolto per completare questo libro possa piacere ai lettori almeno quanto è stato con la precedente edizione (ASP.NET Core 2 and Angular 5), che ha avuto la fortuna di diventare un vero e proprio best-seller con oltre 15.000 copie vendute in tutto il mondo e un video course pubblicato su diverse piattaforme di formazione, tra cui Udemy. Un grazie in anticipo a tutti quelli che hanno apprezzato i nostri sforzi! Nel caso in cui vogliate acquisire maggiori informazioni sui contenuti del libro, ecco la scheda di presentazione (product information sheet) realizzata dall'editore per le piattaforme di distribuzione online: buona lettura e... alla prossima pubblicazione! Key Features Explore the latest edition of the bestselling book ASP.NET Core 2 and Angular 5 Design, build and deploy a Single Page Application or Progressive Web App with ASP.NET Core and Angular Adopt a full stack approach to handle data management, Web APIs, application design, testing, SEO, security and deployment Book Description Learning full stack development calls for knowledge of both frontend and backend web development. By covering the impressive capabilities of ASP.NET Core 3.1 and Angular 9, right from project setup through to the deployment phase, this book will help you to develop your skills effectively. The book will get you started with using the .NET Core framework and Web API Controllers to implement API calls and server-side routing in the backend. Next, you will learn to build a data model with Entity Framework Core and configure it using either a local SQL Server instance or cloud-based data stores such as Microsoft Azure. The book will also help you handle user input with Angular reactive forms and frontend and backend validators for maximum effect. You will later explore the advanced debugging and unit testing features provided by xUnit.net (.NET Core) and Jasmine, as well as Karma for Angular. Finally, you will implement various authentication and authorization techniques with the ASP.NET Core Identity system and the new IdentityServer, as well as deploy your apps on Windows and Linux servers using IIS, Kestrel, and Nginx. By the end of this book, you will be equipped with the skills you need to create efficient web applications using ASP.NET Core and Angular. What you will learn Implement a Web API interface with ASP.NET Core and consume it with Angular using RxJS Observables Create a data model using Entity Framework Core with code-first approach and migrations support Set up and configure a SQL database server using a local instance or a cloud data store on Azure Perform C# and JavaScript debugging using Visual Studio 2019 Create TDD and BDD unit test using xUnit, Jasmine, and Karma Implement authentication and authorization using ASP.NET Identity, IdentityServer4, and Angular API Build Progressive Web Apps and explore Service Workers Who this book is for This book is for experienced ASP.NET developers who already know about ASP.NET Core and Angular and are looking to learn more about them and understand how to use them together to create production-ready Single Page Applications (SPAs) or Progressive Web Applications (PWAs). However, the fully-documented code samples (also available on GitHub) and the step-by-step implementation tutorials make this book easy-to-understand - even for beginners and developers who are just getting started. Table of Contents Getting Ready Looking Around Front-end and Back-end Interactions Data Model with Entity Framework Core Fetching and Displaying Data Forms and Data Validation Code Tweaks and Data Services Back-end and Front-end Debugging ASP.NET Core and Angular Unit Testing Authentication and Authorization Progressive Web Apps Windows and Linux Deployment Read the full article
0 notes
Text
ASP.NET Zero is an Effective Solution for Creating Web and Mobile Apps
Software outsourcing is a way to deploy the organization internal work to some external agency. These agencies could be situated overseas or in the same geographical constant. Hiring an outsource partner is tricky and when a company decides of hiring the external support, its choice of finding a suitable outsourcing partner depends on several crucial considerable thoughts. Outsourcing is not merely a signed agreement between two parties but it could be termed as the growing relation between the client and the outsourced agency for better future project and expanding prospects.
ASP.NET Zero is a ready-made solution that comes with all out-of-the-box functionality for most standard web and Mobile application solution. In fact, this is a good start for the project where the main functionality is ready and you do not need to spend time developing basic functionality and you can immediately proceed to developing business logic and unique solutions.
ASP.NET Zero Features
1. It provides a layered, well-defined and documented architectural model. 2. It's give the predefined scalation / architecture for the application 3. It provides a strong infrastructure and development model for modularity, multi-tenancy, caching, background jobs, data filters, setting management, domain events, unit & integration testing . You focus on your business code and don't repeat yourself! 4. It's based on the open-source and community-driven ABP framework. 5. It makes your daily development easier by providing base classes and infrastructure, and automates your repeated tasks. 6. ASP.NET Zero uses Metronic as the UI theme. 7. Metronic is one of the world's most popular, strongest and richest UI themes, probably even the first. 8. Version and feature management UI 9. Notification system along with real time chat and emails 10. Provides User profile, account linking, social logins 11. Many built-in solutions (extension libraries) for dependency injection, logging, caching, localization, configuration and so on. These are independent from the
ASP.NET Core and usable for any type of application.
1. Repositories (that can be used as is without developing custom extensions) 2. Unit of Work (application service can be decorated with a transactional aspect) 3. Server-side validation (via data annotations or custom validators) 4. Dynamic Web API controllers (automatically-generated web API layer for your application layer) 5. Background Services (jobs) 6. Real Time Services (SignalR integration) 7. Xamarin mobile application
Provide Multiple solution for the Web/Mobile development
1. ASP.NET Core 2.x and Angular 7.x based Single-Page Application (SPA) solution for your web application (with .NET Framework 4.6.1 / .NET Core options) 2. ASP.NET Core 2.x and jQuery based solution for your web application (with .NET Framework 4.6.1 / .NET Core options) 3. ASP.NET MVC 5.x, Web API and AngularJS 1.x based Single-Page Application (SPA) solution for your web application 4. ASP.NET MVC 5.x and jQuery based solution for your web application 5. XAMARIN mobile application integrated with the backend solution. 6. ASP.NET Core/MVC based application for your public web site
Multi-tenancy
1. Tenant and Edition (package) management for SaaS applications 2. Subscription management & recurring payments 3. PayPal & Stripe integration 4. Dashboard for edition, tenant & income statistics 5. Single database, database per tenant and hybrid database support 6. Custom tenant logo and CSS support 7. Can work in multi-tenant and single-tenant modes
Authentication & Authorization
1. Based on ASP.NET Identity Framework 2. User & role management pages 3. Hierarchical organization units system to group users and entities 4. User login, register, password-reset and email validation pages 5. User, role and permission based flexible authorization 6. User and Tenant impersonation 7. User account linking 8. Two Factor Authentication (Email, SMS, Google Authenticator) 9. User Lockout 10. LDAP/Active Directory login support 11. Active Directory Federation Service (ADFS) Authentication 12. Social media logins (Facebook, Twitter, Google+ and Microsoft Account implemented) 13. OpenId Connect Authentication 14. Log and show all login attempts for users 15. Password complexity settings 16. Automatic Cross-Site Request Forgery (CSRF) protection 17. IdentityServer4 integration
Rapid Application Development
1. Templating support to generate customized code
Mobile Application
1. Cross-platform (iOS & Android) Xamarin mobile application 2. Integrated with the backend API 3. Provides infrastructure for common development tasks
Dynamic Ui Localization
1. Fully localized UI 2. Can add, remove and translate languages on UI 3. RTL and LTR support 4. English, Chinese, German, French, Italian, Russian, Portuguese (Brazil), Spanish (Mexico), Spanish (Spain), Turkish and Arabic localizations are included
Setting Management
1. Host & tenant-specific setting pages 2. Hierarchical setting management infrastructure 3. Easily configurable
Solid Architecture
1. Clean source code in a well-defined solution structure 2. Layered & modular architecture 3. Domain Driven Design implementation 4. Dependency injection everywhere 5. Validation 6. Logging 7. Exception handling 8. Caching 9. Automatic audit/security logging 10. Automatic database connection management and unit of work implementation 11. Pre-configured to deploy as Docker containers 12. Application functionalities are also available as HTTP API 13. Real-time push notification system (with SignalR integration) 14. Chat system (with SignalR integration) 15. Background job system (with Hangfire integration) 16. Multiple time zone support for application, tenants and users 17. Built-in global event bus for server-side events (with pre-defined events for entity changes) 18. Show and download logs from UI 19. Application setup screen 20. Personalization of layout, header, menu and footer per user 21. Tested on major PAAS providers (Azure, AWS)
Based on Strong Frameworks
1. .NET Framework 4.6.x / .NET Core 2.x (cross-platform support) 2. ASP.NET Core / ASP.NET MVC & Web API 3. EntityFramework Code-First and Migrations 4. Angular, Bootstrap, AutoMapper... 5. ASP.NET Boilerplate
Based on Metronic Theme
1. Bootstrap based 2. Responsive design 3. Multiple layout options 4. Metronic UI and components
We, at Manektech, always support the way our client wants to handle their project and we have talented and experienced software developers with us for all your technical needs. With years of experience in IT industry, ManekTech provides the best solution for your IT needs, our experiences software professionals associated with us and we always thrives to provide the expert solution to all your technical needs. We invite you to visit us for all your technical need with the best possible solution.
#Outsourcing software development company#software outsourcing company#offshore custom software development
0 notes
Text
Sitecore Identity - 3 - Adding mobile native clients
Sitecore Identity - 3 - Adding mobile native clients #learnsitecore #sitecoreidentity #sitecore
In the last two parts of the Sitecore Identity series, I described the basics and an understanding of the architecture and how IdentityServer4 is embedded and used in Sitecore 9.1+, the second part was a demo for adding a web client that authenticates itself against the Sitecore Identity (meaning that a custom web application uses Sitecore as the login method think like Login using Facebook or…
View On WordPress
0 notes
Link
I'll be honest active directory has always been a difficult area for me to develop in. Which is why I prefer a basic user authorization that's just attached to the database. What I'm trying to do is leverage Oauth and inside pass in credentials to the active directory. Thous prevent users with the built in prompt and instead handle the authorization just like you would if it was inside an aspnet core Identity table. However this is no table! This means they can pass me any username and password. Not just what they are logged as under the domain (and under their browser). Very simple just difficult to explain with all the major buzz words floating around like Single Sign On, external service providers and etc. Which where I start to have trouble explain because I like to keep things simple. What my application will do is have an authorization page and redirect users to it if that are not logged in. Once I figure out they are who they say they are with the AD then continue as normal. Search under "Ldpa/Active Directory" This is probably the best place to start looking because as I was looking for examples, the mostly I could find was examples that had to do with windows as a external provider. Since I didn't want to just pass through the credentials but prompt the user under my own UI this wasn't help. Do I need IdentityServer4? Right now I think I do because of how I'm handling the provider with my client applications. I think its clear I could write something via the database with my personal project but I'm going to depend on active directory so I'm not responsible for user permissions. Notes:
http://docs.identityserver.io/en/release/topics/windows.html
https://stackoverflow.com/a/47438594/1265036: Solution
https://stackoverflow.com/questions/49682644/asp-net-core-2-0-ldap-active-directory-authentication
https://stackoverflow.com/questions/40986335/identityserver4-custom-authentication-with-active-directory
https://stackoverflow.com/questions/38736721/oauth-service-for-ldap-authentication
https://blogs.msdn.microsoft.com/dotnet/2017/11/16/announcing-the-windows-compatibility-pack-for-net-core
https://github.com/jusbuc2k/Justin.AspNetCore.LdapAuthentication
https://stackoverflow.com/questions/46729801/windows-authentication-does-not-accept-credentials: Example using claims
https://stackoverflow.com/questions/290548/validate-a-username-and-password-against-active-directory
0 notes
Text
.NET Developer job at NearU Sdn Bhd Malaysia
We are a startup that is already running that focuses on offering last-mile delivery solutions via our services. We are now looking to grow the tech team to further enhance and help improve the business from a tech point of view. Currently we are on the look out for senior .NET developer and senior iOS developer talent to join us!
Providing problem solving solutions that takes into consideration of multiple aspects (eg. users, business, etc.) and not just technology
Design, plan, build, test and deploy
Ensuring the robustness of applications are at top level
Maintenance and enhancements on application
Continuous discovery and implementation of new technologies
Deliverables of assigned tasks within the project timeline
Experience in .NET csharp (MVC, .NET CORE) using Microsoft Visual Studio
Proficient and familiar with SQL Server 2008 – 2016
Possesses strong problem solving skills
Possesses strong OOP skills
Experience in agile SDLC life cycle
Understand and adhere to good software and development principles
Experience in web services and 3rd party integrations
Obsessed with performance and optimization
Team player with good attitude and professional conduct
Passionate about latest technologies
Good communication and command of both spoken and written English
Added Advantage:
Experience and knowledge in front-end technologies; HTML, CSS, Javascript, AngularJS
Knowledge in web services implementation
Hands on with IdentityServer4 & PolicyServer
Knowledge in server and cloud
Proficient and familiar with MongoDB
Familiar with technology like Google Maps API
StartUp Jobs Asia - Startup Jobs in Singapore , Malaysia , HongKong ,Thailand from http://www.startupjobs.asia/job/38268–net-developer-it-job-at-nearu-sdn-bhd-malaysia Startup Jobs Asia https://startupjobsasia.tumblr.com/post/173889738124
0 notes
Text
.NET Developer job at NearU Sdn Bhd Malaysia
We are a startup that is already running that focuses on offering last-mile delivery solutions via our services. We are now looking to grow the tech team to further enhance and help improve the business from a tech point of view. Currently we are on the look out for senior .NET developer and senior iOS developer talent to join us!
Providing problem solving solutions that takes into consideration of multiple aspects (eg. users, business, etc.) and not just technology
Design, plan, build, test and deploy
Ensuring the robustness of applications are at top level
Maintenance and enhancements on application
Continuous discovery and implementation of new technologies
Deliverables of assigned tasks within the project timeline
Experience in .NET csharp (MVC, .NET CORE) using Microsoft Visual Studio
Proficient and familiar with SQL Server 2008 – 2016
Possesses strong problem solving skills
Possesses strong OOP skills
Experience in agile SDLC life cycle
Understand and adhere to good software and development principles
Experience in web services and 3rd party integrations
Obsessed with performance and optimization
Team player with good attitude and professional conduct
Passionate about latest technologies
Good communication and command of both spoken and written English
Added Advantage:
Experience and knowledge in front-end technologies; HTML, CSS, Javascript, AngularJS
Knowledge in web services implementation
Hands on with IdentityServer4 & PolicyServer
Knowledge in server and cloud
Proficient and familiar with MongoDB
Familiar with technology like Google Maps API
StartUp Jobs Asia - Startup Jobs in Singapore , Malaysia , HongKong ,Thailand from http://www.startupjobs.asia/job/38268--net-developer-it-job-at-nearu-sdn-bhd-malaysia
0 notes
Text
.NET Developer job at NearU Sdn Bhd Malaysia
We are a startup that is already running that focuses on offering last-mile delivery solutions via our services. We are now looking to grow the tech team to further enhance and help improve the business from a tech point of view. Currently we are on the look out for senior .NET developer and senior iOS developer talent to join us!
Providing problem solving solutions that takes into consideration of multiple aspects (eg. users, business, etc.) and not just technology
Design, plan, build, test and deploy
Ensuring the robustness of applications are at top level
Maintenance and enhancements on application
Continuous discovery and implementation of new technologies
Deliverables of assigned tasks within the project timeline
Experience in .NET csharp (MVC, .NET CORE) using Microsoft Visual Studio
Proficient and familiar with SQL Server 2008 – 2016
Possesses strong problem solving skills
Possesses strong OOP skills
Experience in agile SDLC life cycle
Understand and adhere to good software and development principles
Experience in web services and 3rd party integrations
Obsessed with performance and optimization
Team player with good attitude and professional conduct
Passionate about latest technologies
Good communication and command of both spoken and written English
Added Advantage:
Experience and knowledge in front-end technologies; HTML, CSS, Javascript, AngularJS
Knowledge in web services implementation
Hands on with IdentityServer4 & PolicyServer
Knowledge in server and cloud
Proficient and familiar with MongoDB
Familiar with technology like Google Maps API
From http://www.startupjobs.asia/job/38268–net-developer-it-job-at-nearu-sdn-bhd-malaysia
from https://startupjobsasiablog.wordpress.com/2018/05/14/net-developer-job-at-nearu-sdn-bhd-malaysia/
0 notes
Text
ASP.NET Core 3 and Angular 9 - Third Edition
I'm happy to announce that the ASP.NET Core 3 and Angular 9 book is finally available for purchase – in E-Book and Paperback format – on all the major online stores, including: Packt Publishing Amazon.com | it | uk | in |de | fr Google Play Barnes & Noble Mondadori Rakuten Kobo Booktopia ... and more! Here's the updated cover:
As always, if you get it from the Packt Publishing online store you'll be able to obtain a good discount (25%) by using the RYADEL25 promo code. If you want to know what the book is about, here's a detailed description: as you'll be able to see, the new edition is a complete rewrite of the previous ones, featuring a length of 732 pages (the 2nd edition was 550) and a huge GitHub source code repository filled with brand-new sample projects! I definitely hope that you will like it just like you did with the previous one (ASP.NET Core 2 and Angular 5), who happened to be a best-seller in multiple countries with more than 15000 copies sold throughout the world and even a video course on Udemy! That couldn’t be made possible without you, so thanks again and… get ready for another development journey! Key Features Explore the latest edition of the bestselling book ASP.NET Core 2 and Angular 5 Design, build and deploy a Single Page Application or Progressive Web App with ASP.NET Core and Angular Adopt a full stack approach to handle data management, Web APIs, application design, testing, SEO, security and deployment Book Description Learning full stack development calls for knowledge of both frontend and backend web development. By covering the impressive capabilities of ASP.NET Core 3.1 and Angular 9, right from project setup through to the deployment phase, this book will help you to develop your skills effectively. The book will get you started with using the .NET Core framework and Web API Controllers to implement API calls and server-side routing in the backend. Next, you will learn to build a data model with Entity Framework Core and configure it using either a local SQL Server instance or cloud-based data stores such as Microsoft Azure. The book will also help you handle user input with Angular reactive forms and frontend and backend validators for maximum effect. You will later explore the advanced debugging and unit testing features provided by xUnit.net (.NET Core) and Jasmine, as well as Karma for Angular. Finally, you will implement various authentication and authorization techniques with the ASP.NET Core Identity system and the new IdentityServer, as well as deploy your apps on Windows and Linux servers using IIS, Kestrel, and Nginx. By the end of this book, you will be equipped with the skills you need to create efficient web applications using ASP.NET Core and Angular. What you will learn Implement a Web API interface with ASP.NET Core and consume it with Angular using RxJS Observables Create a data model using Entity Framework Core with code-first approach and migrations support Set up and configure a SQL database server using a local instance or a cloud data store on Azure Perform C# and JavaScript debugging using Visual Studio 2019 Create TDD and BDD unit test using xUnit, Jasmine, and Karma Implement authentication and authorization using ASP.NET Identity, IdentityServer4, and Angular API Build Progressive Web Apps and explore Service Workers Who this book is for This book is for experienced ASP.NET developers who already know about ASP.NET Core and Angular and are looking to learn more about them and understand how to use them together to create production-ready Single Page Applications (SPAs) or Progressive Web Applications (PWAs). However, the fully-documented code samples (also available on GitHub) and the step-by-step implementation tutorials make this book easy-to-understand - even for beginners and developers who are just getting started. Table of Contents Getting Ready Looking Around Front-end and Back-end Interactions Data Model with Entity Framework Core Fetching and Displaying Data Forms and Data Validation Code Tweaks and Data Services Back-end and Front-end Debugging ASP.NET Core and Angular Unit Testing Authentication and Authorization Progressive Web Apps Windows and Linux Deployment Read the full article
#.NETCore#.NETCore3#Angular#Angular9#ASP.NETCore#ASP.NETCore3#Books#Full-Stack#Packt#PacktPublishing#PacktPub
0 notes
Text
Protect static files with ASP.NET Core
In this new post I explain how to protect static file with ASP.NET Core and IdentityServer 4 using Razor Pages deployed on Azure. This example is working with all kind of files apert from HTML and CSS files.
A few weeks ago, I started a new ASP.NET Core web application project to protect static files with authorization on that application, but I had no idea how to implement it at that time.
After a quick search on internet, I found some recommendation and I think I want to try to one of the following solutions:
Insert ASP.NET Core middleware that your custom implementation into HTTP process pipeline at the before of static files middleware and reject requests that aren’t authorized.
Place static files you want to authorize to outside of wwwroot, and serve it by ASP.NET Core MVC controller that your custom implementation, instead as explained by Microsoft official document site
However, I couldn’t use those solutions for some reasons specified with the constraint of this project.
So, I continued reading the search results, and finally, I found the solution that I prefer.
The solution that I prefer is, hook the OnPrepareResponse call back point of static files middleware.
Integration with IdentityServer
So, how protect static file with ASP.NET Core and Identity Server 4 starts with user authentication. In my previous post titled “Implement security workflow with Identity Server” I gave you an overview of what security with IdentityServer means for internal and external applications web based or console.
For that, I assume you have your IdentityServer somewhere and you have created a new client for this application, so, you have clientId and clientSecret. In my demo that you can download from GitHub, you have to insert your details in the appsettings.json
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } }, "AllowedHosts": "*", "IdentityServerConfiguration": { "Url": "yoururl", "ClientId": "yourclientid", "ClientSecret": "yourclientsecret" } }
After that, the Startup.cs should be ready to accept the requests.
public void ConfigureServices(IServiceCollection services) { services.AddRazorPages(options => { options.Conventions.AuthorizePage("/Login"); }); services.Configure<IdentityServerConfiguration>( Configuration.GetSection("IdentityServerConfiguration")); services.AddDistributedMemoryCache(); services.AddSession(options => { options.Cookie.Name = ".psc.Session"; options.IdleTimeout = TimeSpan.FromHours(12); }); services.AddAuthentication(options => { options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultChallengeScheme = "oidc"; }) .AddCookie(options => { options.ExpireTimeSpan = TimeSpan.FromMinutes(30); options.Cookie.Name = "psc.dashboard"; }) .AddOpenIdConnect("oidc", options => { IdentityServerConfiguration idsrv = Configuration .GetSection("IdentityServerConfiguration") .Get<IdentityServerConfiguration>(); options.Authority = idsrv.Url; options.ClientId = idsrv.ClientId; options.ClientSecret = idsrv.ClientSecret; #if DEBUG options.RequireHttpsMetadata = false; #else options.RequireHttpsMetadata = true; #endif options.ResponseType = "code"; options.Scope.Clear(); options.Scope.Add("openid"); options.Scope.Add("profile"); options.Scope.Add("email"); options.Scope.Add("roles"); options.Scope.Add("offline_access"); options.ClaimActions.MapJsonKey("role", "role", "role"); options.GetClaimsFromUserInfoEndpoint = true; options.SaveTokens = true; options.SignedOutRedirectUri = "/"; options.TokenValidationParameters = new TokenValidationParameters { NameClaimType = JwtClaimTypes.Name, RoleClaimType = JwtClaimTypes.Role, }; }); }
Then, the integration with IdentityServer is set but we have to add a mechanism for the login and the logout. The project is based on Razor Pages. The idea is just to add two pages:
Login page to force the application to redirect the user to the IdentityServer. Where the application receives the validation, the page has to redirect the user to the home page (for example)
Logout page to remove the cookies created for the authentication
To add authorization to the Login page, we have to change the Startup.cs. At the beginning of the ConfigureServices I added this code:
services.AddRazorPages(options => { options.Conventions.AuthorizePage("/Login"); });
After that, for the Logout page, we have to add the code to remove the cookies.
public async Task<IActionResult> OnGet() { await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); await HttpContext.SignOutAsync("oidc"); return Redirect("/"); }
Static Files middleware
Thinking about how to protect static file with ASP.NET Core and Identity Server 4, I started to look better to the middleware.
What is a middleware?
Middleware is software that’s assembled into an app pipeline to handle requests and responses. Each component:
Chooses whether to pass the request to the next component in the pipeline.
Can perform work before and after the next component in the pipeline.
Request delegates are used to build the request pipeline. The request delegates handle each HTTP request.
Request delegates are configured using Run, Map, and Use extension methods. An individual request delegate can be specified in-line as an anonymous method (called in-line middleware), or it can be defined in a reusable class. These reusable classes and in-line anonymous methods are middleware, also called middleware components. Each middleware component in the request pipeline is responsible for invoking the next component in the pipeline or short-circuiting the pipeline. When a middleware short-circuits, it’s called a terminal middleware because it prevents further middleware from processing the request.
ASP.NET Core Middleware
Use StaticFileOptions
When we register the “Static Files” middleware built-in ASP.NET Core into the HTTP process pipeline, we can also specify a StaticFileOptions option argument.
StaticFileOptions class has the property of a good hook point that allows us to insert a process before serving static files.
That property name is OnPrepareResponse.
We can set a call back function to the OnPrepareResponse property, then that function will be called back before serving each static file, and we can change the response rely on authorization state!
So, we have to register “Authentication” middleware at the before of “Static Files” middleware to be available detect authenticated or not.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { ... app.UseAuthentication(); app.UseStaticFiles(new StaticFileOptions { OnPrepareResponse = ctx => { if (!ctx.Context.User.Identity.IsAuthenticated) { // respond HTTP 401 Unauthorized. ctx.Context.Response.StatusCode = (int)HttpStatusCode.Unauthorized; } ...
My call back function exactly returned the “401 Unauthorized” HTTP status to the browser, but it didn’t stop the response body!
ASP.NET Core blocks the file
I have to not only return HTTP 401 but stop the entire of responding.
To do this, I appended 2 lines in my call back function like this:
// respond HTTP 401 Unauthorized, and... ctx.Context.Response.StatusCode = (int)HttpStatusCode.Unauthorized; // Append following 2 lines to drop body from static files middleware! ctx.Context.Response.ContentLength = 0; ctx.Context.Response.Body = Stream.Null;
This code drops the writing to the stream of response body from “Static Files” middleware, because that code replaces the body stream to System.Null.
The all of contents that wrote into System.Null is discarded, and it doesn’t cause any effects.
Finally, I could protect the secret static files.
This page isn’t working
Please remember, to protect those secret static files, we have to concern browser caches.
In some cases, I could see the secret file from browser cache even if I wasn’t authenticated after signed out from the application.
I avoided this problem by adding the “Cache-Control” header to the response.
ctx.Context.Response.Headers.Add("Cache-Control", "no-store");
If you want to redirect to another page such as “Sign in” page instead of returning “HTTP 401”, yes, you can do it by like this code:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { ... app.UseAuthentication(); app.UseStaticFiles(new StaticFileOptions { OnPrepareResponse = ctx => { if (!ctx.Context.User.Identity.IsAuthenticated) { // Can redirect to any URL where you prefer. ctx.Context.Response.Redirect("/") } ...
Conclusion
At the end of this post about how to protect static files with ASP.NET Core, my conclusions are:
We can protect static files with authorization on the ASP.NET Core web application by using the OnPrepareResponse property of the options argument for “Static Files” middleware.
Don’t forget that place the calling UseAuthentication() at before of the calling UseStaticFiles(...).
We have to drop the entire of the response body from “Static Files” middleware when the request is unauthorized.
Please consider cache control to protect static files perfectly.
We can also redirect to another page such as “Sign in” page instead of returning “HTTP 401”.
The entire of my sample code is public on the GitHub repository.
The post Protect static files with ASP.NET Core appeared first on PureSourceCode.
from WordPress https://www.puresourcecode.com/dotnet/net-core/protect-static-files-with-aspnet-core/
0 notes
Text
InputSelect component for enumerations in Blazor
In this new post about Blazor, I’m going to give you the code for InputSelect component for enumerations in Blazor. In the last few weeks I’m starting to talk about Blazor and here you have the other posts:
Getting Started With C# And Blazor
Setting Up A Blazor WebAssembly Application
Working With Blazor’s Component Model
Secure Blazor WebAssembly With IdentityServer4
Blazor Using HttpClient With Authentication
It’s common to use a dropdown list to select a value from an enumeration. In ASP.NET Core MVC you can use Html.GetEnumSelectList to create the items for an enumeration. This is very convenient and very productive. However, this helper doesn’t exist in Blazor. In this post, we’ll create something even easier to use.
The component InputSelect allows binding a property of type Enum. However, you need to provide all options manually which is error-prone and not very productive:
<EditForm Model="model"> <InputSelect @bind-Value="model.Season"> <option>Spring</option> <option>Summer</option> <option>Autumn</option> <option>Winter</option> </InputSelect> </EditForm> @code { Model model = new Model(); class Model { public Season Season { get; set; } } enum Season { Spring, Summer, Autumn, Winter } }
You can make this code more generic by iterating on Enum.GetValues:
<EditForm Model="model"> <InputSelect @bind-Value="model.Season"> @foreach (var value in Enum.GetValues(typeof(Season))) { <option>@value</option> } </InputSelect> </EditForm>
This way you can copy/paste the code for any enumeration you want to bind to a select. However, the display text is not customizable, so not very use friendly. It is also not localized. As always in Blazor, the solution is to create a component! Components allow encapsulating reusable behaviors. Then, you can use them in your other components and avoid duplicating code.
InputSelectEnum Blazor component
To create this component, I checked how the InputSelect component is made on GitHub. The code is very simple. It contains 2 methods: BuildRenderTree and TryParseValueFromString. We’ll change the first one to populate the option elements when creating the tree instead of using the template ChildContent. The TryParseValueFromString method converts the string value from the select element to a valid enumeration value. We’ll adapt this method to support nullable types.
A few points to note in the implementation:
This component supports nullable types which is not the case of the InputSelect component.
This component read the [Display] attribute to create the option display names. If no attribute is defined, it decamelizes the enumeration member name. This attribute allows localizing the application.
In previous posts, we have created components using the razor syntax. In this case, it is easier to create the component in C# code only. You can add the code in the “Shared” folder, so the component is accessible in all the views. I’ve added a few comments to explain the code. But don’t worry, there’s nothing complicated in this component.
using System; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using Humanizer; using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components.Forms; using Microsoft.AspNetCore.Components.Rendering; // Inherit from InputBase so the hard work is already implemented
// Note that adding a constraint on TEnum (where T : Enum) doesn't work when used in the view, Razor raises an error at build time. Also, this would prevent using nullable types... public sealed class InputSelectEnum<TEnum> : InputBase<TEnum> { // Generate html when the component is rendered. protected override void BuildRenderTree(RenderTreeBuilder builder) { builder.OpenElement(0, "select"); builder.AddMultipleAttributes(1, AdditionalAttributes); builder.AddAttribute(2, "class", CssClass); builder.AddAttribute(3, "value", BindConverter.FormatValue(CurrentValueAsString)); builder.AddAttribute(4, "onchange", EventCallback.Factory.CreateBinder<string>(this, value => CurrentValueAsString = value, CurrentValueAsString, null)); // Add an option element per enum value var enumType = GetEnumType(); foreach (TEnum value in Enum.GetValues(enumType)) { builder.OpenElement(5, "option"); builder.AddAttribute(6, "value", value.ToString()); builder.AddContent(7, GetDisplayName(value)); builder.CloseElement(); } builder.CloseElement(); // close the select element } protected override bool TryParseValueFromString(string value, out TEnum result, out string validationErrorMessage) { // Let's Blazor convert the value for us
if (BindConverter.TryConvertTo(value, CultureInfo.CurrentCulture, out TEnum parsedValue)) { result = parsedValue; validationErrorMessage = null; return true; } // Map null/empty value to null if the bound object is nullable if (string.IsNullOrEmpty(value)) { var nullableType = Nullable.GetUnderlyingType(typeof(TEnum)); if (nullableType != null) { result = default; validationErrorMessage = null; return true; } } // The value is invalid => set the error message result = default; validationErrorMessage = $"The {FieldIdentifier.FieldName} field is not valid."; return false; } // Get the display text for an enum value: // - Use the DisplayAttribute if set on the enum member, so this support localization // - Fallback on Humanizer to decamelize the enum member name private string GetDisplayName(TEnum value) { // Read the Display attribute name var member = value.GetType().GetMember(value.ToString())[0]; var displayAttribute = member.GetCustomAttribute<DisplayAttribute>(); if (displayAttribute != null) return displayAttribute.GetName(); // Require the NuGet package Humanizer.Core // <PackageReference Include = "Humanizer.Core" Version = "2.8.26" /> return value.ToString().Humanize(); } // Get the actual enum type. It unwrap Nullable<T> if needed // MyEnum => MyEnum // MyEnum? => MyEnum private Type GetEnumType() { var nullableType = Nullable.GetUnderlyingType(typeof(TEnum)); if (nullableType != null) return nullableType; return typeof(TEnum); } }
You can now use this component in another Blazor component:
<EditForm Model="model"> <div> @* The type of the enum (TEnum) is detected by the type of the bound property which is just awesome! *@ <InputSelectEnum @bind-Value="model.Season" /> <span>Selected value: @model.Season</span> </div> </EditForm> @code { Model model = new Model(); class Model { public Season Season { get; set; } } enum Season { [Display(Name = "Spring", ResourceType = typeof(Resources))] Spring, [Display(Name = "Summer", ResourceType = typeof(Resources))] Summer, [Display(Name = "Autumn", ResourceType = typeof(Resources))] Autumn, [Display(Name = "Winter", ResourceType = typeof(Resources))] Winter, } }
The post InputSelect component for enumerations in Blazor appeared first on PureSourceCode.
from WordPress https://www.puresourcecode.com/dotnet/blazor/inputselect-component-for-enumerations-in-blazor/
0 notes