Reputation: 41
I wanted to remove authorization, that is to remove bearer token authentication for my web API application for swagger alone. And authorization should work as usual for rest of the console applications like postman.If so how can it be achieved for swagger alone. Provided I'm using the swashbuckle NuGet package for my application.
Upvotes: 3
Views: 2464
Reputation: 41
Below is the code i have tried, I have used custom authorization for swagger and other urls, It is working fine in local environment but my api is not accessible by other api's post deployment in https server, getting unauthorized error.
public class CustomAuthorization : AuthorizationFilterAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
Uri currentUrl = HttpContext.Current.Request.UrlReferrer;
if(currentUrl != null)
{
if (currentUrl.Segments.Contains("swagger"))
{
string accessToken = "";
using (var client = new HttpClient())
{
var form = new Dictionary<string, string>
{
{"grant_type", "password"},
{"username", "user"},
{"password", "password"},
{"scope","scope"}
};
string url = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority);
var tokenResponse = client.PostAsync(url + "/token", new FormUrlEncodedContent(form)).Result;
var token = tokenResponse.Content.ReadAsAsync<AuthorizationToken>(new[] { new JsonMediaTypeFormatter() }).Result;
accessToken = token.access_token;
HttpContext.Current.Request.Headers.Add("Authorization", "Bearer " + accessToken);
}
}
}
else
{
var principal = actionContext.RequestContext.Principal as ClaimsPrincipal;
if (!principal.Identity.IsAuthenticated)
{
AuthorizationMessage autho = new AuthorizationMessage();
autho.Message = "Missing access credentials.";
autho.Type = "Unauthorize";
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized, autho);
}
}
}
class AuthorizationMessage
{
public string Type { get; set; }
public string Message { get; set; }
}
}
Upvotes: 1