Block server-to-server or Postman calls to ASP.NET Core 3.1 API - asp.net-core

I have a ASP.NET Core 3.1 API where I have not used CORS. As I understand, CORS is a browser thing. And as my ajax calls from another site on another origin is blocked to the API endpoints (which is great), I can still reach the same endpoints by using Postman or a HttpClient and GetAsync() calls.
My question is of it's possible to also block server-to-server calls (or Postman calls) to my API? Or like CORS, only allow certain origins?
Most of my endpoints are protected by a bearer JWT token, but I have an anonymous endpoint that I would like to let only origins I control (or can configure) to have access to that anonymous API.

I solved it after i bumped in to this post on stackoverflow:
How do you create a custom AuthorizeAttribute in ASP.NET Core?
I simply made a custom Authorize attribute [ApiAuthorize()], that I call this way:
[ApiController]
[ApiAuthorize(new string[] { "https://localhost:44351", "https://mysite.onthe.net" })]
public class MyInternalApiController : ControllerBase
{
...
}
It may also be implemented on the Action instead of the Controller. The implementation was done like this:
public class ApiAuthorizeAttribute : TypeFilterAttribute
{
public ApiAuthorizeAttribute(string[] origins) : base(typeof(ApiAuthorizeFilter))
{
Arguments = new object[] { origins };
}
}
public class ApiAuthorizeFilter : IAuthorizationFilter
{
readonly string[] _origins;
public ApiAuthorizeFilter(string[] origins)
{
_origins = origins;
}
public void OnAuthorization(AuthorizationFilterContext context)
{
if (_origins == null)
return;
string referer = context.HttpContext.Request.Headers["Referer"].ToString();
if (string.IsNullOrWhiteSpace(referer) || !_origins.Any(origin => referer.StartsWith(origin, StringComparison.OrdinalIgnoreCase)))
context.Result = new ForbidResult();
}
}
Things to consider:
The implementation and check of the referer could be exact match instead of StartsWith
The handling could use RegEx or any good alternative to handle subdomains, wildcards etc
The referer could be translated to a Uri objects to get better results and variations
A jQuery ajax call gets a "403 - Forbidden" as expected, but Postman gets a "404 - Not Found". To me that does not matter, but that's something to look into if it matters.
But it covers what I need, so I'm happy with this.

Related

How does Swagger achieve the same route but different query parameters?

I created an asp.net core web api project, using the .net5 version, and I have a route like this.
[Route("api/detail")]
public IEnumerable<User> Get()
{
//TODO
return users;
}
[Route("api/detail")]
public IEnumerable<User> Get(string name)
{
//TODO
return users;
}
Although my request method is the same and the request parameters are different, the 500 error will be reported in swagger. Is there any way to solve it? Any help is greatly appreciated.
There could be multiple reasons why you're getting a 500 error. When I pasted your code into a new controller the first is error I received was:
Ambiguous HTTP method for action... Actions require an explicit HttpMethod binding for Swagger
It's telling you that you need to decorate each action in the controller with an HttpMethod binding, like [HttpGet]. More on that in a second...
The next issue is that you're using [Route] to bind two different action methods to the exact same route with the same HttpMethod. That's not possible in an API controller.
Conflicting method/path combination... Actions require a unique
method/path combination for Swagger
My preferred method for routing is to use Attribute routing with Http verb attributes.
The first step would be to move the route attribute to the controller. I'm going to assume you've created a DetailsController:
[Route("api/[controller]")]
[ApiController]
public class DetailsController : ControllerBase { }
Now, update your actions. Remove the [Route] attribute, replace with the HttpGet attribute, and add the name parameter to your second endpoint. I also prefer to return an IActionResult:
[HttpGet]
public IActionResult Get()
{
//TODO
return Ok(users);
}
[HttpGet("{name}")]
public IActionResult Get(string name)
{
//TODO
return Ok(users);
}
Note that parameters are identified by using curly braces around the variable {name} in the Http method attribute. Both endpoints work and are accessible through swagger. I urge you to read the linked page above for a better understanding of the possible routing options (linked again).

Is there any way to avoid challenging all registered authentication schemes when one of them succeeds?

I am facing an issue related to handling multiple authentication schemes in an asp.net core application which exposes API.
In particular, I am attempting to make two different authentication modes available, by registering two schemes, each with its own handler.
At the moment my configuration code (simplified) looks like this:
public class Startup {
public void ConfigureServices(IServiceCollection services) {
services
.AddAuthentication()
.AddScheme<AuthenticationSchemeOptions, BasicAuthHandler>("Basic", o => {});
.AddScheme<AuthenticationSchemeOptions, ApiKeyAuthHandler>("ApiKey", o => {});
services.AddAuthorization(o => {
o.DefaultPolicy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.AddAuthenticationSchemes("Basic", "ApiKey").Build();
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {
...
app.UseAuthentication();
app.UseAuthorization();
...
}
}
public class BasicAuthHandler : AuthenticationHandler<AuthenticationSchemeOptions> {
protected override async Task<AuthenticateResult> HandleAuthenticateAsync() {
Console.WriteLine("Challenging Basic Authentication");
if( ... ) {
return AuthenticateResult.Success(...);
}
return AuthenticateResult.Fail(...);
}
}
public class ApiKeyAuthHandler : AuthenticationHandler<AuthenticationSchemeOptions> {
protected override async Task<AuthenticateResult> HandleAuthenticateAsync() {
Console.WriteLine("Challenging ApiKey Authentication");
if( ... ) {
return AuthenticateResult.Success(...);
}
return AuthenticateResult.Fail(...);
}
}
The ApiKeyAuthHandler authenticates requests depending on a custom header (say X-ApiKey) value, the BasicAuthHandler authenticates requests depending on credentials provided through Authorization: Basic BASE_ENCODED_USERNAME_AND_PASSWORD header.
Both handlers work fine: I can provide Authorization header with basic auth credentials and I can provide an api-key through the custom header.
Generally speaking, the two registered handlers are executed sequentially, in the same order I've registered them. So far, so good.
However, when I provide both basic credentials in Authorization header and api-key through X-ApiKey header, I noticed that
the first handler (BasicAuthHandler) is executed, returning AuthenticateResult.Success
the second handler (ApiKeyAuthHandler) is executed, even the first already authenticated the request successfylly, also returning AuthenticateResult.Success
the identity finally available in my controller is the one built by the second handler
I'm wondering why the second handler is executed after the first completed authentication successfully: I googled about this but can't found any configuration flags to enable a sort of short-circuit after the first success result.
The reason seems to be this foreach statement that iterates over all available authentication schemes regardless of theirs results.
Does anyone have any idea of a way to challenge available authentication scheme while no one is successful, stopping when the first succeeds?
No doubt I could implement a CompositeAuthHandler in order to manage this requirement, but I would prefer an already-made, official solution to my problem.
A note about the context which justifies the requirement of short-circuit handler evaluation: the example provided above is simplified and uses two very cheap authentication handlers, but the real case I'm facing off involves at least one very slow handler, that perform paid calls to an external system - so I would like to avoid calling it for requests already authenticated by former handlers.

Can't use Json() in asp.net core web api as it in asp.net core web

In asp.net core web I create a controller and I can use:
return Json(new {status=true});
but in asp.net core web API I can't do it.
In a controller:
[HttpGet("{id}")]
public JsonResult Get(int id)
{
}
I can not return Json()
How to use it?
Asp.Net Core Web API does provide support for wide varieties of response types, with Json being one among them. You can do that like shown below. Make sure you have all your required dependencies. You can learn about the dependencies from the documentation link I attached in this answer.
[HttpGet]
public IActionResult Get()
{
return Json(model);
}
You can also specify strict response formats using the [Produces] Filter on your controller.
Configuring Custom Formatters
You can also configure your own custom formatters in Asp.Net Web API project by calling the .AddFormatterMappings() from ConfigureServices method inside of your Startup.cs. This allows for a greater control on your content negotiation part and lets you achieve strict restrictions.
Please go through this documentation to understand further.
Using Responses with Status Codes
However, when using Web API, I suggest you use the helper methods that are built in so that your response becomes more expressive as it contains both the response content along with the status code. An example of how to do that is below
[HttpGet]
public ActionResult Get()
{
return Ok(_authors.List());
}
For a full list of helper methods available, you can take a look at the Controller.cs and ControllerBase.cs classes.
Asp.net core web api inherit from controllerBase, which doesn't contain a Json(Object) method. You should initialize a new JsonResult yourself in the action.
[HttpGet("{id}")]
public JsonResult Get(int id)
{
return new JsonResult(new { status = true });
}

Customaze API Attribute

Good afternoon, I study .NET CORE. How to create a custom attribute for the controller API? I want to allow requests to controllers from certain ip addresses.
In ASP. Net framework I created a custom attribute inheriting from "AuthorizeAttribute" then I just add my attribute to my controller.
I want that controller work from specific Ip address
Create attribute inherited from IAuthorizationFilter to have similar behavior to previous ASP.NET framework.
public class IpAuthorizationAttribute : AuthorizeAttribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationFilterContext context)
{
if (/*ip not allowed*/)
{
//return 401 Unauthorized
context.Result = new UnauthorizedResult();
}
}
}
However, Microsoft recommends policy based authorization for ASP.NET Core.

Alternative to cookie based session/authentication

Is there an alternative to the session feature plugin in servicestack? In some scenarios I cannot use cookies to match the authorized session in my service implementation. Is there a possibility to resolve the session using a token in http header of the request? What is the preferred solution for that in case the browser is blocking cookies?
I'm using ServiceStack without the built-in auth and session providers.
I use a attribute as request filter to collect the user information (id and token), either from a cookie, request header or string parameter.
You can provide this information after the user takes login. You append a new cookie to the response and inject the id and token info on clientside when rendering the view, so you can use for http headers and query parameters for links.
public class AuthenticationAttribute : Attribute, IHasRequestFilter
{
public void RequestFilter(IHttpRequest request, IHttpResponse response, object dto)
{
var userAuth = new UserAuth { };
if(!string.IsNullOrWhiteSpace(request.GetCookieValue("auth"))
{
userAuth = (UserAuth)request.GetCookieValue("auth");
}
else if (!string.IsNullOrEmpty(request.Headers.Get("auth-key")) &&
!string.IsNullOrEmpty(request.Headers.Get("auth-id")))
{
userAuth.Id = request.Headers.Get("id");
userAuth.Token = request.Headers.Get("token");
}
authenticationService.Authenticate(userAuth.Id, userAuth.token);
}
public IHasRequestFilter Copy()
{
return new AuthenticationAttribute();
}
public int Priority { get { return -3; } } // negative are executed before global requests
}
If the user isn't authorized, i redirect him at this point.
My project supports SPA. If the user consumes the API with xmlhttprequests, the authentication stuff is done with headers. I inject that information on AngularJS when the page is loaded, and reuse it on all request (partial views, api consuming, etc). ServiceStack is powerful for this type of stuff, you can easily configure your AngularJS app and ServiceStack view engine to work side by side, validating every requests, globalizing your app, etc.
In case you don't have cookies and the requests aren't called by javascript, you can support the authentication without cookies if you always generate the links passing the id and token as query parameters, and pass them through hidden input on forms, for example.
#Guilherme Cardoso: In my current solution I am using a PreRequestFilters and the built-in session feature.
My workflow/workaround is the following:
When the user gets authorized I took the cookie and send it to the client by using an http header. Now the client can call services if the cookie is set in a http-header (Authorization) of the request.
To achieve this I redirect the faked authorization header to the cookie of the request using a PreRequestFilter. Now I am able to use the session feature. Feels like a hack but works for the moment ;-)
public class CookieRestoreFromAuthorizationHeaderPlugin : IPlugin
{
public void Register(IAppHost appHost)
{
appHost.PreRequestFilters.Add((req, res) =>
{
var cookieValue = req.GetCookieValue("ss-id");
if(!string.IsNullOrEmpty(cookieValue))
return;
var authorizationHeader = req.Headers.Get("Authorization");
if (!string.IsNullOrEmpty(authorizationHeader) && authorizationHeader.ToLower().StartsWith("basictoken "))
{
var cookie = Encoding.UTF8.GetString(Convert.FromBase64String(authorizationHeader.Split(' ').Last()));
req.Cookies.Add("ss-id",new Cookie("ss-id",cookie));
req.Items.Add("ss-id",cookie);
}
});
}
}