-1

I came accross to work with WCF restful API's with security tokens Json Web Token (JWT). I've created registration and login (created jwt here) service for user. Now I'm unsure about how to authenticate JWT on each request of user while accessing data. Here is the link that I followed for creating JWT.

https://www.c-sharpcorner.com/article/wcf-service-with-jwt-token/

here is the response object with user info and JWT

{  
  "response": "true",  
  "UData": {  
    "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjoibWxpYXFhdDQxNUBnbWFpbC5jb20iLCJwYXNzIjoiMzMzIiwiaWF0IjoiMTU5MzYwNTY0MCJ9.JAeBj0VAJJtCVwbTMrgz_F6ZQWdjYcZFUsif5qLHPGo",  
    "authenticated": true,  
    "UserID": "4",  
    "FullName": "Hellen Waock",  
    "UNo": null,  
    "Email": "hellenwaockofficial@gmail.com",  
    "timestamp": "2020-07-01T17:14:00.355758+05:00"  
  }  
}

Now I'm creating a service for get_AllUsers, but I want to consume JWT, while accessing get_AllUsers. Another point to ask, In the above link I followed, I found a line of code to paste in webconfig, I pasted that in various tag but got some error, anybody could help about where to paste that line. Thanks in advance

Rameez Javed
  • 139
  • 3
  • 9
  • Can you post your error? – Ding Peng Jul 02 '20 at 10:02
  • *In the above link I followed, I found a line of code to paste in webconfig, I pasted that in various tag but got some error* - I'm afraid hardly anyone will read the linked article to find out which line you probably mean and which error it could have caused. Please add ALL information that belongs directly to your question INTO the question itself. Show us what line and where you put it and what error it caused. – jps Jul 02 '20 at 18:00

1 Answers1

1

You can decode the obtained JWT, after decoding you will get the data before encoding, and then you can verify this data.In your project, you can decode the obtained JWT before calling get_AllUsers, and then verify the decoded data.

The JWT decode method in the link is as follows:

public string DeJwt(string token) { 
    byte[] secretKey = Base64UrlDecode("Hi");
    string Json = Jose.JWT.Decode(token, secretKey);
    return Json;
}

The returned json is the decoded data, including username and password, you can verify it.

Jose-JWT has other encode and decode methods. The example in the link is just one of them. You can refer to the link below for more information:

https://github.com/dvsekhvalnov/jose-jwt

Is the error received in web.config because the following line of code was added?

<serviceAuthorization serviceAuthorizationManagerType="WcfService1.DistributorValidator, WcfService"/>

This line of code should be added to the behavior of the service as shown below:

    <serviceBehaviors>
        <behavior name="ServiceBehavior">
            <serviceAuthorization serviceAuthorizationManagerType="Demo_rest_ConsoleApp.DistributorValidator, Demo-rest-ConsoleApp"/>
            <serviceMetadata httpGetEnabled="true"/>
        </behavior>
    </serviceBehaviors>

UPDATE

In WCF, you can intercept all requests by implementing the IDispatchMessageInspector interface.

public class ServerMessageLogger : IDispatchMessageInspector
    {
        public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
        {

            return null;
        }

        public void BeforeSendReply(ref Message reply, object correlationState)
        {
           
        }
    }

You can process all incoming requests in the AfterReceiveRequest method.

Finally you need to add ServerMessageLogger to the service behavior and apply to the service.

If you are not sure how to add ServerMessageLogger to the service, you can refer to this link:

How to enable Cross-Origin Resource Sharing in .Net Console Application WCF Service?

Ding Peng
  • 3,702
  • 1
  • 5
  • 8
  • Thanks, but can you please let me know how to track all the request globally (except user login request as it is the start of user's jwt), as every request is to be filtered and if found correct(authorized) then data access will be given else response will be 401, should I user Global.asax and add on application start? – Rameez Javed Jul 03 '20 at 07:03
  • 1
    @jps You are right,The default JWT is indeed not encrypted, I have modified my reply. – Ding Peng Jul 03 '20 at 08:04
  • decoded,got user, pass & iat, where to verify this? ```public static string GetJwt(string user, string pass) { byte[] secretKey = Base64UrlDecode("Hi"); DateTime issued = DateTime.Now; var User = new Dictionary() { {"user", user}, {"pass", pass}, {"iat", ToUnixTime(issued).ToString()} }; string token = JWT.Encode(User, secretKey, JwsAlgorithm.HS256); return token; } ``` – Rameez Javed Jul 03 '20 at 11:08
  • above mentioned code is to confirm whether this token is stored in dictionary, and on verification we can compare the decoded information with dictionary elements? or we have to make a database query (this approach doesn't satisfy me). – Rameez Javed Jul 03 '20 at 11:15
  • After decoding the JWT, you can verify the JWT according to your requirement. For example, you mentioned storing JWT in a dictionary. This requires you to create a dictionary and store it. The verification method that I think of is that you can pass the UserID and JWT each time the client calls, and compare the UserID obtained after decoding the JWT with the UserID passed in. If the two UserIDs are the same, the verification is passed. – Ding Peng Jul 06 '20 at 01:36
  • Yes bro, but It cleared to me after having research of almost a day. Anyhow Thankyou, Don't know who these people are who degrade the question as its clear with followed link. – Rameez Javed Jul 15 '20 at 07:49