OpenID Connect OAuth 2.0 Framework Learning Protection API for IdentityServer4 ASP.

Source: Internet
Author: User
Tags form post oauth openid rfc



IdentityServer4 ASP. NET Core's OpenID Connect OAuth 2.0 framework learns the Protection API.



Use IdentityServer4 to protect the ASP. NET Core Web API access using client credentials.



IdentityServer4 Github:https://github.com/identityserver/identityserver4



The Identityserver framework supports the following features:



Authentication Service
Centralized login logic and workflow for all applications (WEB, native, mobile, service).



Single Sign-On/exit
Single Sign-on and exit for multiple application types.



Access Control for APIs
Issue access tokens for APIs for various types of customers, such as server-to-server, Web application, spa, and native/mobile applications.



Federated Login
Support for external identity providers, such as Azure Active directory,google,facebook.



Focus on customization
The most important part of identityserver-many aspects can be customized to meet your needs. Since Identityserver is a framework and not a closed product or SaaS, you can write code that adapts your system to the corresponding scene.












Identityserver implements the following specifications:


OpenID Connect


OpenID Connect Core 1.0
OpenID Connect Discovery 1.0
OpenID Connect Session Management 1.0-draft 22
OpenID Connect http-based Logout 1.0-draft 03


OAuth 2.0


OAuth 2.0 (RFC 6749)
OAuth 2.0 Bearer Token Usage (RFC 6750)
OAuth 2.0 Multiple Response Types
OAuth 2.0 Form Post Response Mode
OAuth 2.0 Token Revocation (RFC 7009)
OAuth 2.0 Token Introspection (RFC 7662)
Proof Key for Code Exchange (RFC 7636)






The main explanation is to use the client Credential Protection API. How to ensure that your API is not accessed by other people without authorization?



A formal example begins below.


New ASP. NET core project and reference IdentityServer4


First create a new ASP. NET Core project Identityserver4demo, and then select the empty template.






Then add a reference.



NuGet command line:


Install-package Identityserver4-pre

IdentityServer4 use


Add a good reference and we can use it later.



First create a Config.cs class.



Define the scope:


 public static IEnumerable<Scope> GetScopes()
        { return new List<Scope> { new Scope
                {
                    Name = "zeroapi",
                    Description = "LineZero ASP.NET Core Web API" }
            };
        }


Define the client:


public static IEnumerable <Client> GetClients ()
         {
             return new List <Client>
             {
                 new Client
                 {
                     ClientId = "linezeroclient",

                     // Use clientid / secret for authentication
                     AllowedGrantTypes = GrantTypes.ClientCredentials,

                     // encryption verification
                     ClientSecrets = new List <Secret>
                     {
                         new Secret ("secret" .Sha256 ())
                     },

                     // The scope that the client can access, as defined above.
                     AllowedScopes = new List <string>
                     {
                         "zeroapi"
                     }
                 }
             };
         }


Once defined, configure the IdentityServer4 in Startup.cs


         Public
 public void ConfigureServices(IServiceCollection services)
        {
            services.AddDeveloperIdentityServer()
                .AddInMemoryScopes(Config.GetScopes())
                .AddInMemoryClients(Config.GetClients());
        }
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseIdentityServer();
        }


And then we start Identityserver4demo.



Visit: http://localhost:5000/.well-known/openid-configuration






Identityserver created successfully.





New WEBAPI Project





Then add a reference.



NuGet command line:


Install-package Identityserver4.accesstokenvalidation-pre





First change the URL address of the API and not duplicate the server.



Change this to http://localhost:5001


public static void Main(string[] args)
        { var host = new WebHostBuilder()
                .UseKestrel()
                .UseUrls("http://localhost:5001")
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseIISIntegration()
                .UseStartup<Startup>()
                .Build();

            host.Run();
        }


Then configure the relevant information in the Startup.cs


 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();
            app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
            {
                Authority = "http://localhost:5000",
                ScopeName = "zeroapi",

                RequireHttpsMetadata = false });

            app.UseMvc();
        }


Note: The authorized address defined here is http://localhost:5000



Let's define the API and add a Web API controller Clientcontroller


[Route("api/[controller]")]
    [Authorize] public class ClientController : Controller
    {
        [HttpGet] public IActionResult Get()
        { return new JsonResult(from c in User.Claims select new { c.Type, c.Value });
        }
    }


The authorize feature is added above, and the direct access API is inaccessible.



After the program is started, Access http://localhost:5001/api/client returns 401.


Client Calls


Create a client call to add a console program to the client.



The first thing to add is a reference:



NuGet command line:


Install-package IdentityModel


The client code is as follows:


public static void Main (string [] args)
        {
            // Access the authorization server to obtain the token
            var disco = DiscoveryClient.GetAsync ("http: // localhost: 5000") .Result;
            var tokenClient = new TokenClient (disco.TokenEndpoint, "linezeroclient", "secret");
            var tokenResponse = tokenClient.RequestClientCredentialsAsync ("zeroapi"). Result;
            if (tokenResponse.IsError)
            {
                Console.WriteLine (tokenResponse.Error);
                return;
            }

            Console.WriteLine (tokenResponse.Json);
            Console.WriteLine ("===============================);
            // Set token access API
            var client = new HttpClient ();
            client.SetBearerToken (tokenResponse.AccessToken);

            var response = client.GetAsync ("http: // localhost: 5001 / api / client") .Result;
            if (! response.IsSuccessStatusCode)
            {
                Console.WriteLine (response.StatusCode);
            }

            var content = response.Content.ReadAsStringAsync (). Result;
            Console.WriteLine (content);
            Console.ReadKey ();
        } 





And then start running each.



Start Identityserver4demo First, then the API then client.






Client successfully accesses the API. Using the client Credential Protection API is basically done here.



More IdentityServer4 information: https://identityserver4.readthedocs.io/






If you think this article is helpful to you, please click " recommend ", thank you.



OpenID Connect OAuth 2.0 Framework Learning Protection API for IdentityServer4 ASP.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.