Download as pdf or txt
Download as pdf or txt
You are on page 1of 54

Module 5 - Secure Coding Practices for Authentication &

Authorization

Module Objectives

Understand Authentication and Authorization

Explain Authentication and Authorization in Web Forms

Explain Authentication and Authorization in ASP.NET Core

Explain Authentication and Authorization in MVC

Learn Authentication and Authorization Defensive Techniques in Web


Forms

Learn Authentication and Authorization Defensive Techniques in ASP.NET


Core

Learn Authentication and Authorization Defensive Techniques in MVC

; y ; : | ATE
Authentication and Authorization C | AS
Authentication \ Authorization
| Authentication is the process of verifying a user's |
Authorization is the process of giving a specific rights
identity with an application by using some sort of to the
authenticated users to perform specific tasks
credentials . ) i
| For example: Administrator is an authorized person
| Authentication is always performed before and has privileges and
rights to add or delete any user
authorization account

For example: Username and passwords are used to


authenticate the user with the system

He is John
A
= ] : ! < home.aspx
! Authentication Authorization | >
" #4 (Whoare i) (What rights
> 4 | @ you?) | you have) |W
: admin.aspx
User i
¥

He is an admin and has access to


all pages on the website

Page 139
Common Attacks due to Improper User

| J NET]
Authentication and Authorization [¢ A s E

= Accessing the account of a legitimate user by guessing or stealing


the credentials so as to obtain or tamper with
| Ato igcdy sensitive information

Man-in-the-middle | Intercepting the traffic to read or modify data


during transmission

Luring the legitimate user to enter his/her credentials through fake


website links that look like legitimate

Phishing websites

| Unauthorized Access [ Gaining access to restricted resources though


he/she has no rights to do so
Information Leakage | Using unprotected or revealed information to
compromise the system

| Privilege Escalation | Acquiring higher-level privileges for an


account

Sniffing

Intercepting passwords or confidential information that travels across


the network by using sniffing tools

Authentication and Authorization: Web Forms

Page 140
NET Authentication and Authorization

ns

Anonymous

Basic

Digest

Integrated Windows
Certificate

é
IF | 1IS/ASP.NET
Web Application

Clients Web Server

None, Connect, Call, Packet,

Authentication
Windows,
Form, Passport, None (Custom)

Authorization
Web, NTFS, and Principle Permissions
URL Authz, File Authz, .NET Roles
*

é
1IS/ASP.NET | 1IS/ASP.NET
Web Services Remoting
[ Enterprise Services
RPC Authentication

Integrity, Privacy

RPC

Authorization
ES (COM+) Roles NTFS Permissions

Authentication
Windows, SQL

Authorization
Login Permission Roles

Database
Server

Different Levels of Authentication

Le,
‘rm

CAS

security level

7'S

J The .NET framework provides three levels of authentication depending


upon the web application

ASP.NET Authentication

Enterprise Services Authentication

SQL Server Authentication

Page 141
ASP.NET Authentication

ASP.NET provides a flexible set of alternatives for authentication

It can be performed through coding or by delegating authentication to


other authorities

As the ASP.NET layer is placed just below the Internet Information


Service (11S) level in the web application

security architecture

All requests go through the IIS layer before they are passed to the
ASP.NET layer
The IIS layer can decide to deny access without passing the request to
the ASP.NET layer

ASP.NET Authentication Modes

J NET]
CASE

II

Authentication modes available in ASP.NET

Forms Authentication

Passport Authentication

None Authentication

Windows Authentication

Federated Authentication

J ASP.NET provides various modes of authentication that can be used


for validating a user's credentials and implementing
other security measures

Authentication Modes are Specified in the Web.config File:

Web.config® = X +
version="1 "

#4 Publish =

https://docs.snowflake.com/en/user-guide/admin-security-fed-auth-
overview. html

Page 142
Forms Authentication

Client request
v
| Form authentication collects the user credentials, such us IF IS
authentication settings are set properly, the
as username and password, directly from the user and - request is
passed to ASP.NET
implements customized logic for authenticating it rs
J Auth- ®
FRG > Logon form collects user credentials
v
Authenticate credentials
“| Though form authentication mode does not use the pa
11S authentication; still, it is important to set the IIS a»
authentication setting to run the ASP.NET application enticated? or
v
Attack cookie i
v
Nok i
| For example, IIS Anonymous Access setting is enabled pri cl H
when all the incoming requests are supposed to be ASP.NET ¥ §
allowed to reach form authentication of the ASP.NET 5X
application denied
ET Vo
Allow access to
protected resources
. R : | y NET]
Forms Authentication (Cont'd) CASE

It involves 4 steps:

1. Enable anonymous access in IIS

2. Configure the <authentication> section inthe


Web.config file

Web config” @ X

3. Configure the <authorization> section in the


Web.config file

b= i

Webiconfig® # X

4. Create a login page

Authenticate
§ fat dk TE RT
i Vv
H —1


| | @ Ree! Login aspx + data - a I

asa AE RT BL Wh pe

(Web.config or

User database)

Page 143
Passport Authentication CASE

J Passport authentication is a centralized authentication service from


Microsoft for authenticating users
J The classification of authenticated users is done by using an
encrypted cookie mechanism

| 1t offers single sign-in for accessing member sites or protected


resources

Password authentication can be used in the following situations:


1.) Username and password are not configured for database or login
access
Users are willing to provide personalized content

2.4
e The site used in conjunction with other sites that use passport
authentication
=

Administrators recognize situations where the user requires to sign-on


capability

Passport Authentication (Cont'd) C | ASE

| Users who are already signed in to passport are considered


authenticated and are directed to the site; other users are
redirected to the passport server to log in

I Request Wekomeasx jruopbay


PEE cs ons FE Client rr
Response: Welcome.aspx + cookie : Application
Server
: Passport authentication [2] A
i ereates authentication i Credentials H
: cookies H
Redirect to Passport logon
Authentication Ticket +
Microsoft Passport Logon Redirect to Application Server
Passport Service

Page 144
Custom Authentication

2 It is responsible for matching user-provided


credentials (such as, the username password
pair) against the credentials maintained in a
database

7 To develop custom authentication code, specify


"None" as the authentication provider when
users are not authenticated

A custom or none authentication can be


implemented by creating ISAPI filter, which is
used to bypass the IIS authentication

AS

NZ Custom or none authentication can be


configured as shown in the Web.config file

mo LE ;
= RN

Web.config® + X Hon

4 Publish «

Implementing Custom Authentication Scheme


Classes

AuthenticationException

InvalidCredentialException

Enumerations

oe]

The exception that is thrown when authentication fails for an


authentication
stream

The exception that is thrown when authentication fails for an


authentication stream
and cannot be retried

EE

CipherAlgorithmType Defines the possible cipher algorithms for the


SsiStream class
ExchangeAlgorithmType Specifies the algorithm used to create keys
shared by the client and server
HashAlgorithmType Specifies the algorithm used for generating message
authentication codes (MACs)
SslProtocols Defines the possible versions of SsIProtocols

Page 145
Windows Authentication

| Windows authentication is the default mode of


authentication. It authenticates the user based on the
user’s windows identity

In Windows authentication, ASP.NET relies on IIS to


authenticate the user. IIS creates a windows access
token based on the windows identity of the user and
uses it to represent a particular user

J The correctness of the token depends on IIS


authentication configuration, ASP.NET authentication
providers and appropriate settings of ASP.NET
impersonation

Project Build Debug Signin

Test An Win

T-wE

Web.config® #8 X Home.asp

A Publish =

Windows Authentication (Cont'd)

Pm mm mm a mt em mm em me
© The username and password
are supplied as credentials to
prove identity

1
The browser (client) sends the |
windows credentials to the :
web server in an unencrypted |
format i
1

1
1

The server then performs


remote calls using supplied
user credentials

This authentication can only be


used when a secure channel is
used

Digest Authentication

© [tis similar to basic


authentication but instead of
sending user's credentials in
an unencrypted format, it
sends the Hash value of the
credentials

i
i
1
i
i
1
1
i
i
i
i
i
i
i
1
i
i © Itis more secure than basic
' authentication
i
i
i
i
i
1
i
i
i
i
1
i
i
1
1

| There are five different windows authentication methods provided by


the [1S

Basic Authentication [EES i

@ It uses secret-key cryptography


to encrypt the credentials to be
sent from the browser to the
web server to prove identity

t
i

I]

: The application uses either the

| Kerberos or NTLM

i challenge/response protocols to
| authenticate the user (based on
| the client and server

i configuration)

1]

1
i

It provides secure and strong


authentication for client/server
applications

Page 146
Windows Authentication (Cont'd) CA SE

Certificate Althentication in : : CETTE : = a -

@ |t uses client certificates to prove their identity [

® This certificate is sent from the client to the web server where it
extracts the user's identity from the |
client certificate

@ If anonymous authentication is selected, then any one can access the


ASP.NET application because IIS
does not perform any authentication

Selecting an Appropriate Authentication Method C | A SE

| The selection of authentication methods depends upon the following


factors:
B |
. Operating systems of server and client
B
Type of client browser
B 1 Number of users, location and type of username and password
database
B
Deployment considerations (Internet vs Intranet and Firewalls)

B 1 Application type (interactive website or non-interactive web


service)

B 1 Sensitivity of data that is being protected


7] 1 Performance and scalability factors

B | Application authorization requirements (all users or restricted


areas)

Page 147
Determining an Authentication Method CA

ir Users od app XK V7 custom Credential


Suis > inWindows runs on ed > Mapping asc,
accounts? Intemet? ‘and Kerberos
h,
i VW
x, x v Vv
Perso- x ¥ x Vv Basic,
nalization > Anonymous Reet) . > Passport mics pi FOIE,
Be > Wms
required? Digest and Certificates
vi x
i v i
wv v
x Basic, Digest,
Anonymous | Interactive Forms/ssi
and cookies Corticales i lost phtering x Crm

Enterprise Services Authentication CASE

J Itis performed with remote procedure call (RPC) that uses the
Security Service Provider Interface (SSP1) API of the
operating system
| Kerberos or NTLM authentication is used to authenticate clients of
the enterprise services applications
J The serviced component is included in the library application and
these library applications are included in the client
processes. This helps in recognizing the client's identity
I The service component is also included in the server application
that runs through separate processes on the server with
individual identity

Client Process

Process Identity: Process P2

Process Identity: Process P1

Page 148
Enterprise Services Authentication (Cont'd) C A SE
_| Authentication for the serviced component is performed by issuing
Remote Procedure Calls (RPC) at following levels:
I Default | It provides default authentication for the serviced
component |
None | It does not provide any authentication to the serviced
component
Connect | Itprovides authentication when the connection is
established [
I Call | It authenticates the serviced component at the start of each
RPC |
Packet | Itauthenticates as well as verifies all call data, whether it
is received or not
I Packet Integrity | tis used to authenticate and ensure that the
packet data are not modified during transmission [
Packet Privacy | i as well as encryption for the packet that includes
the data and the sender's identity

SQL Server Authentication

| The user is authenticated to the SQL server either with the help of
windows authentication (NTLM or Kerberos) or through
its built-in authentication scheme, known as SQL authentication

SQL Server Authentication Types


Mixed Mode Authentication Windows Authentication
@ The client is authenticated to the SQL Server & The client
is authenticated to the SQL Server
with the help of Windows authentication with Windows authentication
mode only

and SQL authentication modes

Page 149
Different Level of Authorization

1 Once authentication completed, the user then needs to be authorized


for specific operations or to access specific resources

| It allows to define roles and the interaction of these roles with


the applications operation or resources

The .NET Framework provides the following Level of Authorization

ASP.NET Authorization

Enterprise Services Authorization

SQL Server Authorization

ASP.NET Authorization CA SE

J ASP.NET provides the following authorization options to authorize


the client

op] URL Authorization

File Authorization

Code-based Authorization

.NET Roles

Page 150
URL Authorization

| It allows or denies a user to access particular directory by using


username or role

| Configure the URL authorization on a particular file by specifying


the list of users or roles in the allow or deny attributes of the
authorization tag in the Web.config file

| Syntax for authorization section:

<authorization> <[allow|deny] users roles verbs


/>
</authorization>

The Web.config file shows how to grant or deny access to the user

This element is used to specify the user to which access is


granted or denied
USERS ‘? * denotes the Anonymous users
“*" denotes all the authenticated users
hi: i i I If
ROLES This element is used to specify the role for the current
request
This element is used to specify the HTTP verbs to which the
action replies; the HTTP verbs may include as GET HEAD, and
VERBS e d

POST.
("*"} it is default value used to denotes all verbs.

File

Edit

Build Signin

J wl

Web.config™ # X

File Authorization

| ATE
CASE

File authorization checks the access rights of the user account in


which ASP.NET is running for NTFS file

permissions

= When the user requests a particular file to read, it checks the user
account against read permissions to that file
= The ASP.NET engine by default runs under the ASP.NET user account as
impersonation is “false” in Web.config file

However it is possible to change it through impersonation by making


impersonation “true” in Web.config file

Note: File authorization is only supported for Windows authentication

Page 151
y.NET]
What is Impersonation? CASE

Impersonation is a process of ensuring user identity to access


protected resources

The approval or denial of the access to resources is based on user


identity

It helps run server processes by using security credentials of the


client
If it is enabled in the Web.config file, then the ASP.NET worker
process will impersonate the authenticated user to
access specific resources

ASP.NET impersonates the user from using attached security tokens and
verifies the rights of the user for accessing
resources as specified in the <autharization> element of
the Web.config file

Impersonation Options CA SE

Example

Impersonation is Disabled

@ By default impersonation is disabled, this sets the


ASP.NET process identity to local system account

Example

[ i nabl
Dieconconitise Home.aspx® Web.config® ® X Home.

© When itis enabled, ASP.NET impersonates the


authentication token from the 11S. The user may be
either the authenticated user or an anonymous user

Impersonation Enabled for a Example

Specific Identity {
2 Web.config® # X Hon
© Itis possible for ASP.NET to impersonate the
authentication token for specific identity

Page 152
J NET]
Delegation CASE

1] ih Impersonation enables ASP.NET to access the resources only on


the web server, where it is running

(5) Delegation is a more powerful form of impersonation where ASP.NET


can access the resources located on
the remote server

(3) Delegation will only work when ASP.NET is able to authenticate


against a remote server (with the help of
client's credentials)

4] The attacker may misuse this delegation as it makes the network


more vulnerable to sophisticated attacks

Code-based Authorization CA SE

J tis possible to authorize users through programming


| This approach provides more flexibility in authorizing users
I It allows enforcement of granular security checks throughout the
application

Ways of Programming for User Authorization

Explicit Authorization

Declarative Authorization

Imperative Authorization

i B yi
| | I. J
— >

Note: It is recommended to use code-based authorization for better


protection

Page 153
Authorization using ASP.NET Roles € A SE

The following authorization configuration shows that


users in the role of members are only allowed to access
the pages contained in the member Pages folder

| The ASP.NET role is also used to control the access to the resource
of
the application

- 0

J It considers a group of users as a single unit and assigns it to


roles File Edit Ji Sani

we

De!
Help
-
| These roles are used to manage access rules for the group of users
Web.config® ® X

J Itis used to put a restriction on the pages to limit the access of


the
user

Sample configuration for ASP.NET role management in Web.config file

Home.as. Web.config® # X Home.aspx.cs®

. : i 3 | J NET]
Enterprise Services Authorization CASE

| Authorization at the enterprise services level is provided through


enterprise services (COM+) roles
| These roles contain windows group or user accounts
| The COM+ catalog is used to define role membership
| This role membership is administered by using the component services
tool

Enterprise Services Authorization Steps

‘When the user tries to call method on the serviced Once the user is
authenticated, the enterprise
(1) component, the authentication process takes (2] services
interception layer accesses the COM+
place catalog to decide role membership of the client

Once it is decided, it checks whether the


3] membership of the role or roles allows

4] If it does so, then method gets called, otherwise,


authorized access to the current application

the method call will be rejected

Page 154
| A
SQL Server Authorization CASE

J SQL Server imposes fine-grained permissions on individual database


objects
| These permissions are given by using role-based membership or
granted to individual windows user accounts or group accounts

SQL Server supports Three Types of Roles

efined Database Roles : Application Roles Fixed Database Roles


: ® Groups of users who have i @ [talso establishes object © SQL
server provides fixed
identical security privilegesin | permissions, such as user server
roles that include
the database i database roles: but it does not db_datareader and
: contain users or groups as that db_datawriter. Itis used
i ® Windows user or group ; of user database roles to give a specific
set of
accounts can be added to user | permissions within the
database roles ! @ The application activates these database
t roles by using built-in stored
+ 8 These roles are used to give 1 procedure; it then grants the
permissions on the individual | permissions to the role

database objects such as


stored procedures, tables,
views, etc.

| ATE
Last

Authentication and Authorization: ASP.NET Core

Page 155
ASP.NET Core Authentication

Authentication can be implemented in ASP.NET Core using:


& ASP.NET Core Identity

@ Token Authentication

ASP.NET Core Identity Token Authentication


J Login and Logout Co ———
| Registration Secure
| Password Management I Scalable
J Lockout | Single-page Applications

| Third-party Logins I Mobile Apps

| Twao-factor Authentication

AspNetCore.Identity € A SE

Used to maintain access control (authentication and authorization)

[ 2 ASP.NET Core Identity works with OWIN middleware

It is a Claims-based identity which stares logins, claims and roles

ASP.NET Identity Managers ASP.NET Identity Store


IUserStore Stores user details
UserManager For managing user IUserLoginStore Stores login details
IUserClaimStore Stores user claims
RoleManager For managing roles IUserRoleStore Stores user roles
IRoleStore Stores roles
SigninManager For managing signin
IUserPasswordStore Stores user passwords

Page 156
ASP.NET Core Authentication

No Authentication

Individual User Accounts

Work and School Accounts

Windows Authentication

© Facebook

2 Google

Templates

Applications without authentication

Application with local user account store

Application that authenticates users with Active Directory, Azure


Active Directory, Office 365

Application using Intranet (11S)

Social Authentication
& Twitter

@ Microsoft Account

Implementing Identity on ASP.NET Core (Templates) &

y NET}
ASE

| To implement ASP.NET Core Identity using Visual Studio Application


template

@ Open Visual Studio

© Select File» New => Project =.NET Core=»ASP.NET Core Web


Application. Click OK

@ Click Change Authentication button. You can choose from the


following authentication options

Change Authentication

( For applications that don't require any user


authentication. )

® No Authentication £2

7) Individual User Accounts

Work or School Accounts

1 Windows Authentication

Change Authentication

Store uses accounts in-app + Leam more

[ Select this option to create a project that includes a local user


accounts store.

No Authentication

Work or School Accounts

8 Individual User Accounts ]


Lean more about third-party open source authentication i.

No Authentication

Windows Authentication

Lesm more about third-party open source suthen

Individual User Account

[ok | Conca |
Page 157
Implementing Identity on ASP.NET Core (Templates) C A $E
1
(Cont'd) spas
Change Authentication x
For applications that authenticate users with Active Directory,
Microsoft Azure
Active Directory, or Office 365.
No Authentication eye
Individual User Accounts Cloud - Single Organization hail i }
— .
Windows Authentication
Directory Access Permissions:
[
= 1 Change Authentication x
Learn more sbout third-party open source aul ©) No Authentication
Learn more
: E
Work and School Accounts © Individual User Acco uts
(Zr Work or School Accounts
indows Authenti n
Learn more about third-party open source authentication options OK |
Cancel |
Windows Authentication
| J NET)

ASP.NET Core External Provider Authentication C

Third-party security middleware option available in


ASP.NET.Security.OAuthproviders integrates with ASP.NET Core Identity
to

allow login using third party authentication services like Google,


Facebook, etc.

service

Microsoft.AspNetCore.Authentication.OpeniDConnect can be used with


Azure Active directory or OpeniDConnect authentication

To implement third party authentication include authentication


middleware before App.UseMVC in Startup.cs file

Microsoft. Owin.Security.Facebook

Microsoft.Owin.Security.Google

Microsoft.Owin.Security.0Auth
Microsoft. Owin. Security. Twitter

Microsoft.Owin. Security

Microsoft. Owin. Security. MicrosoftAccount

Clientld = Configuration ~AzureAD:Clientld”],


Authority = String.Format{Configuration[~A

AadInstance™],
enant™]),

Configuration “AzureAd:
ResponseType = OpenldConnectResponseType.ldToken,

// Configure the OWIN pipeline to use OpenID Connect auth


app .UseOpenldConnectAuthentication(new OpenldConnectOptions
{

PostLogoutRedirectUri = Configuration]
“AzureAd:PostlogoutRedirectlri™]

Page 158
J-NET]
Open Source Authentication Providers CASE

ASOS
AspNet.Security.OpenldConnect.Server low-level /protocol-first OpenID
connect server framework
for ASP.NET Core and OWIN/Katana

IdentityServer4
OpenlD Connect and OAuth 2.0 framework for ASP.NET Core - officially
certified by the OpenID
Foundation and under governance of the .NET Foundation

Openlddict
Easy-to-use OpenlD Connect server for ASP.NET Core

PwdLess

Simple, stateless, passwordless authentication for ASP.NET Core

Enabling ASP.NET Core Identity CASE

y X Enable ASP. Net Identity Authentication

| Microsoft.AspNetCore.ldentity needs to be
included in the project to use the ASP.NET
Core Identity system

ASP.NET Core Identity is enabled using


dependency injection

I To enable authentication middleware, add


UserAuthentication method to the configure

method
A 2 4 Add to Source Control »
Microsoft.AspNetCore. Identity. EntityFrameworkCore Implement Identity
with Entity Framework Core
Microsoft.EntityFrameworkCore.SqlServer Implement Identity to access
relational databases, e.g., SQL Server
Microsoft. EntityFrameworkCore.inMemory Implement in memory database
provider (For testing)
Microsoft. AspNetCore. Authentication.Cookies Implement cookie-based
authentication
Page 159
ASP.NET Core Token-based Authentication

Token-based Authentication

| Is stateless (information about user not stored on the server


[session]

[of

‘Works as centralized service for authenticating multiple


applications (Single sign-on)

altered

‘Works both with Web and mobile applications

[1

Token-based Authentication Implementation

“J User requests access to username / password

| Application provides a signed token to the client

Client stores the token and sends it with each request

I Server verifies token and responds with data

Cryptographically signed by the server. This ensures that it is not

hitps://app.yourwebsite.com
R

Server

Browser

POST/authenticate
Usernames=....&

HTTP 200 OK
{token: “..JWT.."}

GET/api/userdetails
Authorization: Bearer....)WT...

HTTP 200 OK
Name: “userdetails”

Modern Token-based Auth

JWT- JSON Web Token

J .NET]
CASE

8]

(on Core 2.0 supports JSON Web Tokens (JWT) and


is used to authenticate web APIs

JWT tokens are created using Oauth framework


(IdentityServer 4)

JWT is used to transmit user claims to the server as


JSON object

J JWTs structure : JWT contains base64URL encoded


sequence of :

© Header: JSON object having details about the JWT type


and the algorithm used to encrypt the data.

© Payload: JSON object with actual data {User Claim)


shared

© Signature: Used to check the integrity of the data

The header, payload and signature are concatenated by

an J

Sample JWT Token

Header. —
| eyshbGeiOillUz11 NilsInR5cCl61kpXVCI9) eylzd WIOL

tZUBvemd1ciSkaylsimpOaSI6ImMwMTgxMmQ4LTI
3MKtNGIhYS04YWQwLTK1ZTI4YjgzNzeINCIsImhO
dHABLy9zY2hIbWFzLnhtbHNvYXAub3J/nL3dzLzIwM
DUvMDUvaWRIbnRpdHkvY2xhaW1zL25hb WVpZ
VudGlmaWVyljoiZDc2MTRINZEEN2ZMyOS000Tk3ig"
ImODUtNDNkYzImMDI2NzZlliwiZXhwijoxNTExN| or
wNTQ3LCIpc3MiOilodHRwOi8ve W31cmRvbWFpbi
5jb20iLCIhdWQIOHodHRwWOIgve W91cmRvbWFpbi |
3jb20ifQ.v8YLTMTUraD7KqoHTskveg9X_zH5WdW|
cpGuHHeqYKM SiSnatire

Page 160

https://apiyourwebsite.com

Configuring JSON Web Token Authentication C A SE

Configure support for JWT-based


authentication in ASP.NET Core

Implement app.UseAuthentication() in the


Startup.cs file, configureService() method to
include the authentication service

Col 10, 4 Add to Source Control a


y

-—— " " bay


480d to Source Control a Storing issuer, audience and signing key
values in appsettings.json

Creating JWT Authentication CA

| API used to create a JWT token should allow anonymous access to


users

Creating Token based on Client Credentials

4. Add to Scurce Control =

Page 161

Using Jquery to Access JWT C | A SE

| To access JWT using jquery, enable the use of static files in


Startup.cs file

Include the script function in a view


to get the token

am

FocguPasmwordcshiant® 8X Home

4. dd to Source Control »

Configuration in Startup.cs file to


use static files

4 Add to Source Control =

IdentityServer4 Authentication CASE

J ldentityServer4 is an OpenlD Connect and OAuth 2.0 framework for


ASP.NET Core 2

IdentityServerd Features

| Centralize login logic for your applications

4 Issues access tokens for APIs

Gateway to external identity providers like Google, Facebook, etc.

nm
‘a Single sign-on
i.

FE
Customizable

Page 162
Implement ASP.NET Identity with IdentityServer

Step 1

Step 2

Step 3

Step 4

Step 5

Open Visual Studio. Select File » New —> Project = .NET Core
=> ASP.NET Core Web Application and click OK

installing the IdentityServerd.AspNetldentity package

Select Web Application (Model-View-Controller) template option from


the new project window

Click Change Authentication button. Click Individual User Accounts


radio button in Change Authentication window

Modify hosting : To view real-time log output to the console, switch


the launch profile to QuickstartidentityServer

Include IdentityServerd.AspNetldentity NuGet package. IdentityServerd


package gets installed automatically on

Implement ASP.NET Identity with IdentityServer

(Contd)

= Miciwieh Vous Stade


Ee [You Popct fukd Deng Tem Jock Tat dpslar Wiedew Hep
y F-tP| S| 0sbog +H Aay OW <b Wigeenn Gs LM,

§ [—————

Insiatied Upoates

Marty Seer sg Netitantty x Gr [) ich proeiuase

© identityServerd Aspetidentity
Lo PE E—

@ IdentityServer3 AspNetidentity vy frock asm, Domes fai, 12%


dowmiosdt
ASPET erty wapport foe KestyServes]

@ IdentityServee3 AspNetidentity.dil o, boc ian, Soom Egy, FLOK


downoad
ASPET dary suppor for kant Serve) epackaged theary
preset
1 TwentyTwenty ldentityServerd Asphetidentity3 xy 50:05, 149 sowsiosts

Rapier denticy | UherService fox dontityServes)

eventing the addon of volatile source code a the

NuGet Package Manager: IdentityServerWithAspNetidentity

Face sure magetony


(@) identityserver Asphetidentity
Veen Lut tie 200

=) Options.

Desasiption
ASPNET Care cost Integration foe enti Sanverd

TY
Microsoft sphieiC ere denity [+x
erway Servest (+2 20

Page 163
Implement ASP.NET Identity with IdentityServer

| J.NET]
(Cont'd) CASE

| Configure the Scopes and Clients


Step 6
© Disable consent for MVC client

4 Addit Source Control =

Implement ASP.NET Identity with IdentityServer

| yf NET}
(Cont'd) CASE

| Configure IdentityServer
Step 7
© Configure IdentityServer using ConfigureServices and Configure in
Startup.cs file

Configure IdentityServer in Services

Configure IdentityServer in Startup.cs File


vr Ea A

#4 Add to Source Control »

Note : As IdentityServer overwrites some configuration setting in


ASP.NET Identity, IdentityServer should be registered after ASP.NET
Identity in the
Dependency Injection System

Page 164
Implement ASP.NET Identity with IdentityServer | o AT
; CASE
(Cont'd) A Bt:

| Create Database

| To create database

Step 8

& Run command prompt from the project directory

© Execute dotnet efdatabase update -c ApplicationDbContext

Configure Windows Authentication £ A SE

BeLLteteteReesetettiicrLaesateestctete | Configure windows and


anonymous authentication using Visual Studio settings
Go to = Visual Studio Project Properties page
& Select Debug tab. Check the Enable Windows Authentication
checkbox
| Configure the Visual Studio
application template to enable PEE
windows authentication: buss

Build Fuents

WindoveduthSample + X

Package IS Express

@ Open Visual Studio

@ Select File» New = Project =.NET


Core=>»ASP.NET Core Web Application

Browse

Click OK

Click = Change Authentication


button. You can choose from the
windows authentication options

Page 165
| aT
Configure Windows Authentication (Cont'd) CASE

Configure windows and anonymous authentication using


launchSettings.json file
@ Configure the properties in the launchSettings.json file

«)

File
Project B Debug Team
ndow Help

- HEP

#4 Add to Source Control «

Configure Windows Authentication (Cont'd) £ A SE

| Enable Windows authentication with Internet Information Services


(11S) Manager
® ASP.NET Core Module (ANCM)] is responsible for hosting ASP.NET Core
application
® Using ANCM will by default direct windows authentication to 115

# Configuration of windows authentication is done within 11S

Disable Anonymous Authentication and enable Windows


Authentication

| @® Select Authentication menu for the website

5 mene smation Samicas (15) Manager

|
rn ib smiticn Lars (85; Manages
iC Br OPE + Sn» Wedowilathample +

© » 095 + Ste 3 WiedowiAutiSamp 3


Ble Yew Help
Comnection.

| @ Windowsauthsample Home

= Arias
@ Authentication
EF fae Show ih [Group i Grewp by. Ho Grsuping
3 re Tart mn Fasgonte Type ®
@ rhc i) a ~ hotbertesticn Doster
@ Ditwk Web Se 5 | € a i & AMET gancnaicn Doatiet
© WendomcahSample dkbwiicst Fompresion Dusk Ducizey Ines Poge 5
Wrdomsaniamghe A — frases HTTP 1 Chute:
- Gorumert Bowing
ry § 1
J - bis H
HTTP loggng MEME Tige Modules Haine
he 2
2 a] a
@ @ [}
Fr Sse
P, Bim
0 cor
Costu Web :

<

Features View |, Comtert View Fostures Voom Ji Content View


Configuration Totsheal sppbobininl ony , «beta paths
VirdsastothSamgle’s

Page 166

| J NET]
o . 5 . 5
Configure Windows Authentication (Cont'd) C | ASE
T Enable Windows with Http.sys or WeblListener
# Windows authentication is not supported in Kestrel
@ For self-hosted scenarios on windows, implement Http.sys
# Configure the app's web host to use Http.sys with windows
authentication
| 8
4 Add to Source Control +
" . . | y NET]
Windows Authentication C A SE
Q The [Authorize] and [AllowAnonymous] attributes used in the app are
implemented based on configuration
settings of anonymous access

The [Authorize] attribute can grant access to resource, and the


[AllowAnonymous] attribute will allow
access to every one

On enabling windows authentication and disabling anonymous access, the


[Authorize] and
[AllowAnonymous] attributes cannot be used

The [Authorize] and [AllowAnonymous] can be used when both Windows


authentication and anonymous
access are enabled

To implement [Authorize] attribute with windows authentication, some


configuration settings need to be
modified in Startup.cs file

© ©6 0 ©

Page 167
Windows Authentication (Cont'd) C A SE

Using Microsoft.AspNetCore.Server.HttpSys

In WS, include
lisDefaults.AuthenticationScheme
in the ConfigureServices method

Fa—

Startup.cs® # X

* pili

#4 Add to Source Control

Startup.cs® # X bund)
In Hitp.sys, include
HttpSysDefaults. Authentication

Scheme in Ty
the ConfigureServices method

4 Add to Source Control =

Using Microsoft.AspNetCore.Server.lISIntegration

Impersonation C A SE
Q ASP.NET Core does not support impersonation feature
2] All requests are executed with application identity, using app pool
or process identity
w Use Windowsldentity.Runimpersonated to explicitly execute a request
on behalf of a user
(4] Execute a single action in a context and then close the context

Page 168
Impersonation (Cont'd)

| J NET]
CASE

Build

Project

Bros

Debug

AccouniControliercs” 8 Xap

Note: Asynchronous operations cannot be performed when impersonated.


Hence, impersonation should be avoided for complex operations (e.g.
wrapping

entire requests or middleware chains)

4 Add to Source Control =

ASP.NET Core Authorization

| Authorization occurs just before an action


method executes, as part of the MVC file
pipeline in the MvcMiddleware

& Namespace for Authorization:


2 Microsoft. AspNetCore. Authorization
© Attributes

2 Authorize: To allow access to authorized user


for a controller / action
2 AllowAnonymous: To allow access to
anonymous users

A request is made to

tic Fil
the frecipefindex URL Stalls re

Middleware

The authentication :

middleware deserializes the


ClaimsPrincipal from the
encrypted cookie

Authentication
Middleware.

The Authorize filter


runs after routing, but
before model binding
or validation

If authorization is
successful, the action
method executes and
generates a response
as normal

If authorization falls,
the authorize filter
returns an error to
the user and the
action is not
executed

Page 169
ASP.NET Core Authorization (Cont'd) CA SE

Allow Access to Non-authenticated Users Apply Authorization to a


Controller

4 Add ta Source Control «

Apply Authorization to an Action

¥ NET]
ASP.NET Core Role-based Authorization CASE

| ASP.NET Core Identity (ASP.NetCoreldentity) provides RoleManager to


manage roles
| Role-based authorization checks are declarative

Role Authorization at the Controller Level

+] =
EmployeeCentroliercs® & X a

Role Authorization at the Action Level

HecountContioflencs® +X

| [= HESY

1 Add to Source Control ~

Page 170
ASP.NET Core Role Authorization Policy C A SE

| To implement policy-based role checks, register a policy at startup

4 Add to Source Control ~

Register Policy in Configureservices in Startup.cs File

4+ Add to Source Control =

Apply Policy in the Policy Property of the Authorize Attribute

Claim-based Authorization C A S E

J Every identity is assigned one or multiple claims (name/value pair)


issued by a trusted party

J Claims-based authorization grants access to resources based on the


value of a claim

| Claim-based authorization checks are declarative

Register Policy EmployeeOnly to Check the Existence of EmployeeNumber


Claim of Current Identity In
Configureservices in Startup.cs File

Startup.cs® ® X

4 Add to Source Control =

Page 171
Claim-based Authorization (Cont'd) CA SE

Supply the List of Allowed Claims while Creating Policy

Col 10

#4 Add to Source Control =

Apply Policy in the Policy Property of the Authorize Attribute

Custom Policy-based Authorization CASE

1
d & Custom authorization policies fulfill more complex
authorization requirements which are beyond role or claims-based
approach

k d

| |
[2 Custom policy contains one or more requirements

L R— d

r 1
Each requirement can have one or more handlers

. d

Policy : Containing one or

: E i 2
more Requirements Each requirement can

have one or more |

N handlers
|
H — MesbershipHandler ) I

—*| validrimingHandler

| AllowInswismingPoolRequizement

|
DatecfBirthHandler I

MinimumAgeRequirement

Example : Custom Policy to Authorize Access Swimming Pool

Page 172
Custom Policy-based Authorization (Cont'd) C A SE

To Create Custom Palicy for Authorization

© Create a Requirement using an |AuthorizationRequirement


© Create a policy with multiple requirements

& Create AuthorizationHandlers to satisfy the requirements

For a Custom Policy to be Satisfied

& Each requirement defined in the policy should be satisfied

3)

For a Requirement to be Satisfied

>,
& Any of the defined handlers in the policy should be
satisfied

J NET]
Custom Policy-based Authorization (Cont'd) 4 ASE

| For the policy to be satisfied, every requirement must be satisfied

De ; NN Requi nt Requi t
[ str smite = Plas Je | pine

If any of the handlers are satisfied,


the requirement is satisfied

Handler 2A J ox | Handler 2B Jon

Page 173
J NET]
Resource-based Authorization C A SE

Require imperative authorization (call to authorize function within


the code)

Role-Based Authorization is implemented as a service


(lAuthorizationService)

The service is registered in the service collection and available via


dependency injection for controllers to access

CIoE®

Resource-based Authorization (Cont'd) C A SE

IAuthorizationService has two methods:

Method 1 : Takes Resource and Policy Name

Method 2 : Takes Resource and


List of Requirements to Evaluate

EmployeeControlles.

pplic

=H

EmployeeControllercs” & X

Col 31 5 4 Add to Source Control o

Page 174
View-based Authorization C AS E

1 To display, hide or modify content of Views (Ul) based on the


current user identityRole
2 Authorization service within MVC views can be accessed via
dependency injection

@inject directive is used to inject the authorization service into a


Razor view

To include authorization service in every view, include the @inject


directive into the _Viewlmports.cshtml file of
the Views directory

5 Do not implement View-based authorization as sole authorization


method, because hidden Ul element can be
accessed by users

KS Include authorization code in the controller with View-based


authorization

Authentication and Authorization: MVC

Page 175
Authentication and Authorization C

£73
AS

I The server redirects users to login page, when request is made to a


controller or action having authorize attribute
| The authentication filter validates the credentials sent along with
the login request

| On finding the credentials valid, the user is logged in and


redirected to the requested view

MVC Authentication Options

Http Request .
with User Change Authentication 5%
Credentials Controller with
uest (View) Authorize Filter For apphications that stere user profiles
in a SOL Server datobese. Users can register,
fe l cx sign in using their existing account for Facebook, Twitter,
Google, Microsoft, ar
No Authentication Fotis provider.
User pute rate: ®) individual User Accounts
Work And School Accounts
Windows Authentication
Response (View) Auth Filter
[ok | [cance |
ASPNET
Users{Rales
Database

MVC Authentication Filter C

Authentication filter is used to authenticate a user

) Authentication filter is the first filter executed for any request


Authentication filter was introduced in MVC 5. Before this,
authorization filter was used both for authentication and

4 authorization
pi

Creating Custom Authentication Filter

| Inherit lAuthenticationFilter Interface. lAuthenticationFilter


Interface contains OnAuthentication and
OnAuthenticationChallenge methods

Implement OnAuthentication method to authenticate a request


| Implement OnAuthenticationChallenge method which will execute on
failure of authentication and authorization

_| OnAuthenticationChallenge method is called after the action method


is executed and before rendering the requested View

Lt

Page 176
y.NET]
MVC Authentication Filter (Cont'd) CASE

OnAuthentication Method Implementation

[+ I-Q HF 2

| \sehuahentication.cs® 2X

+ Addit Source Control =

OnAuthenticationChallenge Method Implementation

Implementing Single Sign-On C A SE

pm th A

r ,
" 2 ; n , 1 Single Sign-On Login
“I Single sign-on: Login only once and access multiple applications
Once WebApp1
I Implementing Single Sign-On by sharing forms authentication cookies
across web Applications WebApp2
| To use a common authentication ticket
WebApp3
@ Use machine level Web.config file and generate manually the
validationKey and decryptionKey values present in the
<machineKey>
element Webippa
8 Share the generated validationKey and decryptionKey across web
L applications to support Single sign-on : wehaves

Generating validationkey and decryptionKey Manually

2 Add to Source Control =


Page 177
Authentication using Third-party Identity Provider ~ ( | A SE

J A website implementing OpenlD authentication enables users, having


account with identity providers
e.g., Google, Facebook, Yahoo! etc., to login to the website using
their third-party identity provider
credentials

Login Process for a Web Application Implementing OpenID Protocol

Browser redirects the user to the respective OpenID provider (like


Google or Facebook)

User logs in using the username and password of the OpenID provider
User permits the website to use his identity

User is redirected back to the website

Q Login page implementing OpenID is displayed


=] 4
Q

Implement Page Access Control with Standard

CASE
Action Filters |

| Authorization filters check if a user has access to execute a


controller's actions based on hard-coded roles and users
in the application

| These filters implement lAuthorizationFilter interface that defines


the methods required for an authorization

Authorize Attribute on a Particular Action for a User John

Debug

HomeController.cs® + X

Employee

4 Adds Source Control «

Page 178
Authentication and Authorization Defensive Techniques: Web Forms

Secure Form Authentication Tickets g ASE

J The integrity and encryption of authentication tickets can be


maintained by setting protection="All" in
Machine.config
| If the protection attribute is set to None, the authentication
ticket will be in clear text format which is prone to integrity
attacks
Ensure that the protection attribute is set to "All"
in both Machine.config and Web.config

Vulnerable Code Secure Code

Build

B-wEE = . bow EE

Web.config” # X 4 Web.conhig? # X

© By setting “None,” the integrity of the authentication ticket may be


loss © By setting "All it ensures the integrity of the
authentication ticket
EEE ————————— — — — —

Page 179
| y NET]
Use Strong Hashing Algorithms to Validate Data C ASE

| Use strong hashing algorithm such as HMACSHA-256, 384 or 512 instead


of MDS or SHA1 in the validation
attribute of <machineKey> settings to enhance the level
of security

Vulnerable Code Secure Code

Pl = 8

Team Signin

oD .

Web.config® ® X Hom

4 Publish =

© MDS is a weak algorithm for hashing that creates small size hash
value # SHAL is a strong algorithm for hashing that creates large size
hash value

Use Strong Encryption Algorithm to Secure Form

CASE
Authentication Data - A = E

| Use AES encryption algorithm instead of DES or 3DES in the


decryption attribute of the <machineKey> settings to
enhance the level of security

Vulnerable Code Secure Code


Help

(<]

Web.config® = Xx

A Publish
@ DES is a weak encryption algorithm that creates small size key value
© AES is a strong encryption algorithm that creates large size key
value

Page 180
| J NET]
Secure Form Authentication Cookies using SSL C ASE

J SSL can be used to protect authentication cookies over the network


from being captured or tampered by the attacker

J In order to secure authentication cookies using SSL, the requireSSL


attribute of Form authentication should be made
true in the Web.config file

J Ifitis false, authentication cookies will not be secured anymore and


can be captured or tampered by the attacker

Vulnerable Code Secure Code

Tow 7 t-te

Web config” © Home.aspr.cs® . Web.config” & X

. When it is False, cookie may get captured or tampered & When


it is True, cookie is secured from getting captured or tampered
a .
Secure Form Authentication Credentials C ASE

J The hash algorithm SHAL should be used to create a hash value of


password in the passwordFozrmat attribute of
<credentials> under the form authentication tag

| This will secure passwords from being stolen by the attacker

| If passwordFormat is set to clear, then the password will appear in


the text format that can easily be stolen

Vulnerable Code Secure Code

Oe E

Webiconig* ® XH

| BRE)
L

1 Publish «

© When it is SHA, the password will appear in hashed format

& When it is clear, the password will appear in clear text


format

Page 181
Prevent Session Hijacking using Cookieless
Authentication
| J NET]
CASE

| An attacker may steal the session or authentication token appended


with the requested URL by using a network
monitoring tool, which is used to impersonate a legitimate user,
thereby breaching application's security

| Use cookies instead of a URL to store session or authentication


tokens so as to prevent session hijacking attacks

Vulnerable Code Secure Code

File Edt
Team

Help
O-a EF X

Web.config” & X H Web.config® # X Home.

4 Publish ~ 4 Publish ~

© Attacker may exploit session information when the URL is used to


maintain @ The session information should be maintained by using a
cookie to secure it
session

Avoid Form Authentication Cookie Persistance

| J NET]
using DisplayRememberMe Property < A 5 E

| Persistent authentication cookies store user credentials in the


user's profile on the computer; an attacker with physical
access to the user's computer can steal these credentials

Set the DisplayRememberMe property of the login control to false to


avoid the cookies persistence

Vulnerable Code Secure Code

@ When it is true, it persists the form authentication cookie @ When


it is false, the form authentication cookie do not persist
I ——

Page 182
Avoid Form Authentication Cookie Persistence
while using RedirectFromLoginPage Method ote 2

| The form authentication cookies can also be prevented from


persisting without using the logging control

_| This can be done by using the RedirectFromLoginPage method of the


FormsAuthentication class

Vulnerable Code
Secure Code

Child

Second parameter of RedirectFromLoginPage method should not be made


true to avoid persisting cookies =

Avoid Form Authentication Cookie Persistence

I NET]
while using SetAuthCookie Method CA SE

| Form authentication cookies can also be prevented from persisting


with the help of the SetAuthCoockie
method of the FormsAuthentication class

Vulnerable Code

Secure Code

4 Publish «

4 Publish ~

Second parameter of SethuthCockie methed should not be made trueto


<-
avoid persisting cookies

Page 183
Avoid Form Authentication Cookie Persistence C A §E
while using GetRedirectUrl Method eit re So

| Form authentication cookies can also be prevented from persisting


with the help of the GetRedirectUrl method
of the FormsAuthentication class

Vulnerable Code

Home aspres™ 8X
*

Secure Code

Second parameter of
GatRedirectUrl method should not «----
be made true to avoid persisting cookies

#4 Publish ~

Col 75

Avoid Form Authentication Cookie Persistence while using C | A SE


FormsAuthenticationTicket Constructor Rill loft

| The form authentication cookies can also be prevented from


persisting by passing false to FormsAuthenticationTicket constructor
| The syntax of the constructor is:
public FormsAuthenticationTicket (string name, bool isPersistent, int
timeout)

Vulnerable Code

# Ifitis true in the FormsAuthenticationTicket constructor, the


cookies will persist

Page 184
Avoid Form Authentication Cookie Persistence while using C A SE
FormsAuthenticationTicket Constructor (Cont'd) h rls

Secure Code

File Edit Project Build Debug Team Tools Test

Th, 9. gle Chrome -


Home.asprcs® #8 X
Click{object sender, EventArgs €)

Login_Click(

p.ValidateUser(txtusername

ctusernam

Col 14

A Publish «

@ Ifitis false in the FormsAuthenticationTicket constructor, the


cookies will not persist

| AT
Secure Passwords with minRequiredPasswordLength C | ASE

The default membership setting values for MinRequiredPasswordLength


property need to be changed in the Web.config file
The default setting allows a lower number of password characters,
which makes it easy for an attacker to guess and crack the password

The minRequiredPasswordLength attribute in the Web.config file should


be set to the largest values to form unbreakable and strong
passwords

Vulnerable Code Secure Code

Weticonfig® ® X

@ tis the default value and does not ensures a secure passward
& Itshould be set to a proper value to ensure security of
password

Page 185
Secure Passwords with
| am
minRequiredNonalphanumericCharacters ¢ AS

| As a default setting and may not allow alphanumeric characters in


the password, it is recommended that the default membership
setting values for minRequiredionalphanumericCharacters properties are
changed in the Web. config file

I Such settings may build weak passwords that can be easily breakable
| Itis recommended that strong passwords with alphanumeric characters
are build so that it can provide a proper value to

minRequiredNonalphanumericCharactexrs properties

Vulnerable Code Secure Code

o D-Q EF

Webiconkig® © % Wisbconhg™ % %

# It is the default value and does not ensures secure password @ It


should be set to a proper value to form unbreakable passwords

Secure Passwords with


passwordStrengthRegularExpression

| Am
CASE

| The passwordStrengthRegularExpression property of the membership


provider helps to build strong passwords by setting
proper regular expression for passwords

| By default, it is not set. This in turn makes it vulnerable for


breaking passwords
| Ifitis set to a proper regular expression, the password can be
protected from being broken

Vulnerable Code Secure Code

| nas Col 18

By default nothing is set © Regular expression for password

https://www.ocpsoft.org/tutorials/regular-expressions/password-
regular-expression/

Page 186
Restrict Number of Failed Logon Attempts CASE

| To prevent users from repeated login attempts with wrong passwords,


the number of failed login attempts should be set to the
minimum level

| This will lock out the account after exceeding failed logon attempts
“J This can be set by using the maxInvalidPasswordAttempts and
passwordAttemptWindow properties of the membership
provider (in the Web.config file)

Vulnerable Code Secure Code

Webconfig® & X

# This large value will give the attacker more chances to try attacks
® This values should be as small as possible to minimize the
attacker's attempts

Secure Application by using Absolute URLs for


Navigation

| Whenever the code redirects to the secure page from the page that is
in the public area, such as aLogin page of the
application, it should use the absolute path of the secure page for
redirecting it, rather than the relative path

I The relative path may give direct access to the restricted area of
the application

| The absolute path looks like http: //servername/appname/login. aspx,


where the relative path as /login.aspx

Secure Code

Debug Team Test

Debug

# Redirecting using relative path €-

A Publish =

© Redirecting using absolute path Gerrrrnanan


EE

Page 187
Secure Applications from Authorization Bypass

| y NET]
Attacks C A Ss E

J The authorization bypass is a severe vulnerability that exists in


the application when the Server . Transfer ()
method is used to redirect to the page that requires specific
authorization privileges

J This vulnerability can be exploited by attackers to gain access to


the secure areas, such as the administration
functionality of the application

| To secure the application from such authorization bypass attacks, Ht


tpResponse . Redirect ()
should be used instead of the Server. Transfer () method for
redirecting to the page that requires specific
authorization privileges

Secure Applications from Authorization Bypass |


Attacks (Cont'd) fd dol Rr

Vulnerable Code Secure Code

¥
& This method should not be used whenever page is need to
redirect to secure page ® This method should be used whenever page is
need to redirect to secure page

ServerTransfer Response.Redirect

Request

Page 188
Create Separate Folder for Secure Pages in

CASE
Application CASE

The application should be partitioned into subfolders to create a more


secure application

The pages in the application that requires specific authentication,


authorization, and SSL should be placed in a separate subfolder under
the virtual root
directory of the application

The pages in the public area that do not require authentication,


authorization, and SSL should be placed in another folder underneath
the virtual directory
root folder

Configure it accordingly in the Web.config file

Vulnerable Code

& The webapp folder, which is a virtual directory root folder,


contains public area pages as well as secured pages

© They all need to be secured with authentication, authorization, and


550

Create Separate Folder for Secure Pages in | o AT


Application (Cont'd) A fo

Secure Code Secure Code

Web.config® + X 5 . Web.config® + X

@ The Nonsecuredapagesfolder contains general pages that do not


require @ The Securedapagesfolder is for authenticated and SSL access
only
authentication, authorization, $5L, etc.
Page 189
using Regular Expressions

Validate Passwords on CreateUserWizard Control

| Regular Expressions are used to validate the


password entered through the CreateUserWizard
control

| The PasswordRegularExpression property of the


CreateUserWizard control is used to set valid
regular expressions for passwords

| Whenever the password is entered through the


CreateUserWizard control, it validates against the
supplied regular expression

| Regular expressions thus secure the


authentication mechanism by enforcing password
complexity

Conform Password:

Email:

Security Question:

Security Answer:

Validate Passwords on CreateUserWizard Control


using Regular Expressions (Cont'd)

| J NET]
CASE

Vulnerable Code

Registerasp® ® X

© Regular expression is not supplied

Secure Code

4 Publish «

© Regular expression is supplied

Page 190
| J-NET]
CASE

Authentication and Authorization Defensive Techniques: ASP.NET Core

Configure Identity Services: Password Policy

NET)
CASE
Property
RequireDigit
RequiredLength

RequireNonAlphanumeric

RequireUppercase

RequireLowercase

ReguiredUniqueChars

Configure IdentityOptions in the Startup.cs file to alter the default


settings of the identity

Password Policy — IdentityOptions Properties


Purpose
Password must contain a numeric character
Minimum password length
Password must contain a nonalphanumeric character

Password must contain a upper case character

Password must contain a lower case character

Password must contain distinct characters

To configure Identity Services, add middleware in the


ConfigureServices Method of the applications Startup.cs file

Default

Page 191
Configure Identity Services: Password Policy
(Cont'd)

Example : Password Policy Configuration

ject

EF

Debug Team

bP] Debug

JJ Ready Ln33 + Add to Source Control =

Configure Identity Services: User Lockout

| J NET]
CASE

AllowedForNewlUsers Boolean value to indicate if a new user should be


locked out

Example : UserLockout Configuration


4 Add to Source Control

UserLockout- IdentityOptions Properties

Property Purpose Default


DefaultLockoutTimeSpan Lockout duration (in min) S mins
MaxFailedAccessAttempts Number of access attempts before locking a
user 5

Page 192
J NET]
> E

Configure Identity Services: Sign in CA S

Signin— IdentityOptions Properties

Property Purpose Default


RequireConfirmedEmail Need confirmed email id to signin False
ReguireConfirmedPhoneNumber Need confirmed mobile number to signin
False

Example : UserLockout Configuration

4 Add to Source Control =

| J NET]
Configure Identity User Validation Settings CASE

User— IdentityOptions Properties

Property Purpose Default

ReguireUniqueEmail Boolean flag for mandatory unique email False

AllowedUserNameCharacters Defines the valid characters for username


abedefghijkimnopgrstuvwxyzABCDEFGHUKLMNOPORSTUVWXYZ20123
456789. @+.

4 Add to Source Control a

Page 193
Configure Application's Cookie Settings C A SE

| A user cookie should expire after a specified time by default

CookieAuthentication Options

Property Purpose Default


Cookie.Name Define a cookie with a name AspNetCore.Cookies
Cookie. HttpOnly Boelean to determine if the cookie is accessible from
client script True
ExpireTimeSpan Define the time for which the authentication ticket is
stored 14 days
LoginPath URL to redirect for login by unauthorized users
JAccount/Login
LogoutPath URL to redirect on logout JAccount/Logout
AccessDeniedPath URL to redirect when user fails to login
JAccount/AccessDenied

Define if a new cookie is issued with extended expiration time when a

| fi fieh + Tr
cookie completes its half expiration time cid

slidingExpiration

Define the query string parameter name to be appended by the

ReturnUriParameter +
middleware on altering 401 status code to a 302

| J NET]
Configure Identity Services: Cookie Settings C ASE

Example : Cookie Settings

File Edit Debug Team

Debug

*y

Cal 16 #4 Add to Source Control =

Page 194
Enforce SSL € A

Https encrypts the data while transferring it from client to server


and prevents it from being modified by Man-in-the-Middle attack
Controllers or methods which require to implement Https can be
decorated with [Requirefttps] attribute

I To implement HTTPS include Microsoft. AspNetCore.Mvc Package


To configure HTTPS globally include RequireHttpsAttribute in
ConfigureServices in Startup.cs file

Configuring Https Globally Action with RequireHttps Attribute

4 Add to Source Control =

A Add to Source Control a

Code to Redirect a Http Request to Hitps

HTTP Strict Transport Security (HSTS) CAS

While redirecting HTTP request to HTTPS, the request is vulnerable to


Man-in-the-Middle attack prior to the
redirection
" HTTP Strict Transport Security (HSTS) includes a Strict-
Transport-Security header, which ensures that the browser always
(2) uses HTTPS when requesting resources from the said domain

To prevent the very first request, submit the domain in the HSTS
Preload List of the browser

Example : Strict-Transport-Security Header

Strict-Transport-Security: max-age=31536000; includeSubDomains;


preload

Page 195
Authentication and Authorization Defensive Techniques: MVC

Implement AllowXRequestsEveryXSecondsAttribute to |

Prevent Brute Force Attack for

Brute force attacks can be protected by restricting user action after


a specified number of attempts or duration

EE : ~
Implementing AllowXRequestsEveryXSecondsAttribute restricts the user
from using the action after repeating a action for
a specified time within a specified duration

Page 196
MVC Page Access Control: Custom Security Filter A SE

J Custom Security Filter are used to implement custom security rules


like IP restricted access

Creating Custom Security Filter

Custom action filters is a simple class derived from the


System.Web.MVC.FilterAttribute

| To implement custom security filter on the action

@ Add the filter to an individual controller

1
1
1
1
1
1
1
1
1
1
1
1
1
i
i © Add the filter to an individual action
1
1
1
1
1
1
1
1
1
i © Implement the filter globally
1
1
1
1

MVC Page Access Control: Custom Security Filter | A=


(Cont'd) ps

Creating Custom Security Filter

{3

Securities” 2X
Ay My

4 Add to Seurce Contig +

4 Add te Source Control +

Setting the Custom Security Filter Globally

Page 197
| NET]
Page Access Control: Third-party Libraries CASE

| To implement page access security, the existing third-party


libraries can be implemented
I Implement FluentSecurity library

@ Set page access rules to individual controllers/action

Example

Implement Control-level Protection CASE

_I Implementing control-level
protection in the views
enables a user to display a

particular section on the page

+ Add to Source Control =

Page 198
Implement Control-level Protection (Cont'd) C A SE
| | Implementing control-level protection using security filters will
decide if controller action should display results based on
accessibility |

Example: Filter using


lActionFilter called

before and after each


action method call

4 Add to Source Contiol ~

Example: Filter ~~ ~~~ ~~~


implements IResul

tFilter OnResultEx

ecuting method

Colds 4 Add to Seusce Control ~

J NET]
Implement Account Lockout C ASE

J Implement ASP.NET Identity 2.0 account lockout feature to deny


access to a user account after specified
unsuccessful login attempts

To Implement Account Lockout Feature

Open ApplicationUserManager.cs file and modify the


DefaultAccountLockoutTimeSpan and MaxFiledAccessAttemptBeforeLockout
properties

Add the following code on the passwordSignin action to implement


account lockout

public async Task PasswordSignIn(stringuserName, string password, bool


isPersistent, bool shouldLockout) {

var user = await UserManager.FindByNameAsync (userName);

await UserManager.IsLockedOutAsync (user.Id);

await UserManager.AccessFailedAsync(user.Id);

await UserManager.SetLockoutEnabledAsync(user.Id, true);

Page 199
Implement Account Lockout (Cont'd) C A SE

Vulnerable Code

Secure Code

Ché 1 Publish =

@ Setting higher Defaul tAccountLockoutTimeSpan and


MaxFailedAccessAttemptsBeforeLockout gives attacker more time and
attempts to perform
brute force attack

HTTPS automatically encrypts the data while


transporting from client to server, and hence,
HTTPS is more secure than HTTP requests

Implementing [RequireHttps] attribute on actions


ensures a HTTP request is redirected to HTTPS

Ensure HTTPS is configured on 11S while


implementing [RequireHttps] (By default -Disabled)

L E Cat 28 5 + Add to Source Control =

OT

Globalasaxcs® @ X

4 Add to Source Control =

Page 200
Implement AllowAnonymous Action Filter CA SE

The [AllowAnonymous] attribute allows anonymous access to controllers


/actions

Use the Global Filters in the FilterConfig class in the App_Start


folder to apply the authorize attribute
to every action method

Selectively allow access to actions that do not require authentication


by implementing
[AllowAnonymous] attribute

AllowAnonymous action filter was introduced in MVC 4

Note:
# Do not implement security using route constraint
# Security decisions should be done at the controller level

J NET]
Implement AllowAnonymous Action Filter (Cont'd) CA SE

Implementing Authorize Attribute Globally

' FilterConfig.cs™ & X

4 Add to Source Control =


5 : ityFilter.c AccountController.cs® ® X

Registen()

b
1 Add to Source Control

Decorating Actions with [Allowanonymous)] Attribute to allow Anonymous


Access

Page 201
Module Summary C A

| Authentication is the process of verifying a user's


identity with an application on the basis of verification of
some sort of credentials

J Authorization is a process of giving an authenticated user the


specific rights to access a particular resource
| Authorization is always performed after authentication

J Each of these processes is performed at different levels of the .NET


web application security architectures,
i.e. ASP.NET, Enterprise Services, SQL server level

_| Delegation is a more powerful form of impersonation where ASP.NET


can access the resources located on a
remote server

Back to Contents

Page 202

You might also like