Identityserver4 implements authentication of. Net core API interface (quick start)

Time:2020-9-4

What is identity server 4

Official explanation: identity server 4 is based on ASP.NET The authentication and authorization framework implemented by core is the implementation of openid connect and OAuth 2.0 protocols.

Generally speaking, it means that the server encapsulates the resources that need authentication and authorization (client request resources) in the outer layer using the identityserver4 framework. Users can only access the resources by obtaining the token token token issued by identityserver4.

Let’s start with the topic of how to quickly build and implement API interface authentication.

Preparation: 1. Download and prepare the NETCORE SDK environment

2. The development environment of this paper is vs2019, and part of the code may be different from the previous version.

The first step,To create a new authority authentication service project, this paper takes the net core API project template as an example (you can also select other templates)

Step two, add the identityserver4 nuget package. Different versions depend on different netcoe SDK environments, so you need to manually select the appropriate version.

Here is a reminder that some students may not find the nuget package when adding it to their system. We have found out the solution here. Click the settings button in the upper right corner of the nuget package add page to see the following page, and manually add the following nuget.org And then search again.

Step three, add the identityserver4 configuration management class. This paper takes the user password authorization mode as an example.

public class Config
  {
    /// <summary>
    ///Define resource scope
    /// </summary>
    public static IEnumerable<ApiResource> GetApiResources()
    {
      return new List<ApiResource>
      {
        New apiresource ("API1", "my first API")
      };
    }

    /// <summary>
    ///Define resource clients to access
    /// </summary>
    /// <returns></returns>
    public static IEnumerable<Client> GetClients()
    {
      return new List<Client>
      {
        new Client{
          ClientID = client ", // define client ID
          ClientSecrets=
          {
            New secret ("secret". Sha256()) // define the client secret key
          },
          AllowedGrantTypes= GrantTypes.ResourceOwnerPassword , // the authorization mode is user password mode. Please refer to the granttypes enumeration for the type
          Allowedscopes = {API1 "} // allowed client access

        }
       };
    }

    /// <summary>
    ///This method is to standardize the rules and methods of token generation. Generally, it is not set, and the default can be used directly.
    /// </summary>
    /// <returns></returns>
    public static IEnumerable<IdentityResource> GetIdentityResources()
    {
      return new IdentityResource[]
      {
        new IdentityResources.OpenId()
      };
    }
  }

Step 4, start up class to register service middleware

// This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
      services.AddIdentityServer () // registration service
        .AddDeveloperSigningCredential()
        .AddInMemoryApiResources( Config.GetApiResources ()) // configure the authorization scope defined by the class
        .AddInMemoryClients( Config.GetClients ()) // configure the authorized client defined by the class
        . addtestusers (new list < testuser > {new testuser {user name = admin, password = 123456, subjectid = 001, isactive = true}}); // simulate test users, where they are lazy and can be managed separately. It's better not to create new directly here
      services.AddControllers();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
      if (env.IsDevelopment())
      {
        app.UseDeveloperExceptionPage();
      }

      app.UseIdentityServer (); // add Middleware
      
      app.UseHttpsRedirection();

      app.UseRouting();

      app.UseAuthorization();

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

There are two default port numbers for applications: 1 http://localhost :5000 2. https://localhost :5001.

Here, the identity server 4 authentication service has been simply set up. We started the project directly in vs. Add /. Well-known / openid configuration after the port number. If the following page appears, the configuration is successful.

Step five,Postman simulates the request to obtain the token (of course, this step is not necessary. Students who are interested in postman can have a try.)

We all know that identityserver4 requires the client to access the authentication service to obtain the token token before further accessing the weighted server resources. First, we simulate the client request through postman to get the token. (you can download the postman tool online or use the postman plug-in provided by Google.)

1. When using postman to request token, there is a point to note:

Many students use HTTPS to request, that is, request https://localhost : 5001, you will find that you cannot succeed. Because postman turns on SSL certificate authentication by default, we can turn it off manually. Find the small wrench icon at the top right of the postman page, enter the settings page, find SSL and turn it off. Of course, students use it directly http://localhost : 5000 requests do not need to set up SSL

2. Request parameters

The parameter value here is the client and testuser information set in the authentication service configuration class.

Grant_ Type is the authorization type. In this paper, we use the user password mode, so fill in password here

Here we see that we have successfully simulated the request to obtain the token. It’s finished. The authentication service has been verified to be available. Let’s go to release the deployment.

Step six,Authentication service release deployment.

There are three release modes of. Net core:

1. Framework dependency + portability

2. Framework dependency + runtime environment (with executable program exe)

3. Independent deployment

In short, the packages released by framework dependent mode need to be deployed with a running environment such as. Net core. However, independent deployment does not need to be considered. The release package already contains the running environment and can be deployed directly.

The following article gives a brief introduction to framework dependency + portable publishing.

After publishing, we will see the program DLL in the release path. We can find the release path and use the CMD command window: dotnet xxx.dll It can be started directly.

As above, it indicates that the startup is successful. (for other publishing modes, double-click the executable EXE file in the publishing package to start)

After the authentication service is deployed, how to use our API interface will be introduced formally.

Step 1:New web API project

Add nuget package

Step 2:Configure startup class

public void ConfigureServices(IServiceCollection services)
    {
      //Registration services
      services.AddAuthentication("Bearer")
        .AddIdentityServerAuthentication(x =>
        {
          x.Authority = " http://localhost : 5000 "; // authentication service address
          x.RequireHttpsMetadata = false;
          x. Apiname = "API1"; // authentication range
        });
      services.AddControllers();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
      if (env.IsDevelopment())
      {
        app.UseDeveloperExceptionPage();
      }
      app.UseAuthentication (); // add authentication
      app.UseHttpsRedirection();
      app.UseRouting();
        app.UseAuthorization();
      app.UseEndpoints(endpoints =>
      {
        endpoints.MapControllers();
      }); 
    }

There are two default port numbers for applications: 1 http://localhost :5000 2. https://localhost In order to avoid the port number conflict being occupied, we can modify the application startup port number in the program class.

public static IHostBuilder CreateHostBuilder(string[] args) =>
      Host.CreateDefaultBuilder(args)
      
        .ConfigureWebHostDefaults(webBuilder =>
        {
          webBuilder.UseUrls ("http: // *: 5555"); // set the boot port number
          webBuilder.UseStartup<Startup>();
        });

Step 3:Create API demo

[Route("api/[controller]")]
  [ApiController]
  public class TestController : ControllerBase
  {
    // GET: api/Test
    /// <summary>
    ///Method weighting
    /// </summary>
    /// <returns></returns>
    [Authorize]
    [HttpGet]
    public IEnumerable<string> Get()
    {
      return new string[] { "value1", "value2" };
    }

    /// <summary>
    ///Methods are not weighted and can be accessed directly
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    // GET: api/Test/5
    [HttpGet("{id}", Name = "Get")]
    public string Get(int id)
    {
      return "value";
    }

    /// <summary>
    ///Open access token API interface
    /// </summary>
    /// <returns></returns>
    [HttpGet("GetToken")]
    public async Task<string> GetToken()
    {
      var client = new HttpClient();
      var tokenResponse = await client.RequestPasswordTokenAsync(new PasswordTokenRequest
      {
        Address = "http://localhost:5000/connect/token",
        ClientId = "client",
        ClientSecret = "secret",
        Scope = "api1",
        UserName = "Admin",
        Password = "123456",
      });

      if (tokenResponse.IsError)
      {
        return tokenResponse.Error;
      }

      return tokenResponse.AccessToken;

    }
  }

1

[Authorize]

It is equivalent to weighting the interface, and only authorized users can access it (that is, the user who obtains token). In this case, the interface aboveBecause API / test is weighted, an error will be reported when requesting. However, API / test / 1 interface is not weighted and can still request normally.

So how can we access the weighted interface??? Go Next

2. We have opened the interface gettoken to obtain token (similar to that of getting token through postman above)

To access the weighted API interface, we need to request the token first, and then bring the token parameter when requesting the weighted interface.

3. Request weighted interface

Take token when requesting weighted interface, interface request succeeded!

OK, how to quickly develop and debug API interface authentication service based on identityserver4 framework has been introduced.

Little brother is not talented, this article has not considered thoroughly or the mistake place, welcome everybody to correct.

(if some students want to deploy API applications through IIS, here is a place to pay attention to. You need to add aspnetcoremodule module to IIS (function view module). The specific reasons are not introduced here. )

This article about identityserver4 to achieve. Net core API interface authority authentication (quick start) article introduced here, more related. Net core API authority authentication content, please search the previous articles of developpaer or continue to browse the related articles below, I hope you can support developeppaer more in the future!