Quick Start Series--webapi--01 Basics

Source: Internet
Author: User
Tags http authentication list of attributes oauth ticket to domain asymmetric encryption

ASP. NET MVC and Webapi are already in the mainstream of the, two common pipeline at the beginning, and then in order to be more lightweight (WEBAPI is lightweight for WCF restful), Webapi uses a new pipeline, Therefore, there are subtle differences in the namespace of the related classes, which need to be noted when using them.

WEBAPI Study Series catalogue is as follows, welcome your reading!

Quick Start Series--webapi--01 Basics

Quick Start Series--webapi--02 Advanced

Quick Start Series--webapi--03 frame you deserve it

Quick Start Series--webapi--04 adjustment under old version MVC4

    • Similarities and differences between WEBAPI and ASP.

Routes for asp: Routes (routecollection), thread-safe, read-write locks, Getreadlock, Getwritelock. RouteTable.Routes.MapPageRoute (...);

namespace is in System.Web.Routing

WEBAPI Routing: first introduces its related types, they are simple encapsulation of Http messages, System.Net.Http (Httprequestmessage, Httpresponsemessage).

The namespace is system.web. Http. In routing

Two routes, such as hosting Webapi in a Web application in Web host mode, the final URL route is completed via the routing system of the ASP. Several main types, Httpcontrollerroutehandler,

Httproutehandler.

    • Message Processing pipeline

It is also remembered that the core of ASP. HttpHandler, while in Webapi its pipeline processor is httpmessagehandler. In practice, it is handled through the Innerhandler (Delegationhandler) way through the responsibility chain mode. Among them, the first of this pipeline is Httpserver, the end of which is httproutingdispatcher (both in the System.Web.Http namespace, supports the asynchronous model), P108

TIP: You can also understand why the WEBAPI pipeline is more lightweight, so it only needs to deal with JSON and other types of data, no need to consider content such as page, JS, static resources, etc.

    • Common features

Class: [Routeprefix ("Api/demo")], the routing settings for specific classes, relative routeconfig, finer granularity.

Method: [Route ("Action")]

[HttpGet], [HttpPost]

About Web services, where the more difficult concepts are generally focused on security, and its related concepts are many, including the Windows-related authentication mode, forms authentication, third-party authentication, cross-domain access, and so on. In addition, the concepts of httpclient, IOC framework selection, service idempotent, SignalR, Ehab in EntLib are added.

. NET security Model:

Identiy represents the user identity, Identity AuthenticationType, isauthenticated, Name}, the common identity has WindowsIdentity, FormsIdentity, GenericIdentity. P556

IPrincipal, the entity that was successfully authorized, is equivalent to the identity plus role, including WindowsPrincipal (permission Group for Windows), GenericPrincipal, RolePrincipal ( Membership components and Roles components). Common authentication methods are through "challenge-answer" (challenge-response) mode.

Common HTTP authentication method, basic and digest, the former use the authentication credentials (username + password) through Base64 encoding without encryption, but we can use HTTPS transmission to solve the confidentiality problem. Two filters associated with this, Authenticationfilter and Authorizationfilter.

To supplement the Actionfilter concept, such as a request involving a large number of operations, and the input and output one by one correspond (i.e. the same input has the same output), then consider caching the action. P585

Windows Authentication mode (both by setting the identity authentication Mode in IIS)

Webhost Security under Boarding: Windows Authentication mode, through basic, Digest authentication scheme, eventually using NTLM or Kerberos protocol. The principal of authenticated users is embodied in HttpContext, current thread, APICONTROLELR. Keep-alive,fidder View the call.

Name State Response type
Active Directory Client certificate authentication is disabled HTTP 401 Challenge
ASP mode is disabled
Forms authentication is disabled HTTP 302 Login/redirect
Windows authentication is disabled HTTP 401 Challenge
Basic Authentication (WINDOWS/BASIC) is disabled HTTP 401 Challenge
Anonymous authentication is disabled
Digest Authentication (Windows/digest) is enabled HTTP 401 Challenge
    • Basic Certification

Now all are HTTP401 challenge models, only forms are HTTP 302 login/redirect. This question about basic is very interesting, that is, when you request an HTTP 401, you will be asked to enter the user name password, enter the user name and password you entered will be sent by Base64 encoding server, in the form of basic ywrtaw46ywrtaw4=, This part of the head is authentication. View Windows Credential Manager, account password Wood has a problem, but still can not pass the verification, very sad, I try to add domain cn1\, the result ok, feel bang bang, haha, explained that the ASP. NET security model and windows have a good integration.

The process of basic mode is that the browser sends a GET request anonymously to server IIS, and IIS replies to a 401 unauthorized response that tells the client the authentication scheme (basic) in the "Www-authenticate" header and corresponding fields (realm, localhost). The browser receives the Response popup login dialog box, collects the input account password to compose the string as the authentication credential, next, the browser sends the request again, carries the authentication scheme in authorization Baotou and the user's voucher basic Ywrtaw46ywrtaw4=,iis decryption authentication , the action executes smoothly.

BASE64: Is the network common encoding used to transfer 8bit bytes of code, used in HTTP forms (including hidden form fields) and HTTP GET URLs, Base64 encoded information is not readable, but not confidential, when used to pay attention to the application scenario.

    • Digest Certification

Digest authentication is only applicable to domain mode, and if it is not available based on workgroup mode, the next step is to look at the corresponding HTTP message header via fiddler.

HTTP 401 Response:

Www-authenticate: Digest qop= "Auth",algorithm=md5-sess,nonce= "+upgraded+ V1e4fcae181b935afc3d94f30f5033141a25e3c7e4b83bd101c60cf10ea425a352c8959c8d47e643e5fc38f90cffe411be5f7a99033900ae4d ", Charset=utf-8,realm=" Digest "

Digest authentication transmits the hash code of the user credential, not the plaintext. The client first sends a GET request anonymously to the server, and the server returns a 401 response that contains a "www-authenticate" header, including the information that is carried.

Parameters Explain
Digest Certification Scheme
Realm= "Digest" Field
Algorithm Represents a hash algorithm supported by the service side, md5-sess
Nonce The unique identifier generated by the server, in general, IIS generates this nonce using the current timestamp and the header value of the requested ETag (the entity value of the requested variable).
Qop (Quanlity of Protection) IIS employs Qop to notify clients of the message protection level, with optional values including auth (authentication), Auth-int (authentication-integrity), which are limited to basic authentication, which also ensures consistency of the transmitted content.

Enter the account password again request (the response is 200 success):

Authorization: Digest username= "cn1\\she_s", realm= "Digest", nonce= "+upgraded+ V1e4fcae181b935afc3d94f30f5033141a25e3c7e4b83bd101c60cf10ea425a352c8959c8d47e643e5fc38f90cffe411be5f7a99033900ae4d ", uri="/sory.entertainment.webapi/", algorithm=md5-sess, response=" 9a6cb99fad4404cdd521e5db432f6b09 ", qop=" Auth ", nc=00000001, cnonce=" c77c05d93544b363 "

The relevant parameters are:

Parameters Explain
Username Represents the user name of the client, it appears that the user name can be intercepted
Qop End of message protection class, qop= "Auth"
Algorithm The ultimate encryption algorithm, md5-sess
Nonce is actually the server-side generated nonce
Cnonce Client-generated nonce (c for client), which can sign the request content to ensure that the content has not been tampered with, can help the client to authenticate the server (the service side can prove that the nonce, which is well suited to defend against cross-site request forgery)
Nc (nonce count) It represents the number of requests sent by the client for the same nonce, one of which is that as the number of requests increases, IIS can prevent "replay attacks" by the numbers represented by NC, which maintains the NC of each nonce, which is considered an illegitimate request if the request carries fewer NC than this.

After receiving the second request, IIS validates the request (such as the legitimacy of the NC) and then extracts the user name, nonce, and encryption algorithm from the authentication header to compute the real digest for the user name. Finally, it is compared with the digest provided in the request to confirm the correctness of the password and complete the client authentication.

TIP:

<script type= "Application/json" id= "__browserlink_initializationdata" >

{"AppName": "Firefox", "RequestID": "Ee1fc1d3f30e4b4cba937703bee3ce10"}

</script>

<script type= "Text/javascript" src= "Http://localhost:13820/69ea419b05a141aaa5111affa4bb02fe/browserLink" async = "Async" ></script>

How is this part understood, related to Jsonp?

    • Integrated Windows authentication, P610

Whether you ask Basic or Digest authentication, if you use a browser to do the client, the first visit will always need to enter in the popup box, very cumbersome, and password transmission in the network, there is a security risk, generally by adding salt to avoid. Integrated Windows authentication can be a good solution to this problem, it is the default to log on to the machine's Windows account to access the authorized resources, the user's password is included in the request to carry the security token, it is very convenient, the way eventually using the NTLM and Kerberos protocol to complete.

NTLM protocol (older): Uses the challenge/answer (CHALLENGE/RESPONSE) message Exchange Mode, and the DC domain controller holds information about the user being used. The basic process is: Step 1, the user enters the account password login host, the main opportunity to cache the password to enter the hash value, the original password will be lost. If the view accesses the server resource, it needs to send a request to the other, and the request contains a clear text representation of the user name; Step 2, the service side accepts the request, generates a 16-bit random number (called Challenge Challenge) and sends it to the client in clear text when stored. And the intent of the nonce in the digest request is exactly the same; Step 3, after the client receives the service-side challenge, encrypts it with the password hash saved in step 1, then sends the encrypted challenge to the server, step 4, after the service side receives the encryption challenge, A client-specific authentication request is sent to the DC (including, in the request, the user name, the client password after the encryption of the challenge and the original challenge); Step 5, 6,DC according to the user name to obtain the password hash, the original challenge encryption, and the server sent a challenge comparison, consistent for the verification passed, otherwise failed.

Kerberos: This thing is also a troubled brother for many years, the old see, especially every time you register windows, oh, you know. In fact, it's a more hilarious and secure authentication protocol, and the process is more complex, similar to NTLM, and contains three parts, the client, server, and KDC (Key distribution Center, in the Windows domain, where the KDC has DC). Kerberos is actually a ticket (Ticket)-based authentication method, the client to access the server side of the resources, the first to buy a service-side approved tickets. In other words, the client must buy tickets before accessing the server, waiting for the server to pass the ticket before admission, but this ticket can not be directly purchased, the first need to subscribe to warrants (and food stamps, stock call warrants similar). Both the warrant and the entry ticket to the server are sold by the KDC, feeling a variety of around ... For more information, put it on hold.

When using Windows Integrated Authentication in IIS, you will see the settings for provider, with the "Negotiate" and "NTLM" two options, which are used by default, provider include "Negotiate:kerberos", and of course can be customized. In addition, the client needs to turn on Windows Integrated authentication in IE settings-advanced, which is turned on by default. When using httpclient, you can simplify the call by using the following methods.

View Code

Can be independent of the Windows system authentication method, before doing WebForm, the forms certification is the most used, at that time also thought that the forms verification also need and windows related, especially with the form of WebForm in the related, now think very naïve, At the same time this verification can be very good with the membership. But in fact this kind of authentication method is independent, is suitable for self-maintenance user account and the password scene, is also the most project scene. Then the next introduction of how the forms certification, and strive to make their own real out of the wrong.

The process design of the forms Authentication 4 times the message exchange, the specific steps are as follows.

Step 1: The user anonymously to IIS through the browser to initiate a request, assuming that the address is "/home", it will receive a status of "302, Found" corresponding, this is a "redirect" HTTP response, it through the location header of the redirect address pointed to the login page, The previously accessed address will be the value of the query string ReturnUrl.

Step 2: After the browser accepts the request, it sends a request for the redirected address, and the login page is eventually rendered in the browser.

Step 3: After the user enters the correct user name password and submits the form, the server extracts them after receiving the request to authenticate the user, and after the authentication succeeds, it generates a security token or authentication ticket. Next, the original request address is represented by the query string ReturnURL , as another "302, Found" response to the location header, and an encrypted/signed security token as a cookie for that response.

Step 4: This cookie that represents the security token is automatically appended to the browser's subsequent request and the server uses it to authenticate the request directly. the name of the cookie, expiration policy, and the level of protection used can be controlled by configuration. In the case of disabling cookies, the security token is delivered directly as part of the URL.

TIP:

The first thing to add is that the original Forms authentication configuration is configured with the following configuration, plus [allowanonymous] on the login-related method, and then the IIS settings enable Anonymous authentication and forms authentication.

View Code

Version configuration after ASP. NET 5 has some changes, in order to integrate with the third-party authentication OAuth, do not need configuration file configuration, but by the following code configuration, if added often error.

View Code

The protection level of the cookie, which includes 6 privacy levels in the IE settings, varies in the degree to which the cookie is administered, from a cookie that is completely unreadable to read-write, to the default rating, to block third-party cookies that do not have a streamlined privacy policy.

Yesterday, chatting with colleagues, also noted that some of the project's logoff is a direct jump to the page, rather than action, so the lack of empty session and other server-side information, in the actual development is also considered a mistake point.

Prior to the authentication method, all require the password (token) to transmit in the network, in order to ensure that the password is not stolen, need to use SSL\TLS to protect the content of the transmission. It involves a lot of safety-related basics, just a brief introduction.

    1. Asymmetric encryption: Guarantees message confidentiality, involving a key pair consisting of a public key and a key.
    2. Digital signature: Ensure identity authentication, prevent repudiation non-repudiation, message consistency
    3. Digital Certificate, also known as public key Certificate, such as 12306 server root certificates required to be installed on the client, most of which are based on the V3 certificate standard, and can also be referred to as the certificate of A/d. It is actually a file that binds the public key in a key pair to a principal subject, including the version number V3, the sequence number, the signature Algorithm (md5withrsaencryption), the issuer (Issuer), valid date, principal information, subject public key and public key algorithm , and the issuer's digital signature .

TIP: What you want to say about digital certificates is that you have to separate it. Understanding, generally contains three parts, public key information, signature information and other information. And the latter both are for the former safe delivery service, in short (such as 12306 buy train ticket scene, wish everyone can buy a happy year, haha), the site by requiring users to install the root certificate of the Web site communication key to the public key to send me, but in order to ensure the security of the process, The process of providing a digital signature is required. It's like giving me the secret code and signing the FBI, and then I can use that code to communicate. This is relatively sketchy, somewhat simplified, omitting the concept of certification authority and authentication tree.

About the concept of SSL/TLS, the latter TLS (Transport layer Security) is actually the former SSL (Secure Sockets layer) Upgrade version, TLS1.0 is SSL3.1, in the IE settings, you can see the default support SSL 3.0 and TLS1.0. And HTTPS refers to the combination of HTTP and SSL/TLS, as described earlier 12306 security, is HTTPS, also known as the weak security model, then what is the strong security model? That is, when we use Net silver, we all experience the process of installing security controls and even using U-shields, which is strong security here. In simple terms, strong security refers to the server side and the client to install each other's certificates, mutual authentication, weak security, refers to the client Installation server certificate, client Authentication server. Next, we describe the process of requesting HTTPS Web sites.

Step 1: The client sends a negotiation request to the HTTPS site, including a list of cryptographic algorithms supported by the client

Step 2:https Site Select from the algorithm list the algorithm (security and efficiency tradeoff) that supports the most appropriate level of security, along with the digital certificate that is bound to the site and sent to the client.

Step 3: After the client accepts the certificate, validates the site identity by verifying that after success, a random number is generated, which is cached on the client as the session key. The client uses the encryption algorithm sent back, using the public key in the certificate to encrypt the key (session key), encrypt and send to the site, the site decryption to get Session key.

Step 4: The client and server use the session key to encrypt and decrypt using the symmetric encryption algorithm . (symmetric encryption is efficient, but key management is difficult, so the combination of the two, using asymmetric encryption to manage the key, with the key to symmetric encryption, Bang Bang)

    • Application of SSL/TLS in IIS

IIS provides support for a variety of transport protocols, including HTTP, TCPH, and MSMQ, where site-bound digital certificates are many, and most convenient is with the IIS Manager, with the following steps.

Step 1: Before you add the HTTPS binding to the target site, we need to prepare a certificate for it, either with the MakeCert.exe tool or by using IIS Manager to create a self-signed certificate. Select Server Certificate in the list of attributes for IIS, and then select Create self-signed certificate, which is the same name as the site.

Step 2: In IIS, select the site (Web site) that we specified, right-click the edit binding, add the HTTPS type on the site Bindings page and select the appropriate certificate, you can see HTTP, and HTTPS in the Browse site column. At this point you can browse the Web through two different ways, of course your custom certificate is not added to the root certificate, so when using HTTPS, the browser will display a small red fork. Later in the HttpClient section, you will also find that we can easily invoke the server certificate by setting, skipping client authentication, but not recommended.

Common calls to a site can be made via HTTP and HTTPS two, but specific to a call requires a tradeoff between "security" and "performance", but the authentication process must be HTTPS, setting the specified action to [Requirehttps], Then it can only be accessed through the HTTPS protocol. This feature is actually a authenticationfilter provided by MVC, which, if it is a normal request, redirects the request to the appropriate address for HTTPS. Here you will notice that one problem is that Requiredhttps is the concept under MVC, so is there a corresponding concept in WEBAPI? This can be handled by a custom authentication filter.

View Code

Generally speaking, the user authentication of the Web application is done by itself, by storing the user name and password and verifying, but this way in the current Internet scene there will be two major problems: the user needs to register a different account, remember and use very troublesome, for the application provider, a large number of certification system will be a lot of effort. The emergence of a third-party authentication model based on the OAuth2.0 (Open Authentication 2.0) is a good solution to this pain point, thanks to Google, a trusted IT service provider. OAuth is the definition of a protocol that helps the owner of a resource authorize a third-party app to store protected resources on his behalf without providing its own credentials .

Obtain a third-party app authorized by the resource owner the access token issuance process involves a number of different roles, instead of the licensor credentials, but a security token called access token. The following is a brief introduction to a simple example by the master Jiang. For example, we have developed an app that integrates Sina Weibo certification for the release of discounted product information, and after authorization it can call Sina Weibo's webapi to get the user's e-mail address and post the corresponding discount message. So the role of OAuth in this scenario is that the user authorizes the app to call Sina Weibo's Webapi in its own name to get its own email address, involving 4 roles: The resource owner, typically the end user, and the client application, which requires access to the application that the resource owner authorizes and ultimately accesses the protected resource; The server that eventually hosts the resource, one for a WEBAPI, an authorization server that authenticates users and clients, and grants access tokens to client applications in the context of a user's authorization, in the scenario described earlier, both of which are Sina Weibo.

In general, if you need to develop an application for a third-party authentication service, you need to register the application with the corresponding certification service provider, get Appid/appsecet after success (not necessarily the same name), and in fact each item in the actual work is often appid. Common, we can apply for Windows service https://account.live.com/developers/applications/, apply after application can get ClientID and Clientsecret, and set the redirected domain name. The point here is to remind you that this redirection setting can be multiple and must correspond to the redirect settings for each of your requests, and Windows Live will not be able to provide a service error once it is not set.

The process here is similar to Kerberos authentication, where the client obtains the authorization credentials, then buys the access credentials, and finally accesses the resources. Authorization Grant (Abbreviation AG) contains 4 types: implicit, omitted to obtain the AG process; Authorization code, Standard mode, this AG is an authorization code; After the two are not very valuable, it is not introduced.

    • Implicit Authorization Grant abbreviated IMP, examples are as follows (need to modify host), P640, the more troublesome part.

The model, by getting the accesstoken of the current request, then calls the API (HTTPS://APIS.LIVE.NET/V5.0/ME) provided by Windows Live Connect. However, prior to this, if the user did not log in to Windows Live, then the first jump to the landing page, the completion of the GetProfile call after the JSON format string is displayed in the browser. The core here is that we write accesstoken into a cookie through Authenticateattribute, which is similar to the forms authentication, but from a security standpoint, using cookies to carry security tokens can cause what is known as "cross-site request forgery CSRF, Cross-site Request Forgery "security issue, so use the Htto header as a security token carrier more reasonable. The Challengeasync of the Iauthenticationfilter interface is used to send a "challenge" response to the client during the authentication process, if Accesstoken does not exist, just like windowlive authorization page redirection, parameters ( Response-type, Redirect_uri, client, scope) are provided in query string form. The method Executeactionfilterasync in Iactionfilter is used to write accesstoken to the cookie. The code looks like this:

View Code

TIP:

Location is the built-in object that manages the address bar inside JavaScript, such as location.href to manage the URL of the page, and Location.href=url to redirect the page directly to the URL. Location.hash can then be used to get or set the label value of the page. For example, http://domain/#admin location.hash= "#admin". Using this attribute value can make a very meaningful thing. Simply put, the "#" followed by the content, similar to the query string.

Window.location.hash This property can be read and writable. When read, it can be used to determine if the state of the Web page changes, and when it is written, it creates an access history without reloading the page.

    • Authorization Code Authorization Grant (simplified AC)

There are two issues with the IMP described earlier, one of which is that the authorization server does not authenticate the client application because the request to access token provides only the ClientID of the client app and no Clientsecret; Tokens are issued separately to the client app by the authorization server and should be invisible to others (including the grantee who owns the resource being accessed). The IMP type authorizes the client to run in a purely client-side context environment, where the user of the AC type runs the server's application, such as a controller in an MVC application.

Step 1: The client sends a request to the authorization server to obtain the authentication Code (call warrant), and the requested address and parameters are similar to Imp.

Name of parameter Explain
Response_type Represents the type of object that the request wants to get, where we want to get the authorization Code
Redirect_uri Indicates that the authorization server obtains the user authorization and completes the user authentication after the redirect the address, the AC is the query string way append
client_id CLINT_ID for authorized client applications
Scope Represents the scope of authorization, depending on the specific set of permissions required

Step 2: The client uses AC to obtain access tokens from the authorization server, typically a POST request, which includes the following parameters:

Name of parameter Explain
Client CLINT_ID for authorized client applications
Client_secret The identifier corresponds to the Clientsecret
Redirect_uri The redirect address specified before getting AC
Grant_type With the authorization grant type, the value is "Authorization_code"

After a request is accepted by the authorization server, in addition to validating the client with ClientID and secret, the redirect address is checked for consistency and a accesstoken is generated after completion. Messages include: Token_type,bearer;expires_in,3600;scope,wl.signin Wl.basic;access_token;authentication_token.

For security reasons, access token has an expiration time limit, and the authorization server returns a long-lasting security token that can be used to retrieve the AC token when it expires, using it to add "wl.offline_access" to the scope, The relevant code is shown below.

By the way, the actual use, do not need so troublesome, you can see in Project App_start Startupauth, you can see the Microsoft settings, only the input corresponding ClientID and Clientsecret.

TIP:

A question, why am I setting www.sory.com can access to, and I did not apply for that domain and bind IP?

Webapi uses the rest style, the browser as the execution context client JS application is the main consumer, but the "same-origin policy" restricts the cross-site invocation of JS, which will cause WEBAPI to access resources across domains, then it will be "a misnomer", how to solve this problem? In the latter sense, there are two main ways of JSONP and Cros specification.

As an Internet tool, the browser provides a hosted and running environment for client applications. This application is a JavaScript program, because the JS script is not all worth the trust, so the JS run is limited to a sandbox sandbox. The same origin policy is the most basic security policy, is the basis of browser security, it restricts the script from the a site can only manipulate the DOM of a page, the cross-domain operations B site resources will be rejected. Same origin requires 3 aspects of the same: host name (domain name/subdomain or IP address); Port number; network protocol (SCHEMA). It should be noted that for a JS script, the "source" is independent of the address it stores, and depends on the page that the script is loaded on, JSONP takes advantage of this feature. In addition to the <script> tags, HTML has other tags with src attributes (<iframe><link>) that have the ability to load resources across domains, for these tags, Each load involves a GET request. The same-origin policy is primarily for AJAX requests, which mainly limit the Ajax requests sent through XMLHttpRequest, and if it is a different source address, the browser will refuse to read the returned content.

A small example of cross-domain access, an MVC application that calls a service for a WEBAPI application, when both are under different interfaces.

View Code

Error message for cross-domain invocation: XMLHttpRequest cannot load http://www.sory.com/Sory.Entertainment.WebAPI/api/contact. No ' Access-control-allow-origin ' header is present on the requested resource. Origin ' http://localhost:26829 ' is therefore not allowed access.

    • Jsonp Way

As mentioned before, the source of the JS script has the load page decision, not the storage address. For a section <script> tag src attribute added in the JS script, it is the same as the current page. For the previous example, the rendering of the contact list can be defined separately in the Listcontacts function, and the address of the WEBAPI is placed in the SRC attribute of the <script> tag for indirect invocation.

Namespace: System.Net.Http simplifies the invocation pattern of our original HttpWebRequest.

Basic use:

Httpresponsemessage response = client. Getasync ("http://..."). Result;

Cw (response. Content.readasasync<datetime> (). Result.tostring ();(The result here is very similar to the await, task<long>)

    • Using HttpClient to invoke the WEBAPI under Basic authentication

Note here, first in NuGet to get httpclient related components, which depend on the MICROSOFT.BCL library, some extension methods need to add the appropriate namespace, their own half a day readasync<t> this generic method was not found, can also write their own, relatively simple and convenient.

View Code
    • Using HttpClient to invoke WEBAPI under Forms authentication

At Froms authentication, we first need to request the login page, send the username password as token to the server, then get the "Set-cookie" attribute in the server response information head, then get the key ". Aspxauth "Cookie information, which is the token of the server-side and client communication. Then in the request that you really need, attach the token (with formurlencodecontent packaging, this kind of actual gas is the original mediatype= "application/x-www-form-urlencoded" role), Also note that it is necessary to initialize the Cookiecontainer in Httpclienthandler.

View Code

Resources:

    1. Jing Jinnan. The ASP. NET Web API 2 framework reveals [M]. Beijing: Electronic Industry press, 2014.
    2. (Mei) Galloway. ASP. NET MVC 5 Advanced Programming (5th Edition) [M]. Beijing: Tsinghua University Press, 2015.

Quick Start Series--webapi--01 Basics

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.