Summary of IDENTITYSERVER4 usage of WEBAPI security access

Source: Internet
Author: User

WEBAPI projects often need to consider issues such as cross-domain, security, and so on. Today we summarize one of the simplest ways to protect Webapi from being casually invoked by others. Here is a summary of the use of identityserver4.

IdentityServer4 is the newest and more easy to use an open source framework, if you start from IdentityServer3, it will be easy to head big, do not know why. GitHub the above example

Son, IdentityServer4 is easier to understand. This time we used a way like OpenID connect. When the client accesses the Apiserver, first go to the identityserver above request

A visit to token. Use this token to access each interface of the apiserver.


As shown above: IdentityServer4 need to increase the reference to the IDENTITYSERVER4 framework, and webapiserver, need to increase IdentityServer4. Accesstokenvalidation, the client can request it in a variety of ways. Refer to Git above for sample. The console program I use here tests, and the Client introduces the IdentityModel reference.

The following frame is built:

1 First is identityserver4, mainly from the demo to rewrite the configuration can be. There is basically no need to add code.

Configuring IdentityServer4 in Startup.cs

        public void Configureservices (iservicecollection services)
        {
            services. Adddeveloperidentityserver ()
                . Addinmemoryscopes (Config.getscopes ())
                . Addinmemoryclients (Config.getclients ());
        }
        public void Configure (Iapplicationbuilder app, ihostingenvironment env)
        {
            app. Useidentityserver ();
        }
Configure the available client in Config, note that the allowdgranttypes is clientcredentials type.

        public static ienumerable<client> getclients ()         {        &NB Sp
  list<client> LST = new list<client> ();             var client = new Client ()             {  &NB Sp             ClientId = setting. ClientID,                 allowedgranttypes = granttypes.clientcredentials, &nbs P               clientsecrets =                 & nbsp   {                        new Secret (setting. SERCETKEY.SHA256 ())                    },         & nbsp       Accesstokenlifetime = setting. Tokenlifttime * 3600,//accesstoken expiration, in seconds         &NBSp       allowedscopes = {setting.
APPName}            };             LST.
ADD (client);
            return LST;                    

2 WEBAPI Service Configuration

Because the new identityserver4 are available on the. NET core platform, publishing uses the Useiisintegration attribute instead of Useurls on IIS.

        public static void Main (string[] args)
        {
            var host = new Webhostbuilder ()
                . Usekestrel ()
                . Useiisintegration ()  //. Useurls ("http://localhost:5001") 
                . Usecontentroot (Directory.GetCurrentDirectory ())
                . Useiisintegration ()
                . Usestartup<startup> ()
                . Build ();

            Host. Run ();
        }

Then, in Startup.cs, configure the IP of the authorized server that needs to be bound. That is, modify the Authority property, specify Apiname, this information will be written to the token signature, so a character

Can not be wrong. Otherwise, n more than 401 errors. unauthroity public void Configure (Iapplicationbuilder app, Ihostingenvironment env, Iloggerfactory loggerfactory)

        {
            Loggerfactory.addconsole (configuration.getsection ("Logging"));
            Loggerfactory.adddebug ();
            App. Useidentityserverauthentication (New identityserverauthenticationoptions
{
authority = configuration["Server"],
Requirehttpsmetadata = False,
//backchanneltimeouts = T
   apiname = "Tempsengoapi"
});


App. Usecors ("any");

            App. Usemvc ();
        }

Here we define the API, add a Web API controller Clientcontroller use the "authorize" annotation to mark the class. The token validation is completed by the framework. If the token validation passes, it goes into the code of the Get action to handle the business logic if the validation is illegal. Will not go into the code of Get. [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});
        }
    
3. Request Token

The client code is as follows: public static void Main (string [] args)

        {
            //Access authorization server gets token
            var disco = discoveryclient.getasync ("http://localhost:5000"). result;
            var tokenclient = new Tokenclient (Disco. Tokenendpoint, "Linezeroclient", "secret");
            var tokenresponse = Tokenclient.requestclientcredentialsasync ("Zeroapi"). result;
            
            Setting the token Access API Tokenresponse.accesstoken is the requested token and can use this token to access Webapi
            var client = new HttpClient ();
            Client. Setbearertoken (Tokenresponse.accesstoken);

            var response = client. Getasync ("Http://localhost:5001/api/Identity"). result;
            if (!response. Issuccessstatuscode)
            {
                Console.WriteLine (response). StatusCode);
            }
            var content = Response. Content.readasstringasync (). result;
            Console.WriteLine (content);
            Console.readkey ();
        }
4 Use Postman to test the token.


Summary: I understand that the process is like this. Token is stored on IDENTITYSERVER4 servers instead of temporary storage, such as in memory, and token is still valid even if the server reboots. Only depends on the content of the token itself, the time expires. When applying the client request to token, add token to the head. The request sent to the accesstokenvalidation in Webapi,webapi will send the token to identityserver4 in real time to verify. Once the validation is passed, it enters the action's handler function. That is, the token will not expire regardless of whether the WEBAPI is restarted or the identityserver4 is restarted.

I found a good post when I finished. can also refer to.

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.