SlideShare ist ein Scribd-Unternehmen logo
1 von 7
Downloaden Sie, um offline zu lesen
Authorization
Part III
Custom Policy-Based Authorization
Both the role authorization and claims authorization make use of a need, a handler for the requirement
and a per-configured policy.
They allow you to express authorization access in code, allowing a richer, reusable, and easily testable
authorization structure.
An authorization policy is made up of one or more needs and registered at application startup as part of
the Authorization service configuration, in ConfigureServices in the Startup.cs file system.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddAuthorization(options =>
{
options.AddPolicy("Over21",
policy => policy.Requirements.Add(new MinimumAgeRequirement(21)));
}
});
Here you see an “Over21” policy is created with a single requirement of a minimum age, which is
passed as a requirement.
Policies are applied using the Authorize feature by specifying the policy name, e.g.
[Authorize(Policy="Over21")]
public class AlcoholPurchaseRequirementsController : Controller
{
public ActionResult Login()
{
}
public ActionResult Logout()
{
}
}
Requirements
An authorization requirement is a sum of data parameters that a policy can use to evaluate the current
user principal. In the Minimum Age policy, the requirement is of a single parameter. A requirement
must implement IAuthorizationRequirement. This is a void, marker interface. The criteria of minimum
age requirement might be implemented as follows;
public class MinimumAgeRequirement : IAuthorizationRequirement
{
public MinimumAgeRequirement(int age)
{
MinimumAge = age;
}
protected int MinimumAge { get; set; }
}
A requirement doesn’t need to have data or properties.
Authorization Handlers
This is responsible for the assay of any properties of requirement. The authorization handler must
assay them against a provided AuthorizationContext to finalize if authorization is allowed. A
requirement can have many handlers. Handlers must inherit AuthorizationHandler<T> where the
alphabet T is the need it handles.
The minimum age handler might look like this:
public class MinimumAgeHandler : AuthorizationHandler<MinimumAgeRequirement>
{
protected override Task HandleRequirementAsync(AuthorizationContext context,
MinimumAgeRequirement requirement)
{
if (!context.User.HasClaim(c => c.Type == ClaimTypes.DateOfBirth &&
c.Issuer == "http://contoso.com"))
{
return Task.FromResult(0);
}
var dateOfBirth = Convert.ToDateTime(context.User.FindFirst(
c => c.Type == ClaimTypes.DateOfBirth && c.Issuer == "http://contoso.com").Value);
int calculatedAge = DateTime.Today.Year - dateOfBirth.Year;
if (dateOfBirth > DateTime.Today.AddYears(-calculatedAge))
{
calculatedAge--;
}
if (calculatedAge >= requirement.MinimumAge)
{
context.Succeed(requirement);
}
return Task.FromResult(0);
}
}
In the code above let's first see if the current user principal has a DOB claim which has been issued by
an Issuer we could know and trust. If the claim is missing we can’t authorize so we return. If we have a
claim, we find out how old the user is, and if they meet the minimum age criteria then the authorization
is successful. Once it is a success we call context.Succeed() passing in the requirement.
Handlers must be listed in the services collection during configuration, for example;
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddAuthorization(options =>
{
options.AddPolicy("Over21",
policy => policy.Requirements.Add(new MinimumAgeRequirement(21)));
});
services.AddSingleton<IAuthorizationHandler, MinimumAgeHandler>();
}
Each handler is added to the services collection by using
services.AddSingleton<IAuthorizationHandler, YourHandlerClass>(); passing in your handler class.
You can see in the handler example that the Handle() method has no return value, so how do we
indicate success and failure.
A handler depicts success by calling context.Succeed passing the need that has been successfully
assayed.
To guarantee failure even if other handlers for a requirement succeed, refer context.Fail.
Why would I want many handlers for a requirement?
In cases where you want the assay on an OR basis, you use multiple handlers for only one requirement.
E.g. , Microsoft has doors which open with key cards only. If you leave your key card at home the
responsible authority prints a temporary sticker and opens the door for you. In this case, you have a
single requirement, EnterBuilding, but many handlers, each one examining a single requirement.
public class EnterBuildingRequirement : IAuthorizationRequirement
{
}
public class BadgeEntryHandler : AuthorizationHandler<EnterBuildingRequirement>
{
protected override Task HandleRequirementAsync(AuthorizationContext context,
EnterBuildingRequirement requirement)
{
if (context.User.HasClaim(c => c.Type == ClaimTypes.BadgeId &&
c.Issuer == "http://microsoftsecurity"))
{
context.Succeed(requirement);
return Task.FromResult(0);
}
}
}
public class HasTemporaryStickerHandler : AuthorizationHandler<EnterBuildingRequirement>
{
protected override Task HandleRequirementAsync(AuthorizationContext context,
EnterBuildingRequirement requirement)
{
if (context.User.HasClaim(c => c.Type == ClaimTypes.TemporaryBadgeId &&
c.Issuer == "https://microsoftsecurity"))
{
// We'd also check the expiry date on the sticker.
context.Succeed(requirement);
return Task.FromResult(0);
}
}
}
Now, if both handlers are registered when a policy assays the EnterBuildingRequirement if either
handler does succeed the policy evaluation will succeed.
Using a function to fulfill a policy
There may be occasions where satisfying a policy is simple to express in code. It is possible to simply
supply a Func<AuthorizationHandlerContext, bool> when configuring the policy with the
RequireAssertion policy builder.
E.g. the previous BadgeEntryHandler could be again written as follows;
services.AddAuthorization(options =>
{
options.AddPolicy("BadgeEntry",
policy => policy.RequireAssertion(context =>
context.User.HasClaim(c =>
(c.Type == ClaimTypes.BadgeId ||
c.Type == ClaimTypes.TemporaryBadgeId)
&& c.Issuer == "https://microsoftsecurity"));
}));
}
}
Accessing MVC Request the context In Handlers
You must implement the Handle method which has two contexts, an AuthorizationContext and the
Requirement you are handling. Frameworks such as MVC or Jabber are free to join any object to the
Resource property on the AuthorizationContext to pass through extra information.
If you want to improve your skill set in ASP.Net and optimize yourself in .NET training, then our CRB
Tech Solutions would be of great support for you. Join us with our scientifically designed program of
ASP.Net course.
Stay connected to CRB Tech reviews for more technical optimization and other resources.

Weitere ähnliche Inhalte

Was ist angesagt?

Web 20 Security - Vordel
Web 20 Security - VordelWeb 20 Security - Vordel
Web 20 Security - Vordelguest2a1135
 
User Authentication and Cloud Authorization in the Galaxy project: https://do...
User Authentication and Cloud Authorization in the Galaxy project: https://do...User Authentication and Cloud Authorization in the Galaxy project: https://do...
User Authentication and Cloud Authorization in the Galaxy project: https://do...Vahid Jalili
 
MongoDB.local Sydney: Evolving your Data Access with MongoDB Stitch
MongoDB.local Sydney: Evolving your Data Access with MongoDB StitchMongoDB.local Sydney: Evolving your Data Access with MongoDB Stitch
MongoDB.local Sydney: Evolving your Data Access with MongoDB StitchMongoDB
 
Azure Mobile Services .NET Backend
Azure Mobile Services .NET BackendAzure Mobile Services .NET Backend
Azure Mobile Services .NET BackendShiju Varghese
 
How lagom helps to build real world microservice systems
How lagom helps to build real world microservice systemsHow lagom helps to build real world microservice systems
How lagom helps to build real world microservice systemsMarkus Eisele
 
Building Your First App with MongoDB Stitch
Building Your First App with MongoDB StitchBuilding Your First App with MongoDB Stitch
Building Your First App with MongoDB StitchMongoDB
 
Microservices Manchester: Highly Scalable, and Reliable Microservices with Mi...
Microservices Manchester: Highly Scalable, and Reliable Microservices with Mi...Microservices Manchester: Highly Scalable, and Reliable Microservices with Mi...
Microservices Manchester: Highly Scalable, and Reliable Microservices with Mi...OpenCredo
 
RIA services exposing & consuming queries
RIA services exposing & consuming queriesRIA services exposing & consuming queries
RIA services exposing & consuming queriesiedotnetug
 
Oauth 2.0 security
Oauth 2.0 securityOauth 2.0 security
Oauth 2.0 securityvinoth kumar
 
FIWARE Developers Week_ Introduction to Managing Context Information at Large...
FIWARE Developers Week_ Introduction to Managing Context Information at Large...FIWARE Developers Week_ Introduction to Managing Context Information at Large...
FIWARE Developers Week_ Introduction to Managing Context Information at Large...FIWARE
 
VBA API for scriptDB primer
VBA API for scriptDB primerVBA API for scriptDB primer
VBA API for scriptDB primerBruce McPherson
 
201410 2 fiware-orion-contextbroker
201410 2 fiware-orion-contextbroker201410 2 fiware-orion-contextbroker
201410 2 fiware-orion-contextbrokerFIWARE
 
Hybrid apps - Your own mini Cordova
Hybrid apps - Your own mini CordovaHybrid apps - Your own mini Cordova
Hybrid apps - Your own mini CordovaAyman Mahfouz
 
Attack Surface Reduction for Web Services based on Authorization Patterns
Attack Surface Reduction for Web Services based on Authorization PatternsAttack Surface Reduction for Web Services based on Authorization Patterns
Attack Surface Reduction for Web Services based on Authorization PatternsMax Vogler
 
Mixing OAuth 2.0, Jersey and Guice to Build an Ecosystem of Apps - JavaOne...
Mixing OAuth 2.0, Jersey and Guice to Build an Ecosystem of Apps - JavaOne...Mixing OAuth 2.0, Jersey and Guice to Build an Ecosystem of Apps - JavaOne...
Mixing OAuth 2.0, Jersey and Guice to Build an Ecosystem of Apps - JavaOne...Hermann Burgmeier
 

Was ist angesagt? (20)

Web 20 Security - Vordel
Web 20 Security - VordelWeb 20 Security - Vordel
Web 20 Security - Vordel
 
Mockito junit
Mockito junitMockito junit
Mockito junit
 
User Authentication and Cloud Authorization in the Galaxy project: https://do...
User Authentication and Cloud Authorization in the Galaxy project: https://do...User Authentication and Cloud Authorization in the Galaxy project: https://do...
User Authentication and Cloud Authorization in the Galaxy project: https://do...
 
MongoDB.local Sydney: Evolving your Data Access with MongoDB Stitch
MongoDB.local Sydney: Evolving your Data Access with MongoDB StitchMongoDB.local Sydney: Evolving your Data Access with MongoDB Stitch
MongoDB.local Sydney: Evolving your Data Access with MongoDB Stitch
 
Azure Mobile Services .NET Backend
Azure Mobile Services .NET BackendAzure Mobile Services .NET Backend
Azure Mobile Services .NET Backend
 
How lagom helps to build real world microservice systems
How lagom helps to build real world microservice systemsHow lagom helps to build real world microservice systems
How lagom helps to build real world microservice systems
 
Building Your First App with MongoDB Stitch
Building Your First App with MongoDB StitchBuilding Your First App with MongoDB Stitch
Building Your First App with MongoDB Stitch
 
Microservices Manchester: Highly Scalable, and Reliable Microservices with Mi...
Microservices Manchester: Highly Scalable, and Reliable Microservices with Mi...Microservices Manchester: Highly Scalable, and Reliable Microservices with Mi...
Microservices Manchester: Highly Scalable, and Reliable Microservices with Mi...
 
RIA services exposing & consuming queries
RIA services exposing & consuming queriesRIA services exposing & consuming queries
RIA services exposing & consuming queries
 
Azure DocumentDB
Azure DocumentDBAzure DocumentDB
Azure DocumentDB
 
Oauth 2.0 security
Oauth 2.0 securityOauth 2.0 security
Oauth 2.0 security
 
One tool to rule them all
One tool to rule them allOne tool to rule them all
One tool to rule them all
 
FIWARE Developers Week_ Introduction to Managing Context Information at Large...
FIWARE Developers Week_ Introduction to Managing Context Information at Large...FIWARE Developers Week_ Introduction to Managing Context Information at Large...
FIWARE Developers Week_ Introduction to Managing Context Information at Large...
 
VBA API for scriptDB primer
VBA API for scriptDB primerVBA API for scriptDB primer
VBA API for scriptDB primer
 
201410 2 fiware-orion-contextbroker
201410 2 fiware-orion-contextbroker201410 2 fiware-orion-contextbroker
201410 2 fiware-orion-contextbroker
 
Hybrid apps - Your own mini Cordova
Hybrid apps - Your own mini CordovaHybrid apps - Your own mini Cordova
Hybrid apps - Your own mini Cordova
 
Form1.vb
Form1.vbForm1.vb
Form1.vb
 
Goa tutorial
Goa tutorialGoa tutorial
Goa tutorial
 
Attack Surface Reduction for Web Services based on Authorization Patterns
Attack Surface Reduction for Web Services based on Authorization PatternsAttack Surface Reduction for Web Services based on Authorization Patterns
Attack Surface Reduction for Web Services based on Authorization Patterns
 
Mixing OAuth 2.0, Jersey and Guice to Build an Ecosystem of Apps - JavaOne...
Mixing OAuth 2.0, Jersey and Guice to Build an Ecosystem of Apps - JavaOne...Mixing OAuth 2.0, Jersey and Guice to Build an Ecosystem of Apps - JavaOne...
Mixing OAuth 2.0, Jersey and Guice to Build an Ecosystem of Apps - JavaOne...
 

Andere mochten auch (17)

Photos for shoot
Photos for shootPhotos for shoot
Photos for shoot
 
Калькулятор ремонта
Калькулятор ремонтаКалькулятор ремонта
Калькулятор ремонта
 
Prateek
PrateekPrateek
Prateek
 
CONTABILIDAD
CONTABILIDADCONTABILIDAD
CONTABILIDAD
 
KLima
KLima KLima
KLima
 
Updated research
Updated researchUpdated research
Updated research
 
El sistema excretor
El sistema excretorEl sistema excretor
El sistema excretor
 
Authorization p iv
Authorization p ivAuthorization p iv
Authorization p iv
 
Research
ResearchResearch
Research
 
Radme ru_leroy_merlin
Radme ru_leroy_merlinRadme ru_leroy_merlin
Radme ru_leroy_merlin
 
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
 
Cricket
CricketCricket
Cricket
 
Emails
EmailsEmails
Emails
 
China
ChinaChina
China
 
Semana Santa
Semana Santa Semana Santa
Semana Santa
 

Ähnlich wie Authorization iii

Hibernate working with criteria- Basic Introduction
Hibernate working with criteria- Basic IntroductionHibernate working with criteria- Basic Introduction
Hibernate working with criteria- Basic IntroductionEr. Gaurav Kumar
 
Community call: Develop multi tenant apps with the Microsoft identity platform
Community call: Develop multi tenant apps with the Microsoft identity platformCommunity call: Develop multi tenant apps with the Microsoft identity platform
Community call: Develop multi tenant apps with the Microsoft identity platformMicrosoft 365 Developer
 
Jasigsakai12 columbia-customizes-cas
Jasigsakai12 columbia-customizes-casJasigsakai12 columbia-customizes-cas
Jasigsakai12 columbia-customizes-casellentuck
 
Policy Injection in ASP.NET using Enterprise Library 3.0
Policy Injection in ASP.NET using Enterprise Library 3.0Policy Injection in ASP.NET using Enterprise Library 3.0
Policy Injection in ASP.NET using Enterprise Library 3.0PhilWinstanley
 
ASP.NET MVC 3.0 Validation
ASP.NET MVC 3.0 ValidationASP.NET MVC 3.0 Validation
ASP.NET MVC 3.0 ValidationEyal Vardi
 
Dependency injection - the right way
Dependency injection - the right wayDependency injection - the right way
Dependency injection - the right wayThibaud Desodt
 
AuthN deep.dive—ASP.NET Authentication Internals.pdf
AuthN deep.dive—ASP.NET Authentication Internals.pdfAuthN deep.dive—ASP.NET Authentication Internals.pdf
AuthN deep.dive—ASP.NET Authentication Internals.pdfondrejl1
 
Building the an End-to-End ASP.NET MVC 4, Entity Framework, HTML5, jQuery app...
Building the an End-to-End ASP.NET MVC 4, Entity Framework, HTML5, jQuery app...Building the an End-to-End ASP.NET MVC 4, Entity Framework, HTML5, jQuery app...
Building the an End-to-End ASP.NET MVC 4, Entity Framework, HTML5, jQuery app...Dan Wahlin
 
Security enforcement of Java Microservices with Apiman & Keycloak
Security enforcement of Java Microservices with Apiman & KeycloakSecurity enforcement of Java Microservices with Apiman & Keycloak
Security enforcement of Java Microservices with Apiman & KeycloakCharles Moulliard
 
Behavioral pattern 4
Behavioral pattern 4Behavioral pattern 4
Behavioral pattern 4Naga Muruga
 
The complete ASP.NET (IIS) Tutorial with code example in power point slide show
The complete ASP.NET (IIS) Tutorial with code example in power point slide showThe complete ASP.NET (IIS) Tutorial with code example in power point slide show
The complete ASP.NET (IIS) Tutorial with code example in power point slide showSubhas Malik
 
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
 
Paul Lammertsma: Account manager & sync
Paul Lammertsma: Account manager & syncPaul Lammertsma: Account manager & sync
Paul Lammertsma: Account manager & syncmdevtalk
 
Integrating Force.com with Heroku
Integrating Force.com with HerokuIntegrating Force.com with Heroku
Integrating Force.com with HerokuPat Patterson
 

Ähnlich wie Authorization iii (20)

Hibernate working with criteria- Basic Introduction
Hibernate working with criteria- Basic IntroductionHibernate working with criteria- Basic Introduction
Hibernate working with criteria- Basic Introduction
 
Community call: Develop multi tenant apps with the Microsoft identity platform
Community call: Develop multi tenant apps with the Microsoft identity platformCommunity call: Develop multi tenant apps with the Microsoft identity platform
Community call: Develop multi tenant apps with the Microsoft identity platform
 
Jasigsakai12 columbia-customizes-cas
Jasigsakai12 columbia-customizes-casJasigsakai12 columbia-customizes-cas
Jasigsakai12 columbia-customizes-cas
 
Policy Injection in ASP.NET using Enterprise Library 3.0
Policy Injection in ASP.NET using Enterprise Library 3.0Policy Injection in ASP.NET using Enterprise Library 3.0
Policy Injection in ASP.NET using Enterprise Library 3.0
 
ASP.NET MVC 3.0 Validation
ASP.NET MVC 3.0 ValidationASP.NET MVC 3.0 Validation
ASP.NET MVC 3.0 Validation
 
JSON and XML
JSON and XMLJSON and XML
JSON and XML
 
Dependency injection - the right way
Dependency injection - the right wayDependency injection - the right way
Dependency injection - the right way
 
AuthN deep.dive—ASP.NET Authentication Internals.pdf
AuthN deep.dive—ASP.NET Authentication Internals.pdfAuthN deep.dive—ASP.NET Authentication Internals.pdf
AuthN deep.dive—ASP.NET Authentication Internals.pdf
 
Building the an End-to-End ASP.NET MVC 4, Entity Framework, HTML5, jQuery app...
Building the an End-to-End ASP.NET MVC 4, Entity Framework, HTML5, jQuery app...Building the an End-to-End ASP.NET MVC 4, Entity Framework, HTML5, jQuery app...
Building the an End-to-End ASP.NET MVC 4, Entity Framework, HTML5, jQuery app...
 
Security enforcement of Java Microservices with Apiman & Keycloak
Security enforcement of Java Microservices with Apiman & KeycloakSecurity enforcement of Java Microservices with Apiman & Keycloak
Security enforcement of Java Microservices with Apiman & Keycloak
 
Behavioral pattern 4
Behavioral pattern 4Behavioral pattern 4
Behavioral pattern 4
 
Reduxing like a pro
Reduxing like a proReduxing like a pro
Reduxing like a pro
 
The complete ASP.NET (IIS) Tutorial with code example in power point slide show
The complete ASP.NET (IIS) Tutorial with code example in power point slide showThe complete ASP.NET (IIS) Tutorial with code example in power point slide show
The complete ASP.NET (IIS) Tutorial with code example in power point slide show
 
AJAX
AJAXAJAX
AJAX
 
AJAX
AJAXAJAX
AJAX
 
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
 
El bueno, el feo y el malo
El bueno, el feo y el maloEl bueno, el feo y el malo
El bueno, el feo y el malo
 
Paul Lammertsma: Account manager & sync
Paul Lammertsma: Account manager & syncPaul Lammertsma: Account manager & sync
Paul Lammertsma: Account manager & sync
 
70562 (1)
70562 (1)70562 (1)
70562 (1)
 
Integrating Force.com with Heroku
Integrating Force.com with HerokuIntegrating Force.com with Heroku
Integrating Force.com with Heroku
 

Mehr von 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
 
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
 
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
 

Mehr von 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
 
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
 
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
 

Kürzlich hochgeladen

Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...anjaliyadav012327
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...Sapna Thakur
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 

Kürzlich hochgeladen (20)

Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 

Authorization iii

  • 1. Authorization Part III Custom Policy-Based Authorization Both the role authorization and claims authorization make use of a need, a handler for the requirement and a per-configured policy. They allow you to express authorization access in code, allowing a richer, reusable, and easily testable authorization structure. An authorization policy is made up of one or more needs and registered at application startup as part of the Authorization service configuration, in ConfigureServices in the Startup.cs file system. public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddAuthorization(options =>
  • 2. { options.AddPolicy("Over21", policy => policy.Requirements.Add(new MinimumAgeRequirement(21))); } }); Here you see an “Over21” policy is created with a single requirement of a minimum age, which is passed as a requirement. Policies are applied using the Authorize feature by specifying the policy name, e.g. [Authorize(Policy="Over21")] public class AlcoholPurchaseRequirementsController : Controller { public ActionResult Login() { } public ActionResult Logout() { } } Requirements An authorization requirement is a sum of data parameters that a policy can use to evaluate the current user principal. In the Minimum Age policy, the requirement is of a single parameter. A requirement must implement IAuthorizationRequirement. This is a void, marker interface. The criteria of minimum age requirement might be implemented as follows; public class MinimumAgeRequirement : IAuthorizationRequirement { public MinimumAgeRequirement(int age) { MinimumAge = age; }
  • 3. protected int MinimumAge { get; set; } } A requirement doesn’t need to have data or properties. Authorization Handlers This is responsible for the assay of any properties of requirement. The authorization handler must assay them against a provided AuthorizationContext to finalize if authorization is allowed. A requirement can have many handlers. Handlers must inherit AuthorizationHandler<T> where the alphabet T is the need it handles. The minimum age handler might look like this: public class MinimumAgeHandler : AuthorizationHandler<MinimumAgeRequirement> { protected override Task HandleRequirementAsync(AuthorizationContext context, MinimumAgeRequirement requirement) { if (!context.User.HasClaim(c => c.Type == ClaimTypes.DateOfBirth && c.Issuer == "http://contoso.com")) { return Task.FromResult(0); } var dateOfBirth = Convert.ToDateTime(context.User.FindFirst( c => c.Type == ClaimTypes.DateOfBirth && c.Issuer == "http://contoso.com").Value); int calculatedAge = DateTime.Today.Year - dateOfBirth.Year; if (dateOfBirth > DateTime.Today.AddYears(-calculatedAge)) { calculatedAge--; }
  • 4. if (calculatedAge >= requirement.MinimumAge) { context.Succeed(requirement); } return Task.FromResult(0); } } In the code above let's first see if the current user principal has a DOB claim which has been issued by an Issuer we could know and trust. If the claim is missing we can’t authorize so we return. If we have a claim, we find out how old the user is, and if they meet the minimum age criteria then the authorization is successful. Once it is a success we call context.Succeed() passing in the requirement. Handlers must be listed in the services collection during configuration, for example; public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddAuthorization(options => { options.AddPolicy("Over21", policy => policy.Requirements.Add(new MinimumAgeRequirement(21))); }); services.AddSingleton<IAuthorizationHandler, MinimumAgeHandler>(); } Each handler is added to the services collection by using services.AddSingleton<IAuthorizationHandler, YourHandlerClass>(); passing in your handler class. You can see in the handler example that the Handle() method has no return value, so how do we indicate success and failure. A handler depicts success by calling context.Succeed passing the need that has been successfully assayed.
  • 5. To guarantee failure even if other handlers for a requirement succeed, refer context.Fail. Why would I want many handlers for a requirement? In cases where you want the assay on an OR basis, you use multiple handlers for only one requirement. E.g. , Microsoft has doors which open with key cards only. If you leave your key card at home the responsible authority prints a temporary sticker and opens the door for you. In this case, you have a single requirement, EnterBuilding, but many handlers, each one examining a single requirement. public class EnterBuildingRequirement : IAuthorizationRequirement { } public class BadgeEntryHandler : AuthorizationHandler<EnterBuildingRequirement> { protected override Task HandleRequirementAsync(AuthorizationContext context, EnterBuildingRequirement requirement) { if (context.User.HasClaim(c => c.Type == ClaimTypes.BadgeId && c.Issuer == "http://microsoftsecurity")) { context.Succeed(requirement); return Task.FromResult(0); } } } public class HasTemporaryStickerHandler : AuthorizationHandler<EnterBuildingRequirement> { protected override Task HandleRequirementAsync(AuthorizationContext context, EnterBuildingRequirement requirement) { if (context.User.HasClaim(c => c.Type == ClaimTypes.TemporaryBadgeId &&
  • 6. c.Issuer == "https://microsoftsecurity")) { // We'd also check the expiry date on the sticker. context.Succeed(requirement); return Task.FromResult(0); } } } Now, if both handlers are registered when a policy assays the EnterBuildingRequirement if either handler does succeed the policy evaluation will succeed. Using a function to fulfill a policy There may be occasions where satisfying a policy is simple to express in code. It is possible to simply supply a Func<AuthorizationHandlerContext, bool> when configuring the policy with the RequireAssertion policy builder. E.g. the previous BadgeEntryHandler could be again written as follows; services.AddAuthorization(options => { options.AddPolicy("BadgeEntry", policy => policy.RequireAssertion(context => context.User.HasClaim(c => (c.Type == ClaimTypes.BadgeId || c.Type == ClaimTypes.TemporaryBadgeId) && c.Issuer == "https://microsoftsecurity")); })); } } Accessing MVC Request the context In Handlers You must implement the Handle method which has two contexts, an AuthorizationContext and the Requirement you are handling. Frameworks such as MVC or Jabber are free to join any object to the Resource property on the AuthorizationContext to pass through extra information.
  • 7. If you want to improve your skill set in ASP.Net and optimize yourself in .NET training, then our CRB Tech Solutions would be of great support for you. Join us with our scientifically designed program of ASP.Net course. Stay connected to CRB Tech reviews for more technical optimization and other resources.