Thursday, August 5, 2021

Basic Client Authentication Using IdentityServer4 - The Client

 Let us now create the client. Out client will be a web api project which exposes weatherforecast api. 

1. Create a new asp .net core web api project: 





2. Main changes will be in startup.cs and a minor change is required in the controller file. 

We need to use JwtBearerDefaults structure in startup.cs. For that we need to install 

IdentityServer4.AccessTokenValidation package. Let us install this using nuget: 




3. In startup.cs, in the ConfigureServices method, add the following : 

        public void ConfigureServices(IServiceCollection services)

        {

            services.AddControllers();

            services.AddAuthentication(options => {

                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;

                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

            }).AddJwtBearer(op =>

            {

                op.Authority = "https://localhost:44368";

                op.Audience = "weatherapiresource";

            });


        }


4. In the Configure method, add  app.UseAuthentication();


        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }

This completes your modifications in startup.cs. The only remaining thing is to add [Authorize] attribute in controller. 


5. Go to controllers\WeatherForecastController and  add [Authorize] attribute before the [HttpGet] attribute of Get() method. You will need to reference Microsoft.AspNetCore.Authorization for it. 

         [Authorize]

        [HttpGet]

        public IEnumerable<WeatherForecast> Get()

        {

            var rng = new Random();

            return Enumerable.Range(1, 5).Select(index => new WeatherForecast

            {

                Date = DateTime.Now.AddDays(index),

                TemperatureC = rng.Next(-20, 55),

                Summary = Summaries[rng.Next(Summaries.Length)]

            })

            .ToArray();

        }


6. Build and Run the project. 

7. Notice that the project runs but gives an authorization error in the browser: 


The same error is given in postman too: 



8. This is because now the weatherforecast api requires a token to allow access to it. 

So let us generate a token using POSTMAN by calling /connect/token endpoint and then pass it to get request. 

To pass a token to get request in POSTMAN, open the "Authorization" tab of the request: 


Then open the "Type" drop down and select "Bearer Token" 


In the "Token" input box that appears on the right side, paste your token. 

And resend the GET request by pressing the "Send" button. 


9. Provided the token is not old and expired, you should now get the response of weatherforecast get api. 





No comments:

Post a Comment

How to check local and global angular versions

 Use the command ng version (or ng v ) to find the version of Angular CLI in the current folder. Run it outside of the Angular project, to f...