PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label asp.net-identity. Show all posts
Showing posts with label asp.net-identity. Show all posts

Thursday, October 20, 2022

[FIXED] How does .net core web api jwtbearer middleware verify OpenID Connect token with authentication provider

 October 20, 2022     asp.net-identity, idp, jwt, keycloak, openid-connect     No comments   

Issue

I have been banging my head against the wall for a few days now. The solution is probably too simple to state in blogs so I ask the question here.

I am developing a .NET Core Web API which should delegate all authentication and authorization to a Keycloak identity provider server.

I have written the following code in my Startup.cs file:

services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

            }).AddJwtBearer(o =>
            {
                o.Authority = "https://idp.abc.xyz/auth/realms/master";
                o.Audience = "products-api";
            });

            services.AddAuthorization(options =>
            {
                options.AddPolicy("Administrator", policy => policy.RequireClaim("user_roles", "product_catalog_admin"));
                options.AddPolicy("User", policy => policy.RequireClaim("user_roles", "product_catalog_user"));


            });

Now I can use Postman to request a token from the IDP and send that token to the Web API. Then the Web API validates that token but does NOT know anything about the IDP other than the URL and only makes a request to a public URL of the IDP to get some configuration.

Question: HOW does the Web API know that the token is valid, not tampered with (created using different key), if it doesn't know anything about the IDP?


Solution

AddJwtBearer will use the options you give it to perform in memory validation of tokens. By default this involves the following actions:

  • Validate issuer
  • Validate audience
  • Check that the token's exp claim is not in the past (expired)
  • Verify the access token's digital signature

The 4th check is the most complex and by default this involves downloading token signing public keys from the IDP's JWKS endpoint, then choosing the one in the JWT's kid header. A blog post of mine has some details on how this works.

Of course you should always test the above 4 conditions and ensure that in each case API access is denied with a 401 error response that clients can code against.



Answered By - Gary Archer
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, September 4, 2022

[FIXED] How to protect all controllers by default with bearer token in ASP.NET Core?

 September 04, 2022     asp.net-core, asp.net-identity, authentication, c#, jwt     No comments   

Issue

I have added a JWT middleware to my application:

app.UseJwtBearerAuthentication(options => { options.AutomaticAuthenticate = true;} )

Ideally what I want to achieve is that all controller actions are protected by default (there were filters for that in previous ASP.NET), and I will put Anonymous on those that I want public or perhaps Authorize("SomePolicy") if I want additional policies, but I want that without a token the API cannot be accessed at all. How do I do this in the ASP.NET Core?


Solution

Starting with .Net 6 we can do this (if using minimal hosting model recommended by Microsoft):

app
  .MapControllers()
  .RequireAuthorization(); // This will set a default policy that says a user has to be authenticated

Starting with .Net Core 3 we can do this:

app.UseEndpoints(endpoints =>
{
    endpoints
        .MapControllers()
        .RequireAuthorization(); // This will set a default policy that says a user has to be authenticated
});

It is possible to change default policy or add a new policy and use it as well.

P.S. Please note that even though the method name says "Authorization", by default it will only require that the user is Authenticated. It is possible to add more policies to extend the validation though.



Answered By - Ilya Chernomordik
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, July 16, 2022

[FIXED] How to request additional claims with Facebook authentication

 July 16, 2022     asp.net-core, asp.net-identity, authentication, c#, facebook-login     No comments   

Issue

I have created a new ASP.net Core 3.0 website, with individual user authentication from the .net project template.

I am storing users by registering directly on the site or using facebook. Here's what my Startup.cs looks like:

public void ConfigureServices(IServiceCollection services)
{
     services.Configure<CookiePolicyOptions>(options => {
           // This determines user consent for non-essential cookies is needed for a given request.
           options.CheckConsentNeeded = context => true;
           options.MinimumSameSitePolicy = SameSiteMode.None;
      });

      services.AddDbContext<ApplicationDbContext>(options => {
           options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
      });

      services.AddAuthentication()
           //.AddMicrosoftAccount(microsoftOptions => {  })
           //.AddGoogle(googleOptions => {  })
           //.AddTwitter(twitterOptions => {  })
           .AddFacebook(facebookOptions =>
           {
               facebookOptions.AppId = "x";
               facebookOptions.AppSecret = "y";
           });

    ...
}

This all works fine and using the default template I can Register/Login as expected.

When I login via Facebook, I'm given five default pieces of claims information about the user:

  • name identifier
  • email address
  • given name
  • name
  • surname

What I need to do is extend the code so it does more than the default and gives me access to the users:

  • phone number
  • address
  • postcode

(Obviously with the users consent)

I've been reading the documentation (https://docs.microsoft.com/en-us/aspnet/core/security/authentication/social/facebook-logins?view=aspnetcore-3.1) but it seems to be more about configuring the authentication provider than additional claims info.

Has anyone done this? Maybe it's not possible?

Thanks for any pointers in advance.


Solution

From: Persist additional claims and tokens from external providers in ASP.NET Core - If the app requires additional scopes, add them to the options. For example, in Facebook, you can add scopes like this.

services.AddAuthentication().AddFacebook(facebookOptions =>
{
    facebookOptions.AppId = "4387237897237";
    facebookOptions.AppSecret = "23498423808320849082308";
    facebookOptions.Scope.Add("email");
    facebookOptions.Scope.Add("user_location");
    facebookOptions.Scope.Add("user_birthday");
});

Which will show details like this - login screen more details.

Facebook authentication dialog



Answered By - Anuraj
Answer Checked By - Senaida (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home
View mobile version

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing