A day with .Net

My day to day experince in .net

Micro Services Architecture – Design Authentication with IdentityServer4, SQL Server and ASP.NET Core Part-2

Posted by vivekcek on January 20, 2018

This is the continuation of my first post about “Setting up IdentityServer4 for token based authentication in Microservices architecture”

Please read the first part.
Micro Services Architecture – Design Authentication with IdentityServer4, SQL Server and ASP.NET Core Part-1

In this part we will create a Web Api. To access this Web Api first we need to get a valid token from our Identity Server. After getting the token we can call the Web Api.

Please note that we are using ASP.NET Core 1.1. The steps to do the same in ASP.NET Core 2.0 is little bit different.

1.Create a Web Api project named Protected Api.

2.Select Web Api template.

3.Now add nuget package named “IdentityServer4.AccessTokenValidation”.

4.Now update your Configure method in Startup.cs

 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
            {
                Authority = "http://localhost:5000",
                RequireHttpsMetadata = false,

                ApiName = "api1"
            });

            app.UseMvc();
        }

5.Now create a controller as below with Authorize attribute.

 [Route("api/[controller]")]
    public class ValuesController : Controller
    {
        [Authorize]
        [HttpGet]
        public IActionResult Get()
        {
            return new JsonResult(User.Identity.IsAuthenticated);
        }

    }

6.Now first start our IdentityService. Then get a token as explained in the Part 1.
7.Now use that token with Postman to call our protected Api.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s