llasarov
llasarov

Reputation: 2111

Handle authentication redirect when consuming REST service in .NET

In a desktop application I'm consuming a REST service.

The service implements custom authentication. When the URI is invoked in the browser (GET request) the authentication page appears in the browser and you have to enter your credentials. After successful authentication you get forwarded back to the initial address. The GET request is sent again by the browser and you receive the service response (JSON document).

My goal is every time the service is invoked and the user credentials are not provided (coockie after successful authentication), the login mask to be shown in a web control inside the desktop app and not in a new browser window.

My implementation is quite primitive:

var proxy = new WebClient();
var str = proxy.DownloadString("https://mycompany.net/myservice/Entity/123");

My problem is that in case the user credentials are not provided, the request doesn't throw an exception neither an event is fired. But in the response string I see the HTML content of the authentication page. So the redirection happens somehow internally and I could not know whether the returned string is the JSON object or some HTML page.

Can you tell me whether I use the right class for this task and how can I hook the request in order to know that the authentication is to be provided?

Upvotes: 0

Views: 1252

Answers (1)

MvdD
MvdD

Reputation: 23436

What you're doing is using a web application authentication mechanism (redirect browser to login page) for a web service, which will lead to the problems you are experiencing. You would have similar problems if you tried to consume this service from a mobile client or from JavaScript (AJAX call).

You don't state whether you control the REST service, but if you do, you should change the authentication mechanism to expect a bearer token and return a 401 Unauthorized response when the header is missing.

The client (desktop application in your case) should authenticate the user and get a JWT token to send along in the Authorization header in the REST service call.

Upvotes: 1

Related Questions