当前位置:网站首页>WCF restful+jwt authentication
WCF restful+jwt authentication
2022-06-21 09:57:00 【panda_ two hundred and twenty-five thousand and four hundred】
List of articles
- Preface
- One 、JWT What is it? ?
- 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
- 2. front end - Users need to carry token, Send it to the server
- 3. Back end - Users need to carry token, Send it to the server
- 4. The server receives token after , adopt jwt Yes token Check for timeout 、 Is it legal
- Two 、 Verification interface
- summary
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 :
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

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

Two 、 Verification interface
First, we add a method to verify identity 
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 

then , When registering a route , Make a change :

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
边栏推荐
猜你喜欢

Les nouveaux programmeurs optimisent une ligne de code lundi et sont exhortés à se retirer mercredi?

燎原之势 阿里云数据库“百城聚力”助中小企业数智化转型

The execution process before executing the main function after the DSP chip is powered on

Stm32mp1 cortex M4 Development Chapter 11: expansion board buzzer control
![[actual combat] STM32 FreeRTOS porting series Tutorial 4: FreeRTOS software timer](/img/16/ad38288689f629106a19a0b8defea2.jpg)
[actual combat] STM32 FreeRTOS porting series Tutorial 4: FreeRTOS software timer

【实战】STM32MP157开发教程之FreeRTOS系统篇3:FreeRTOS 计数型信号量

The memory allocation of the program, the storage of local const and global const in the system memory, and the perception of pointers~
![The most authoritative Lei niukesi in history --- embedded Ai Road line [yyds]](/img/0c/95930c7c49c5ebeee9c179c035b317.jpg)
The most authoritative Lei niukesi in history --- embedded Ai Road line [yyds]

stm32mp1 Cortex M4开发篇12:扩展板震动马达控制

The spingboot microservice is packaged into a docker image and connected to the database
随机推荐
记一次协程环境下类成员变量污染的问题
R language obtains help information of global, package and function: use the rsitesearch function to search the information of the specified package or function in the R community help manual and arch
[cloud native | kubernetes] kubernetes configuration (XV)
信号功率谱估计
ENGRAIL THERAPEUTICS公布ENX-101临床1b研究正面结果
Concurrency - condition variable
R language through rprofile Site file, user-defined configuration of R language development environment startup parameters, shutdown parameters, user-defined specified cran local image source download
如何选择嵌入式练手项目、嵌入式开源项目大全
Telecommuting Market Research Report
Embedded software project process and project startup instructions (example)
R language factor variable type: use factor function to convert string vector to factor vector, and use as The factor function converts a factor vector into a string vector and uses as The numeric fun
TC software detailed design document (mobile group control)
Underlying principle of Concurrency: thread, resource sharing, volatile keyword
Audio and video synchronization knowledge points you must pay attention to:
[practice] STM32 FreeRTOS migration series tutorial 5:freertos message queue
Audio and video format introduction, encoding and decoding, audio and video synchronization
Vuforia引擎支持的版本
How to be an interesting person
Stm32mp1 cortex M4 development part 10: expansion board nixie tube control
Inner class