Nginx cluster SSL Certificate WebApi authentication, nginxwebapi
Directory
1 General idea... 1
2 Nginx cluster SSL Certificate WebApi authentication... 1
3 AuthorizeAttribute class... 2
4. generate an SSL certificate using Openssl... 2
5. Compile. NET WebApi 2
6. Deploy webapis to three PCs in the LAN... 5
7. Nginx cluster configuration and setup... 6
8 running results... 7
9 Conclusion... 9
1. General idea
L SSL Certificate WebApi authentication for Nginx Clusters
L AuthorizeAttribute class
L Openssl generate an SSL Certificate
L compile. NET WebApi
L deploy WebApi to three PCs in the LAN
L Nginx cluster configuration and Setup
L running result
L Summary
2. WebApi authentication for SSL certificates in Nginx Clusters
The Nginx cluster can implement Http Basic-based identity authentication. By entering the user name and password and passing through the ssl https protocol, effective identity authentication can be achieved and the corresponding WebApi can be accessed. Of course, the access method is not only based on Http Basic, but also through the token, or based on redis to achieve single-point login access, this document describes how to implement simple cluster Authentication Based on Http Basic Authentication and secure HTTPS communication.
The main structure diagram described in this article is as follows:
Enter the user name and password on the client and access the Nginx URL: Ingress. The WebApi Authentication Architecture of the SSL certificate in the Nginx cluster is shown in:
Disadvantages of BASIC Authentication
HTTP basic authentication is designed to provide simple user authentication functions. The authentication process is simple and clear, and is suitable for authentication on the configuration page of routers used by systems or devices with low security requirements, almost all adopt this method. The disadvantage is that there is no flexible and reliable authentication policy, for example, the domain (domain or realm) authentication function cannot be provided, and the BASE64 encryption strength is very low. Of course, the basic HTTP authentication system can also be combined with SSL or Kerberos to implement a high-security (relative) authentication system.
3 AuthorizeAttribute class
When you use AuthorizeAttribute to mark an operation method, access to the operation method is limited to users who have been authenticated and authorized.
If you use this feature to mark a controller, all operation methods in the Controller will be restricted.
The Authorize feature allows you to restrict authorization to predefined roles or individual users. This allows you to strictly control who has the right to view any page on the site.
If an unauthorized user attempts to access the method marked with the Authorize feature, the MVC Framework returns the 401 HTTP status code.
If the site is configured to use ASP. NET form authentication, the 401 status code will cause the browser to redirect the user to the logon page.
Derived from AuthorizeAttribute. to derive from the AuthorizeAttribute class, the derived type must be thread-safe.
Therefore, do not store the status in the type instance itself (for example, in the instance field) (unless the status is applied to all requests), but store the status in the Items attribute by request, this attribute can be accessed by passing it to the context object of AuthorizeAttribute.
For specific features, visit:
Https://msdn.microsoft.com/zh-cn/library/system.web.mvc.authorizeattribute.aspx
4. generate an SSL certificate using Openssl
See Nginx cluster SSL Certificate web API microservice
Http://www.cnblogs.com/yongfeng/p/7921905.html
5. Compile. NET WebApi
Server:
CustomAuthorizeAttribute. cs
Using System. web. http; using System. web. http. controllers; namespace SSLWebApi. controllers {public class CustomAuthorizeAttribute: AuthorizeAttribute {public override void OnAuthorization (HttpActionContext actionContext) {// determine whether the user is logged on if (actionContext. request. headers. authorization! = Null) {string userInfo = System. text. encoding. default. getString (System. convert. fromBase64String (actionContext. request. headers. authorization. parameter); // user verification logic if (string. equals (userInfo, string. format ("{0 }:{ 1}", "zhyongfeng", "123456") {IsAuthorized (actionContext);} else {HandleUnauthorizedRequest (actionContext );}} else {HandleUnauthorizedRequest (actionContext) ;}} protected override void HandleUnauthorizedRequest (System. web. http. controllers. httpActionContext actionContext) {var challengeMessage = new System. net. http. httpResponseMessage (System. net. httpStatusCode. unauthorized); challengeMessage. headers. add ("WWW-Authenticate", "Basic"); throw new System. web. http. httpResponseException (challengeMessage );}}}
BaseController. cs
Using System. web. http; namespace SSLWebApi. controllers {// <summary> // BaseController inherits the BaseController and requires authentication. // </summary> [CustomAuthorize] public class BaseController: ApiController {}}
UserController. cs
Using System. net; using System. web. http; namespace SSLWebApi. controllers {[RoutePrefix ("api/User")] public class UserController: baseController {// <summary> /// obtain the current user information /// </summary> /// <param name = "msg"> </param> /// <returns> </returns> [HttpPost] [Route ("PostMessage")] public string PostMessage ([FromBody] string msg) {return string. format ("the current input message is: {0}", msg);} [Route ("GetMachine")] public string GetMachine () {string AddressIP = string. empty; foreach (IPAddress _ IPAddress in Dns. getHostEntry (Dns. getHostName ()). addressList) {if (_ IPAddress. addressFamily. toString () = "InterNetwork") {AddressIP = _ IPAddress. toString () ;}} return string. format ("the current IP address for WebApi deployment is: {0}", AddressIP );}}}
Client:
Program. cs
Using System; using System. IO; using System. net; using System. text; namespace SSLWebApiClient {class Program {static void Main (string [] args) {for (int I = 0; I <10; I ++) {// Authorization string url =" https://zhyongfeng.com/api/user/GetMachine "; ServicePointManager. serverCertificateValidationCallback = delegate {return true ;}; HttpWebRequest req = (HttpWebRequest) WebRequest. create (url); NetworkCredential credential = new NetworkCredential ("zhyongfeng", "123456"); req. credentials = credential; HttpWebResponse response = (HttpWebResponse) req. getResponse (); Stream responseStream = response. getResponseStream (); StreamReader streamReader = new StreamReader (responseStream, Encoding. UTF8); string html = streamReader. readToEnd (); Console. writeLine (html);} Console. read ();}}}
6. Deploy webapis to three PCs in the LAN
Deploy webapis to the following three PCs: 10.92.202.56
7. Configure and build an Nginx Cluster
Access the Server Load balancer cluster through the self-built domain name zhyongfeng.com: 80, access C: \ Windows \ System32 \ drivers \ etc \ hosts, and add the following "Custom Domain Name of the local IP Address ":
10.93.85.66 zhyongfeng.com
Nginx cluster configuration:
#user nobody;worker_processes 1;events { worker_connections 1024;}http { include mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 65; #server { # listen 80; # server_name localhost; # location / { # root html; # index index.html index.htm; # } # error_page 500 502 503 504 /50x.html; # location = /50x.html { # root html; # } #} upstream zhyongfeng.com { server 10.92.202.56:560; server 10.92.202.57:570; server 10.92.202.58:580; } server { listen 80; server_name zhyongfeng.com; rewrite ^(.*)$ https://$host$1 permanent; } # HTTPS server # server { listen 443 ssl; server_name zhyongfeng.com; ssl_certificate server.crt; ssl_certificate_key server_nopass.key; # ssl_session_cache shared:SSL:1m; # ssl_session_timeout 5m; # ssl_ciphers HIGH:!aNULL:!MD5; # ssl_prefer_server_ciphers on; location / { proxy_pass http://zhyongfeng.com; } }}
Run CMD:
D:\DTLDownLoads\nginx-1.10.2>start nginxD:\DTLDownLoads\nginx-1.10.2>nginx -s reload
8 running results
Directly access the domain name running result:
Soap ui call running result:
Start the client. The authentication result is as follows:
9 Summary
During HTTP Communication, the HTTP protocol defines the basic authentication process to allow the HTTP server to perform a user ID card on the WEB browser, when a client sends a data request to the HTTP server, if the client is not authenticated, the HTTP server verifies the user name and password of the client through the basic authentication process to determine whether the user is legal. After receiving the authentication requirements of the HTTP server, the client prompts the user to enter the user name and password, and then encrypts the user name and password with BASE64.
Based on the SSL protocol, Nginx uses http basic authentication to implement simple access to webapis, achieving Cluster load balancing. Through simple design, the application on the LAN is sufficient. Of course, there are many identity authentication methods, and redis and token can be used. WebApi is encrypted Based on the SSL protocol data transmission. Combined with http basic, the communication security is guaranteed.
Source code download:
Http://download.csdn.net/download/ruby_matlab/10141134
PDF download:
Webapiid verification token of the sslcertificate in the nginxcluster