SlideShare a Scribd company logo
1 of 5
Download to read offline
Authorization In Asp.Net
Part IV
Resource Based Authorization
Today we will be discussing resource based authorization.
Often authorization is based upon the accessed resource . E.g. a document might have an author
property. So only the author would be allowed to update it; the resource must be loaded from the
document repository before an authorization access can be made. This can't be done with an Authorize
attribute, as feature evaluation takes place before data binding and before the code to load a resource
runs inside an action. Instead of the declarative authorization, the attribute method, we must use
impervious authorization, where a developer calls upon an authorize function within his own code.
Authorizing within a code
Authorization is executed as a service, IAuthorizationService, registered in the service collection and
available via dependency injection for Controllers to approach.
public class DocumentController : Controller
{
IAuthorizationService _authorizationService;
public DocumentController(IAuthorizationService authorizationService)
{
_authorizationService = authorizationService;
}
}
IAuthorizationService has 2 methods: in one, you pass the resource and the policy name and in the
other, you pass the resource and a list of requirements to assess.
Task<bool> AuthorizeAsync(ClaimsPrincipal user,
object resource,
IEnumerable<IAuthorizationRequirement> requirements);
Task<bool> AuthorizeAsync(ClaimsPrincipal user,
object resource,
string policyName);
To call upon the service load resource within action then call the AuthorizeAsync overload you
require. e.g.
public async Task<IActionResult> Edit(Guid documentId)
{
Document document = documentRepository.Find(documentId);
if (document == null)
{
return new HttpNotFoundResult();
}
if (await authorizationService.AuthorizeAsync(User, document, "EditPolicy"))
{
return View(document);
}
else
{
return new ChallengeResult();
}
}
Writing a resource based handler
Now to write a handler for resource based authorization is not very much different to write a plain
requirements handler. You create a requirement, and then execute a handler for the requirement, then
specify the requirement as before and also the resource type.
Therefore, a handler which might accept a Document resource would look as below:
public class DocumentAuthorizationHandler : AuthorizationHandler<MyRequirement, Document>
{
public override Task HandleRequirementAsync(AuthorizationHandlerContext context,
MyRequirement requirement,
Document resource)
{
// Ratify the requirement against the resource and identity.
return Task.CompletedTask;
}
}
Don’t forget you also need to list your handler in the ConfigureServices method;
services.AddSingleton<IAuthorizationHandler, DocumentAuthorizationHandler>();
Requirements
If you want to make decisions based on operations such as read, write, update and delete, you can use
the OperationAuthorizationRequirement in the Microsoft.AspNetCore.Authorization.Infrastructure
namespace. This previously built requirement class helps you to write a single handler which has a set
parameterized operation name, rather than develop individual classes for each operation. To utilize it
provide some operation names:
public static class Operations
{
public static OperationAuthorizationRequirement Create =
new OperationAuthorizationRequirement { Name = "Create" };
public static OperationAuthorizationRequirement Read =
new OperationAuthorizationRequirement { Name = "Read" };
public static OperationAuthorizationRequirement Update =
new OperationAuthorizationRequirement { Name = "Update" };
public static OperationAuthorizationRequirement Delete =
new OperationAuthorizationRequirement { Name = "Delete" };
}
Your handler could then be executed as follows, using a hypothetical Document class as the resource;
public class DocumentAuthorizationHandler :
AuthorizationHandler<OperationAuthorizationRequirement, Document>
{
public override Task HandleRequirementAsync(AuthorizationHandlerContext
OperationAuthorizationRequirement ,
Document resource)
{
// Validate the operation using the resource, the identity and
// the Name property value from the requirement.
return Task.CompletedTask;
}
}
You can view the handler works upon OperationAuthorizationRequirement. The code inside the
handler must take the Name property of the supplied need into account when making its evaluations.
To call an operational resource handler you are required to specify the operation when calling
AuthorizeAsync in your action. For example
if (await authorizationService.AuthorizeAsync(User, document, Operations.Read))
{
return View(document);
}
else
{
return new ChallengeResult();
}
This example checks if the user is able to perform the read function for the current document. If
authorization succeeds the view for the document will be returned.
If you want to learn ASP.Net and perfect yourself in .NET training, our CRB Tech Solutions would be
of great support for you. Join us with our updated program in ASP.Net course.
Stay connected to CRB Tech reviews for more technical optimization and other resources.

More Related Content

Viewers also liked (17)

Photos for shoot
Photos for shootPhotos for shoot
Photos for shoot
 
CONTABILIDAD
CONTABILIDADCONTABILIDAD
CONTABILIDAD
 
KLima
KLima KLima
KLima
 
El sistema excretor
El sistema excretorEl sistema excretor
El sistema excretor
 
Updated research
Updated researchUpdated research
Updated research
 
Authorization iii
Authorization iiiAuthorization iii
Authorization iii
 
Research
ResearchResearch
Research
 
Mastering Your Destiny
Mastering Your DestinyMastering Your Destiny
Mastering Your Destiny
 
Salario (Art. 123 hasta 140 LOTTT)
Salario (Art. 123 hasta 140 LOTTT)Salario (Art. 123 hasta 140 LOTTT)
Salario (Art. 123 hasta 140 LOTTT)
 
PLANTS AND ARSENICALS AS THERAPEUTIC AGENTS
PLANTS AND ARSENICALS AS THERAPEUTIC AGENTSPLANTS AND ARSENICALS AS THERAPEUTIC AGENTS
PLANTS AND ARSENICALS AS THERAPEUTIC AGENTS
 
Калькулятор ремонта
Калькулятор ремонтаКалькулятор ремонта
Калькулятор ремонта
 
Radme ru_leroy_merlin
Radme ru_leroy_merlinRadme ru_leroy_merlin
Radme ru_leroy_merlin
 
Emails
EmailsEmails
Emails
 
China
ChinaChina
China
 
Prateek
PrateekPrateek
Prateek
 
Cricket
CricketCricket
Cricket
 
Semana Santa
Semana Santa Semana Santa
Semana Santa
 

Similar to Authorization p iv

Leveraging Azure Search in Your Application
Leveraging Azure Search in Your ApplicationLeveraging Azure Search in Your Application
Leveraging Azure Search in Your ApplicationJeremy Hutchinson
 
Introduction to the SharePoint Client Object Model and REST API
Introduction to the SharePoint Client Object Model and REST APIIntroduction to the SharePoint Client Object Model and REST API
Introduction to the SharePoint Client Object Model and REST APIRob Windsor
 
(4) OAuth 2.0 Obtaining Authorization
(4) OAuth 2.0 Obtaining Authorization(4) OAuth 2.0 Obtaining Authorization
(4) OAuth 2.0 Obtaining Authorizationanikristo
 
How Netflix Is Solving Authorization Across Their Cloud
How Netflix Is Solving Authorization Across Their CloudHow Netflix Is Solving Authorization Across Their Cloud
How Netflix Is Solving Authorization Across Their CloudTorin Sandall
 
Implementing access control with zend framework
Implementing access control with zend frameworkImplementing access control with zend framework
Implementing access control with zend frameworkGeorge Mihailov
 
How To Manage API Request with AXIOS on a React Native App
How To Manage API Request with AXIOS on a React Native AppHow To Manage API Request with AXIOS on a React Native App
How To Manage API Request with AXIOS on a React Native AppAndolasoft Inc
 
The OAuth 2.0 Authorization Framework
The OAuth 2.0 Authorization FrameworkThe OAuth 2.0 Authorization Framework
The OAuth 2.0 Authorization FrameworkSamuele Cozzi
 
Authorization in asp dot net part 2
Authorization in asp dot net part 2Authorization in asp dot net part 2
Authorization in asp dot net part 2sonia merchant
 
.NET Core, ASP.NET Core Course, Session 19
 .NET Core, ASP.NET Core Course, Session 19 .NET Core, ASP.NET Core Course, Session 19
.NET Core, ASP.NET Core Course, Session 19aminmesbahi
 
Lyudmila Zharova: Developing Solutions for SharePoint 2010 Using the Client O...
Lyudmila Zharova: Developing Solutions for SharePoint 2010 Using the Client O...Lyudmila Zharova: Developing Solutions for SharePoint 2010 Using the Client O...
Lyudmila Zharova: Developing Solutions for SharePoint 2010 Using the Client O...SharePoint Saturday NY
 
Ppt on web development and this has all details
Ppt on web development and this has all detailsPpt on web development and this has all details
Ppt on web development and this has all detailsgogijoshiajmer
 
Introduction to PicketLink
Introduction to PicketLinkIntroduction to PicketLink
Introduction to PicketLinkJBUG London
 
Understanding and testing restful web services
Understanding and testing restful web servicesUnderstanding and testing restful web services
Understanding and testing restful web servicesmwinteringham
 
Cloudbase.io MoSync Reload Course
Cloudbase.io MoSync Reload CourseCloudbase.io MoSync Reload Course
Cloudbase.io MoSync Reload Coursecloudbase.io
 

Similar to Authorization p iv (20)

Understanding AJAX
Understanding AJAXUnderstanding AJAX
Understanding AJAX
 
Leveraging Azure Search in Your Application
Leveraging Azure Search in Your ApplicationLeveraging Azure Search in Your Application
Leveraging Azure Search in Your Application
 
Introduction to the SharePoint Client Object Model and REST API
Introduction to the SharePoint Client Object Model and REST APIIntroduction to the SharePoint Client Object Model and REST API
Introduction to the SharePoint Client Object Model and REST API
 
(4) OAuth 2.0 Obtaining Authorization
(4) OAuth 2.0 Obtaining Authorization(4) OAuth 2.0 Obtaining Authorization
(4) OAuth 2.0 Obtaining Authorization
 
How Netflix Is Solving Authorization Across Their Cloud
How Netflix Is Solving Authorization Across Their CloudHow Netflix Is Solving Authorization Across Their Cloud
How Netflix Is Solving Authorization Across Their Cloud
 
Implementing access control with zend framework
Implementing access control with zend frameworkImplementing access control with zend framework
Implementing access control with zend framework
 
How To Manage API Request with AXIOS on a React Native App
How To Manage API Request with AXIOS on a React Native AppHow To Manage API Request with AXIOS on a React Native App
How To Manage API Request with AXIOS on a React Native App
 
The OAuth 2.0 Authorization Framework
The OAuth 2.0 Authorization FrameworkThe OAuth 2.0 Authorization Framework
The OAuth 2.0 Authorization Framework
 
Authorization in asp dot net part 2
Authorization in asp dot net part 2Authorization in asp dot net part 2
Authorization in asp dot net part 2
 
.NET Core, ASP.NET Core Course, Session 19
 .NET Core, ASP.NET Core Course, Session 19 .NET Core, ASP.NET Core Course, Session 19
.NET Core, ASP.NET Core Course, Session 19
 
Routes Controllers
Routes ControllersRoutes Controllers
Routes Controllers
 
Lyudmila Zharova: Developing Solutions for SharePoint 2010 Using the Client O...
Lyudmila Zharova: Developing Solutions for SharePoint 2010 Using the Client O...Lyudmila Zharova: Developing Solutions for SharePoint 2010 Using the Client O...
Lyudmila Zharova: Developing Solutions for SharePoint 2010 Using the Client O...
 
Ppt on web development and this has all details
Ppt on web development and this has all detailsPpt on web development and this has all details
Ppt on web development and this has all details
 
Ajax
AjaxAjax
Ajax
 
Introduction to PicketLink
Introduction to PicketLinkIntroduction to PicketLink
Introduction to PicketLink
 
Understanding and testing restful web services
Understanding and testing restful web servicesUnderstanding and testing restful web services
Understanding and testing restful web services
 
Cloudbase.io MoSync Reload Course
Cloudbase.io MoSync Reload CourseCloudbase.io MoSync Reload Course
Cloudbase.io MoSync Reload Course
 
AJAX
AJAXAJAX
AJAX
 
AJAX
AJAXAJAX
AJAX
 
Tutorial asp.net
Tutorial  asp.netTutorial  asp.net
Tutorial asp.net
 

More from sonia merchant

What does dot net hold for 2016?
What does dot net hold for 2016?What does dot net hold for 2016?
What does dot net hold for 2016?sonia merchant
 
What does .net hold for 2016?
What does .net hold for 2016?What does .net hold for 2016?
What does .net hold for 2016?sonia merchant
 
Data protection api's in asp dot net
Data protection api's in asp dot netData protection api's in asp dot net
Data protection api's in asp dot netsonia merchant
 
Asp dot-net core problems and fixes
Asp dot-net core problems and fixes Asp dot-net core problems and fixes
Asp dot-net core problems and fixes sonia merchant
 
Search page-with-elasticsearch-and-dot-net
Search page-with-elasticsearch-and-dot-netSearch page-with-elasticsearch-and-dot-net
Search page-with-elasticsearch-and-dot-netsonia merchant
 
Build a-search-page-with-elastic search-and-dot-net
Build a-search-page-with-elastic search-and-dot-netBuild a-search-page-with-elastic search-and-dot-net
Build a-search-page-with-elastic search-and-dot-netsonia merchant
 
How to optimize asp dot-net application
How to optimize asp dot-net applicationHow to optimize asp dot-net application
How to optimize asp dot-net applicationsonia merchant
 
How to optimize asp dot net application ?
How to optimize asp dot net application ?How to optimize asp dot net application ?
How to optimize asp dot net application ?sonia merchant
 
Learn dot net attributes
Learn dot net attributesLearn dot net attributes
Learn dot net attributessonia merchant
 
Learn about dot net attributes
Learn about dot net attributesLearn about dot net attributes
Learn about dot net attributessonia merchant
 
Owin and-katana-overview
Owin and-katana-overviewOwin and-katana-overview
Owin and-katana-overviewsonia merchant
 
Top 15-asp-dot-net-interview-questions-and-answers
Top 15-asp-dot-net-interview-questions-and-answersTop 15-asp-dot-net-interview-questions-and-answers
Top 15-asp-dot-net-interview-questions-and-answerssonia merchant
 
Next generation asp.net v next
Next generation asp.net v nextNext generation asp.net v next
Next generation asp.net v nextsonia merchant
 
Dot net universal apps
Dot net universal appsDot net universal apps
Dot net universal appssonia merchant
 
Browser frame building with c# and vb dot net
Browser frame building  with c# and vb dot netBrowser frame building  with c# and vb dot net
Browser frame building with c# and vb dot netsonia merchant
 
A simplest-way-to-reconstruct-.net-framework
A simplest-way-to-reconstruct-.net-frameworkA simplest-way-to-reconstruct-.net-framework
A simplest-way-to-reconstruct-.net-frameworksonia merchant
 
Silverlight versions-features
Silverlight versions-featuresSilverlight versions-features
Silverlight versions-featuressonia merchant
 
History of silverlight versions and its features
History of silverlight versions and its featuresHistory of silverlight versions and its features
History of silverlight versions and its featuressonia merchant
 
What is microsoft silverlight?
What is microsoft silverlight?What is microsoft silverlight?
What is microsoft silverlight?sonia merchant
 

More from sonia merchant (20)

What does dot net hold for 2016?
What does dot net hold for 2016?What does dot net hold for 2016?
What does dot net hold for 2016?
 
What does .net hold for 2016?
What does .net hold for 2016?What does .net hold for 2016?
What does .net hold for 2016?
 
Data protection api's in asp dot net
Data protection api's in asp dot netData protection api's in asp dot net
Data protection api's in asp dot net
 
Asp dot-net core problems and fixes
Asp dot-net core problems and fixes Asp dot-net core problems and fixes
Asp dot-net core problems and fixes
 
Search page-with-elasticsearch-and-dot-net
Search page-with-elasticsearch-and-dot-netSearch page-with-elasticsearch-and-dot-net
Search page-with-elasticsearch-and-dot-net
 
Build a-search-page-with-elastic search-and-dot-net
Build a-search-page-with-elastic search-and-dot-netBuild a-search-page-with-elastic search-and-dot-net
Build a-search-page-with-elastic search-and-dot-net
 
How to optimize asp dot-net application
How to optimize asp dot-net applicationHow to optimize asp dot-net application
How to optimize asp dot-net application
 
How to optimize asp dot net application ?
How to optimize asp dot net application ?How to optimize asp dot net application ?
How to optimize asp dot net application ?
 
10 things to remember
10 things to remember10 things to remember
10 things to remember
 
Learn dot net attributes
Learn dot net attributesLearn dot net attributes
Learn dot net attributes
 
Learn about dot net attributes
Learn about dot net attributesLearn about dot net attributes
Learn about dot net attributes
 
Owin and-katana-overview
Owin and-katana-overviewOwin and-katana-overview
Owin and-katana-overview
 
Top 15-asp-dot-net-interview-questions-and-answers
Top 15-asp-dot-net-interview-questions-and-answersTop 15-asp-dot-net-interview-questions-and-answers
Top 15-asp-dot-net-interview-questions-and-answers
 
Next generation asp.net v next
Next generation asp.net v nextNext generation asp.net v next
Next generation asp.net v next
 
Dot net universal apps
Dot net universal appsDot net universal apps
Dot net universal apps
 
Browser frame building with c# and vb dot net
Browser frame building  with c# and vb dot netBrowser frame building  with c# and vb dot net
Browser frame building with c# and vb dot net
 
A simplest-way-to-reconstruct-.net-framework
A simplest-way-to-reconstruct-.net-frameworkA simplest-way-to-reconstruct-.net-framework
A simplest-way-to-reconstruct-.net-framework
 
Silverlight versions-features
Silverlight versions-featuresSilverlight versions-features
Silverlight versions-features
 
History of silverlight versions and its features
History of silverlight versions and its featuresHistory of silverlight versions and its features
History of silverlight versions and its features
 
What is microsoft silverlight?
What is microsoft silverlight?What is microsoft silverlight?
What is microsoft silverlight?
 

Recently uploaded

Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfakmcokerachita
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptxENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptxAnaBeatriceAblay2
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaVirag Sontakke
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Blooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxBlooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxUnboundStockton
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 

Recently uploaded (20)

Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdf
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptxENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of India
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Blooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxBlooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docx
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 

Authorization p iv

  • 1. Authorization In Asp.Net Part IV Resource Based Authorization Today we will be discussing resource based authorization. Often authorization is based upon the accessed resource . E.g. a document might have an author property. So only the author would be allowed to update it; the resource must be loaded from the document repository before an authorization access can be made. This can't be done with an Authorize attribute, as feature evaluation takes place before data binding and before the code to load a resource runs inside an action. Instead of the declarative authorization, the attribute method, we must use impervious authorization, where a developer calls upon an authorize function within his own code. Authorizing within a code Authorization is executed as a service, IAuthorizationService, registered in the service collection and available via dependency injection for Controllers to approach. public class DocumentController : Controller { IAuthorizationService _authorizationService;
  • 2. public DocumentController(IAuthorizationService authorizationService) { _authorizationService = authorizationService; } } IAuthorizationService has 2 methods: in one, you pass the resource and the policy name and in the other, you pass the resource and a list of requirements to assess. Task<bool> AuthorizeAsync(ClaimsPrincipal user, object resource, IEnumerable<IAuthorizationRequirement> requirements); Task<bool> AuthorizeAsync(ClaimsPrincipal user, object resource, string policyName); To call upon the service load resource within action then call the AuthorizeAsync overload you require. e.g. public async Task<IActionResult> Edit(Guid documentId) { Document document = documentRepository.Find(documentId); if (document == null) { return new HttpNotFoundResult(); } if (await authorizationService.AuthorizeAsync(User, document, "EditPolicy")) {
  • 3. return View(document); } else { return new ChallengeResult(); } } Writing a resource based handler Now to write a handler for resource based authorization is not very much different to write a plain requirements handler. You create a requirement, and then execute a handler for the requirement, then specify the requirement as before and also the resource type. Therefore, a handler which might accept a Document resource would look as below: public class DocumentAuthorizationHandler : AuthorizationHandler<MyRequirement, Document> { public override Task HandleRequirementAsync(AuthorizationHandlerContext context, MyRequirement requirement, Document resource) { // Ratify the requirement against the resource and identity. return Task.CompletedTask; } } Don’t forget you also need to list your handler in the ConfigureServices method; services.AddSingleton<IAuthorizationHandler, DocumentAuthorizationHandler>(); Requirements If you want to make decisions based on operations such as read, write, update and delete, you can use the OperationAuthorizationRequirement in the Microsoft.AspNetCore.Authorization.Infrastructure namespace. This previously built requirement class helps you to write a single handler which has a set parameterized operation name, rather than develop individual classes for each operation. To utilize it provide some operation names:
  • 4. public static class Operations { public static OperationAuthorizationRequirement Create = new OperationAuthorizationRequirement { Name = "Create" }; public static OperationAuthorizationRequirement Read = new OperationAuthorizationRequirement { Name = "Read" }; public static OperationAuthorizationRequirement Update = new OperationAuthorizationRequirement { Name = "Update" }; public static OperationAuthorizationRequirement Delete = new OperationAuthorizationRequirement { Name = "Delete" }; } Your handler could then be executed as follows, using a hypothetical Document class as the resource; public class DocumentAuthorizationHandler : AuthorizationHandler<OperationAuthorizationRequirement, Document> { public override Task HandleRequirementAsync(AuthorizationHandlerContext OperationAuthorizationRequirement , Document resource) { // Validate the operation using the resource, the identity and // the Name property value from the requirement. return Task.CompletedTask; } } You can view the handler works upon OperationAuthorizationRequirement. The code inside the handler must take the Name property of the supplied need into account when making its evaluations.
  • 5. To call an operational resource handler you are required to specify the operation when calling AuthorizeAsync in your action. For example if (await authorizationService.AuthorizeAsync(User, document, Operations.Read)) { return View(document); } else { return new ChallengeResult(); } This example checks if the user is able to perform the read function for the current document. If authorization succeeds the view for the document will be returned. If you want to learn ASP.Net and perfect yourself in .NET training, our CRB Tech Solutions would be of great support for you. Join us with our updated program in ASP.Net course. Stay connected to CRB Tech reviews for more technical optimization and other resources.