-
Notifications
You must be signed in to change notification settings - Fork 0
/
RapidApiAuthenticationService.cs
62 lines (53 loc) · 2.01 KB
/
RapidApiAuthenticationService.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
using System.Configuration;
using Microsoft.Azure.WebJobs.Host;
namespace BikeTheT
{
public class RapidApiAuthenticationService
{
private const string RapidApiConfigSetting = "RapidApiSecret";
private const string RapidApiCustomHeader = "X-Mashape-Proxy-Secret";
/// <summary>
/// Determine if there is an authentication error, and if so return it.
/// </summary>
/// <param name="req">The incoming request</param>
/// <returns>500 status code if no secret is configured
/// 401 status code if the consumer provides the wrong credentials
/// null if the user provided correct credentials</returns>
public HttpResponseMessage GetAuthenticationError(HttpRequestMessage req)
{
var secretInRequest = GetRapidApiSecretInRequest(req);
var correctSecret = GetCorrectRapidApiSecret();
if (string.IsNullOrEmpty(correctSecret))
{
return req.CreateErrorResponse(HttpStatusCode.InternalServerError, "No secret available");
}
if (!correctSecret.Equals(secretInRequest))
{
return req.CreateErrorResponse(HttpStatusCode.Unauthorized, "Credentials are not valid");
}
return null;
}
private string GetRapidApiSecretInRequest(HttpRequestMessage req)
{
var answer = string.Empty;
if (req.Headers.Contains(RapidApiCustomHeader))
{
IEnumerable<string> headerValues = req.Headers.GetValues(RapidApiCustomHeader);
answer = headerValues.FirstOrDefault();
}
return answer;
}
private string GetCorrectRapidApiSecret()
{
return ConfigurationManager.AppSettings.Get(RapidApiConfigSetting);
}
}
}