Wednesday 22 May 2019

Azure B2C Authentication for SaaS applications

Overview:  This blog post looks at setting up multiple public federation services on an Azure based SaaS web application.  It is worth understanding that a Microsoft account (old passport accounts) is like a google account and not the same as an Organisational Account (Azure AD IT company (e.g. paul@mycompany.com) setup account.

AAD B2C Overview
1. Client using a browser, goes to a website URL
2. User receives a 302 HTTP response and is redirected to Azure's B2C (AAD and Azure B2C are separate services)
3. User is prompted to login (assuming they don't already have a valid token)
4. After the user is authenticated, they get a Valid token.
5. Using a valid token, the users sessions is established on the web site.

The diagram does not show the flow pass B2C, this shall use "Passive-claims base authentication" to select the users Identity Provider e.g. Google account.  Once the user has a google account authenticated, they are redirected back to the B2C service where the Google token is used to issue a B2C user token for the user.  And step 4 continues.

Azure Active Directory (AAD) also sometimes referred to as AAD B2C
Has two types of users, namely:
1. Members - these are internal company users from an organization e.g., paul.beck@mycompany.com
2. Guests - are external users from outside our company e.g., harry@jpmorgan.com
Tip: Native member users passwords are stored in your Azure B2C service.  Whereas, native guest users e.g. harry@jpmorgan.com, actually logs into JP Morgans AAD and our AAD tenant sees him as a guest and issues a SAML token from us based on JPMorgan's assertion that the user is valid on their AAD tenant.
Note:  A guest user can be made a member and a member user can be changed to be a guest user.  There is no good reason that I have come across for switching guests to members (maybe 2 companies merging) but it is possible if you need to do it.
AAD supports the  following protocols: WS-Federation, SAMLP, & OIDC & OAuth2.  WS-Fed and SAMLP are used but go for OIDC as the default.

AAD B2C Instance:
The diagram above show AAD B2C not B2C.  B2B is provisiong on you Azure tenant and is tied to your O365 instance.  B2C is a separate Azure service used fro managing customers identities.  So if I have a website and some mobile applications, offered an API to clients, I would use B2C not B2B for managing security.  You can connect multiple AAD B2C to your single B2C instance.  B2C basically allows you to connect to other Identity providers using SAML, OIDC, OAuth2 and WS-Fed.  B2C also has the option to use it's own local store if the user doesn't want to connect existing accounts.

If a user has a gmail account, B2C can create an object in the service, but the users password is still maintained by Google.   When accessing our applications, the user goes to the B2C service instance, and then is pushed onto their own IdP (Google in this example) , once they authenticate, they are redirected to the B2C servce, get another new B2C token and are redirected back to the app and shall have access.

Billing/Cost of AAD B2C Service:
B2C is base on Monthly Active Users (MAU), you can have 60k users in the B2C but only 20k of the users have actively logged in using the B2C service.  Dormant/unused accounts in a calendar moth are not counted.
Updated 30 Nov 2019: first 50k MAU's are free for single factor authentication.  It's very cheap per user after the initial 50k and get's cheaper the more you have per user i.e. 50k-100k are £0.0041 per user.  So if I have 61,000 users, the first 50,000 are free and I pay £0.0041 per MAU for the next 11,000 users, amounting to £45.10 for my additional 11k users.
Multi Factor Authentication (MFA) is billed at £0.023 per event (think event as each SMS attempt both successful or failed).  So if the users use MFA and each of the 20k MAU users do 3 MFA's per month on average, the first part is free and the MFA part will cost (20,000 users * 3 attempts * 0.023 per SMS) £1380 per month.  It's a bargain.


More Info:
Great Post from my ex colleague Deepak Srinivasan on Guest and Member AAD access
Understanding ADFS Authentication with SharePoint

Sunday 12 May 2019

PowerApps Input Validation

Overview:  Validation can be handled in a multitude of ways in Power Apps, this technique I used for a fairly advanced set of Validation Requirements.


Basic Validation Example
To check that at least 1 of these two textInput box has been filled in.  Add this function to the DisplayMode:
If((IsBlank(srchMemberAccNo.Text)) && (IsBlank(srchMemberEmail.Text)), DisplayMode.Disabled, DisplayMode.Edit)

There are a number of ways to check if data exists in a control, I just try keep them consistent throughout my logic.  Here is a good approach: If(Not(IsBlank(txtBox1.Text)),<true>,<false>)

Designing an API with Web API on Azure

.NET core is great for creating a Web API project to provide an API.
Tip: Swagger is a great tool that has an editor to specify your API.  With the OpenAPI specification for your API, you can generate documentation, or use the code generation feature to generate tests or C# code.
Tip:  Use the Swashbuckle.AspNetCore Nugget package to generate an OpenAPI specification for your API if you use a code first approach.

Do not trust incoming parameters, you must validate.  Always respond with generic header error messages so you don't give away back-end information.  Ensure you log all errors and review them.

Preferred High Level Design I like for Web API projects

The API needs to return Status Codes to allow consumers/clients to know how there operations are doing so I design with these standard HTTP status codes:

CodeCode Status Meaning
200OK (GET)
201Created (POST or PUT)
202Accepted.  Used for long running operations.
204Resource has been deleted (DELETE)
304Not Modified
400Bad Request
401Not Authorized
403Forbidden
404Not Found
422Entity Validation Issue
429Too many Requests (Implement at APIM layer only)
500Internal Error
    



  • The bold codes are the three minimum set of response codes I will use for a simple API.  The next 4 most important are italicized.
  • Name resources/EndPoints with nouns and I always use lowercase e.g. /api/customers is better than verb noun which was common a few years ago, e.g., /api/GetAllCustomers  NB!  No verbs in URL naming.
  • Keep the URL's simple.
  • Always use HTTPS.
  • DateTime data is always in UTC.
  • Sensitive information must be in the header or body, not in the URL as it is not encrypted.

URL/Resource

GET

(read)

POST

(create)

PUT

(Update)

DELETE

(Delete)

/customers

List all customers

Add/created a new customer

Bulk update customers

Bulk Delete or Generally error and don’t implement

/customers/35

Get a specific customer.  Customer 35 is John DoeNAUpdate the John Doe recordDelete the John Doe object/record

HTTP Methods to Support
GETReturn the current value of an object
PUTReplace or update an object
DELETEDelete an object
POSTCreate a new object.  Return 201 for created and 202 for long running operations.
* PATCH - is also used for updating objects but normally a subsets of existing data

Versioning
API's need to change but there can be multiple client applications consuming my OpenAPI.  We use versioning to ensure I don't break existing implementations.  There are different strategies for versioning API's:
  • No versioning:   https://pbeck.co.uk/customers/35
  • URI versioning: https://pbeck.co.uk/v2/customers/35
  • Query string versioning: https://pbeck/customers/35?version=2
  • Header Versioning:  Not in the URL but passed in the header (my preferred option)
APIM has a great implementation for versioning.  Generally, adding optional data is pretty safe for API versioning.  You need to give 3rd parties using your API's time to implement the new version before deprecating and versions.

Tip: Enforce versions are present in the header.  No version return bad request.

JSON
JSON property names SHOULD be camelCased.

Query Params
Allow filtering using query param e.g. https://pbeck.co.uk/customers?firstname='paul'
Allow sorting for the most common properties
DateTime should be in UTC - The pattern for this date and time format is YYYY-MM-DDThh:mm:ss.sTZD. It is recommended to use the ISO-8601 format.  UI does adjustment for local time display.

Paging
Requests must have max return limit e.g. 100 items.  Specifying the limit param if you want to change the size of the dataset to return.

CORS
Cross Origin Request will need to be supported, reply on OAuth for who can use the API.

HATEOAS 
Good way to navigate around your API.  And a principle worth adhering to where possible.  

Authentication and Authorization
API's access should be via OAuth2.0.  It is very easy to hook APIM and underlying App Service (Web API) up to AAD B2C.  Scopes are used for authorization.

Code Review/Quality
"Linting is the automated checking of your source code for programmatic and stylistic errors. This is done by using a lint tool (otherwise known as linter)".   Examples of Linting Tools are Resharper, StyleCopSonarQube, ...

Security

It's a good idea to also have a WAF in front of your API.

Sunday 7 April 2019

Azure Active Directory, B2C and Rights

Azure Identity Management is a fairly large body on knowledge.  Basically, dividing it into different areas makes if easier to understand.

RBAC in Azure:
Azure AD and B2C bother offer a way to authenticate a user thru the user providing an identity.
The user is assigned to 1 or more groups, and then the groups (or individual users) are assigned to Roles.  The diagram below shows internal and external users and how permissions can be given out.  Resulting in Role Based Access Control (RBAC).  The application itself deals with the operations a user can perform but having the users role/claims allows the individual applications to figure out what action the user can perform.

RBAC can be assigned at 1 of these 4 levels to manage Azure Resources:

Tip: For small Azure Tenants, managing resources are the resource level works well, but in most enterprises, you should mange at the Resource group or even subscription level to keep management controllable.
Note: There is the concept of "Directory", multiple "Resource Groups" are setup to a directory.  I believe all companies should have a single directory but it is more common to find even relatively small businesses common to have multiple directories. 
"Multiple subscriptions can trust the same Azure AD directory. Each subscription can only trust a single directory." Microsoft Docs

Thursday 4 April 2019

Adding users to all new SQL database using Azure AD groups

Problem:  I have a dedicated SQL 2017 VM on Azure that is joined to my Azure AD tenant e.g. int.contoso.com (Azure AD Domain Service).  I need a set of users to have read and write access to all databases that get provisioned on the SQL 2017 instance.

Initial Hypothesis: 
Create an Azure AD security group and add all the AAD users and
Add the AAD group to the Model database with the permissions that all new database should have.

Resolution:
1. Using Azure AD create a new security group, I called my group developers and add the users as members Fig 1.& Fig2.
Fig 1. Azure Portal, go to Azure AD and Groups

Fig2. Add the security group

2. Add the AAD Group e.g. int.contoso.com\Developers to the System "Model Database", I have given the group read and write access below in Fig 3.
Fig3. Add permissions to the Model DB
3. Create a new database and validate that the new permissions are added to the new database as shown in fig4.
Fig4.
Note: Changing exsiting DB permissions
To add permissions to existing database, an option is to run
EXEC sp_MSForEachDB 'exec sp_addrolemember ''db_datareader'',''INT\paul.beck'''
T-SQL to list of Daatbase: EXEC sp_MSforeachdb 'USE ? SELECT SF.Name FROM sys.databases SF'


Wednesday 3 April 2019

PowerBI Pro for Licencing

Problem:  Requirement to provide reporting and dashboards quickly and securely at a reasonable price.

Hypothesis: There are great reporting solutions and a couple of enterprise leading products are TableauQlik.  These can get pretty expensive installing and paying for licencing.

Proposed Resolution: PowerBI Pro (PowerBI Premium is for larger enterprise solutions) is a cloud based solution that can connect to multiple data source and on-prem using the Gateway.  E5 licences include the PowerBI Pro licence for creating and publishing reports.  E3 licence can get a add-on for about £7.50 per month.  This is only needed by the people creating the reports.
 
To paraphrase "You can embed the report (not dashboard) on a SharePoint web page and share it with company users. You will then only be needing one licence to publish the report. The downside of this option is there is no builtin security for the report. Anyone who has access to the web page can access the report."

Disclaimer: These are my thoughts and understanding, pls check your licencing with Microsoft and a licencing professional.

Updated: Nov 2022
3 Power BI licence types:
  1. Free (per user)
  2. Pro (per user per month) $
  3. Premium (resource/capacity based)  $$$ - 2 options
Choose depending on usage patter, so Premium is great for enterprises level but out of the range for most SME businesses.  Feature and pricing comparison

Saturday 30 March 2019

Azure Security Checklist

Overview:  Constantly improving Security on Azure and Office 365 is essential to a lot of companies.  Microsoft provide outstanding infrastructure and monitoring for companies and it is also the companies responsibility to configure and secure O365 and Azure to ensure security and allow for the appropriate liberalization of services so the business can operate effectively.  This post outlines some basic items to look at to optimize the balance of security and it meeting you business needs.

I generally go through the infrastructure and write up a report for management in the form of:  Finding, Recommendation and Management Comment.

Finding:  The company users login using their Azure AD accounts and the credentials page has not got customized branding to help user know they are logging into the companies secure resources (SharePoint, email etc.)
Recommendation:  Using the "Azure Portal", use the "Azure Active Directory" Service > "Company Branding" to upload the company logo in banner and square format and update the color/theme for match the firms branding.
Management Comment: We accept the finding and wish to mark the changes immediately.

Microsoft Provide Tooling to help identify improvements and below are two tools you can use to help clarify the current environment so improvements can be recommended.

Network Security Groups (NSG's)
NSG's are basically firewall on Azure.  Fantastic and simple.  They can get really complex with multiple policies.  Azure gives you great tooling for Azure networks called "Network Watcher".