Asp.net mvc 5 Access to VB, mvcvb
Access to official documents is php, and the code copied several times on the internet is c #, that is, there is no vb. Today, I entered this pitfall to implement access authentication for the vb version.
First, write the access model according to the development document. Create a Model in the Models folder
Public Class WeChatRequestModel ''' <summary> ''' encrypted signature ''' </summary> Public Property signature $ ''' <summary> ''' timest''' </summary> Public Property timestamp $ ''' <summary> ''' random number ''' </summary> Public Property nonce $ ''' <summary> ''' random string ''' </summary> Public Property echostr $ End Class
After the model is created, create a new Controller.
For authentication, nonce, Token, and timestamp are sorted, and SHA1 is compared with signature. As a String constant, Token is written based on the Token entered during application.
Const Token = "the Token you applied"
The remaining code is to translate the php code. Be sure not to use outdated members such as FormsAuthentication, so that you do not need to rewrite the code when migrating to asp.net core in the future:
1 Private Function SHA1$(str$) 2 Return Encoding.UTF8.GetString(System.Security.Cryptography.SHA1.Create().ComputeHash(Encoding.UTF8.GetBytes(str))) 3 End Function 4 Private Function CheckSignature(data As WeChatRequestModel) As Boolean 5 Return data.signature = SHA1(String.Join("", Aggregate s In {data.nonce, Token, data.timestamp} Order By s Into ToArray)).ToLower() 6 End Function 7 <HttpGet> 8 Public Sub Authenticate(data As WeChatRequestModel) 9 If CheckSignature(data) AndAlso Not String.IsNullOrEmpty(data.echostr) Then10 Response.Write(data.echostr)11 Response.End()12 End If13 End Sub