当前位置:网站首页>WCF restful+jwt authentication

WCF restful+jwt authentication

2022-06-21 09:57:00 panda_ two hundred and twenty-five thousand and four hundred


Preface

I've already introduced restful style wcf, This article will introduce , call restful Content of authority authentication . Interface called at , For the sake of safety , It is always necessary to authenticate the request , To prevent some illegal operations .


Tips : The following is the main body of this article , The following cases can be used for reference

One 、JWT What is it? ?

Json web token (JWT) Is a kind of implementation based on the JSON Open standards for ((RFC 7519). The token Designed to be compact and safe , Is the most popular cross domain authentication solution .JWT The declaration of is generally used to pass the authenticated user identity information between the identity provider and the service provider , To get resources from the resource server , You can also add some additional declaration information that other business logic requires , The token It can also be used directly for authentication , It can also be encrypted .
JWT The composition of the
The first part is what we call the head (header), The second part is called load (payload, Similar to what is carried on an aircraft ), The third part is visa (signature).
I won't go into details about others , Very detailed online , This is the whole process :
 Insert picture description here

Two 、 How to use JWT Authentication

1. front end - After the user logs in successfully , Server through jwt Generate a random token To the user

The code is as follows ( Example ):

 var str = {
     "UserName": "test", "Pwd": "123456"}
jQuery.support.cors = true;
$("#login").click(function () {
    
                $.ajax({
    
                    url: "http://localhost:5393/RestCustomerService.svc/Login",
                    data: JSON.stringify(str),
                    method: "POST",
                    success: function (data) {
    
                        if (data.Success) {
    
                            // For the sake of simplicity , take token Stored in global variables .
                            window.token = data.Token;
                            alert(" Login successful ");
                        } else {
    
                            alert(" Login failed :" + data.Message);
                        }
                    }
                });
            });
JWT toke:
eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiLnrb7lj5HogIXkv6Hmga8iLCJpYXQiOjE2MzIxODQ5NzguMCwiZXhwIjoxNjMyMTkyMTc4LjAsImF1ZCI6Imh0dHA6Ly9leGFtcGxlLmNvbSIsInN1YiI6IkhvbWVDYXJlLlZJUCIsImp0aSI6IjIwMjEwOTIxMDg0MjUyIiwiVXNlck5hbWUiOiJMT05HLlpIQU5HIiwiVXNlclB3ZCI6ImphY2sxMjM0NTYiLCJVc2VyUm9sZSI6IkhvbWVDYXJlLkFkbWluaXN0cmF0b3IifQ.2TbYJdO8apLRm7PIfsYGapvjiwj1tI1kyAwHDY_nhuA 
 
  
 
 

2. front end - Users need to carry token, Send it to the server

The code is as follows ( Example ):

 function HttpPostEx() {
    
               var str = {
     "ApplicationId": 12, "ApplicationName": "JSCC_NMCA", "FromUsers": "TEST", "ToUsers": "ToUsers01", "CcUsers": "CcUsers01", "Subject": "Subject01", "Contents": "Contents01", "Folio": "Folio01", "LinkAddress": "LinkAddress01" };
               jQuery.support.cors = true;
               $.ajax({
    
                   type: "POST",
                   url: "http://localhost:5393/RestEmailService.svc/AddEmail",
                   data: JSON.stringify(str),
                   cache: false,
                   dataType: "json",
                   contentType: "application/json",
                   beforeSend: function (xhr) {
    
                    // take token Send it to the server for verification .
                       xhr.setRequestHeader("Authorization", window.token);
                   },
                   success: function (data) {
    
                       alert("star03");
                       alert(data.ResultEx.length);
                       alert(JSON.stringify(data.ResultEx));
                   },
                   complete: function (xhr) {
    
                   },
                   error: function (XMLHttpRequest, textStatus, errorThrown) {
    
                       alert("error(HttpPostEx):" + errorThrown);
                   }

               });

           }

3. Back end - Users need to carry token, Send it to the server

 Insert picture description here

4. The server receives token after , adopt jwt Yes token Check for timeout 、 Is it legal

 Insert picture description here

Two 、 Verification interface

First, we add a method to verify identity
 Insert picture description here
then , In each interface , Add the statement of authority authentication , Is it too annoying , It can be done by WebServiceHostFactory In the context of intercepting requests in Authorization Achieve
 Insert picture description here
 Insert picture description here

then , When registering a route , Make a change :
 Insert picture description here
 Insert picture description here


summary

Before the cross domain call, the front end used jsonp, But jsonp Cannot be in http header Inner transmission Authorization Information , It is troublesome to send by address , Front end use jQuery.support.cors = true Solve this problem .
You can also use Redis Cache the user's identity information to reduce the pressure of repeated authentication on the server , Record every bit of it

原网站

版权声明
本文为[panda_ two hundred and twenty-five thousand and four hundred]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/172/202206210951058138.html

随机推荐