Custom authentication scheme with AbpMvcAuthorize - asp.net-core

I'm having trouble making AbpMvcAuthorize attribute working in my special case.
I have some custom authentication mechanism (with a custom AuthenticationScheme), that sign-in my user.
To do that, I implemented a AuthenticationHandler<MyCustomAuthenticationOptions> and overrode the HandleAuthenticateAsync method and registered it inside the AuthConfigurer.Configure method from the Module-zero :
services.AddAuthentication(o => o.AddScheme("amx", b => b.HandlerType = typeof (MyCustomAuthenticationHandler)));
Now if I have this:
[Authorize(AuthenticationSchemes = "amx")]
public string GetTest()
{
return "OK";
}
And make a request with my special amx header, it's working and I can only access the method when I'm specifying it.
If I'm doing the same thing with:
[AbpMvcAuthorize(AuthenticationSchemes = "amx")]
public string GetTest()
{
return "OK";
}
It's not working anymore and I have a 401 Unauthorized result and in debug mode, I never enter my custom AuthenticationHandler.
It seems like either the AbpMvcAuthorize attribute was executed BEFORE my custom AuthenticationHandler or maybe it didn't read the AuthenticationScheme property?
Have any idea if I'm doing something wrong?
Thanks

I asked on their Github: https://github.com/aspnetboilerplate/aspnetboilerplate/issues/3778
And was told that this is not possible right now because the AbpMvcAuthorize doesn't read the AuthenticationScheme property.
I'll try to implement it with some Policy

Related

ASP.NET Core : Return Json response on Unauthorized in a filter at the controller/action level

I am not using Identity.
I have this ASP.NET Core configuration enabling two authentication schemes, cookies and basic auth:
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.Cookie.Name = "_auth";
options.Cookie.HttpOnly = true;
options.LoginPath = new PathString("/Account/Login");
options.LogoutPath = new PathString("/Account/LogOff");
options.AccessDeniedPath = new PathString("/Account/Login");
options.ExpireTimeSpan = TimeSpan.FromHours(4);
options.SlidingExpiration = true;
})
.AddScheme<AuthenticationSchemeOptions, BasicAuthenticationHandler>("BasicAuthentication", null);
BasicAuthenticationHandler is a custom class inheriting from AuthenticationHandler and overriding HandleAuthenticateAsync to check the request headers for basic authentication challenge, and returns either AuthenticateResult.Fail() or AuthenticateResult.Success() with a ticket and the user claims.
It works fine as is:
Controllers/Actions with the [Authorize] tag will check the cookies and redirect to the login page is not present.
Controllers/Actions with the [Authorize(AuthenticationSchemes = "BasicAuthentication")] tag will check the header and reply a 401 Unauthorized HTTP code if not present.
Controllers/Actions with the [Authorize(AuthenticationSchemes = "BasicAuthentication,Cookies")] tag will allow both methods to access the page, but somehow use the Cookies redirection mechanism when failing both checks.
My goal is to have most of my project to use Cookies (hence why it is set as default), but have some API type of controllers to accept both methods. It should also be possible to tag the Controllers/Actions to return a specific Json body when desired (as opposed to the login redirect or base 401 response), but only for certain controllers.
I've spent the last 2 days reading different similar questions and answers here on StackOverflow, nothing seems to accommodate my need.
Here's a few methods I found:
The options under AddCookie allow you to set certain events, like OnRedirectToAccessDenied and change the response from there. This does not work because it applies to the whole project.
Under my BasicAuthenticationHandler class, the AuthenticationHandler class allow to override HandleChallengeAsync to change the response from there instead of replying 401. Unfortunately, again it applies globally to everywhere you use the scheme, not on a controller/action level. Not sure if it's applied when mixing multiple schemes either.
Many answers point to adding a Middleware to the solution, again, it impacts the whole project.
Many answers point to Policies, but it seems to be to control whether or not an user have access to the resource based on claims, not controlling the response when he do not.
Many answers suggest creating a class inheriting from AuthorizeAttribute, IAuthorizationFilter. Again, this allow to override the OnAuthorization method to decide if the user have the right or not to access the resource, but not to control the response AFTER the normal authentication scheme failed.
I'm thinking either there's a filter type I'm missing, or maybe I need to create a third authentication type that will mix the previous two and control the response from there. Finding a way to add a custom error message in the options would also be nice.
I managed to do it via a IAuthorizationMiddlewareResultHandler. Not my favorite approach because there can be only one per project and it intercepts all calls, but by checking if a specific (empty) attribute is set, I can control the flow:
public class JsonAuthorizationAttribute : Attribute
{
public string Message { get; set; }
}
public class MyAuthorizationMiddlewareResultHandler : IAuthorizationMiddlewareResultHandler
{
private readonly AuthorizationMiddlewareResultHandler DefaultHandler = new AuthorizationMiddlewareResultHandler();
public async Task HandleAsync(RequestDelegate requestDelegate, HttpContext httpContext, AuthorizationPolicy authorizationPolicy, PolicyAuthorizationResult policyAuthorizationResult)
{
// if the authorization was forbidden and the resource had specific attribute, respond as json
if (policyAuthorizationResult.Forbidden)
{
var endpoint = httpContext.GetEndpoint();
var jsonHeader = endpoint?.Metadata?.GetMetadata<JsonAuthorizationAttribute>();
if (jsonHeader != null)
{
var message = "Invalid User Credentials";
if (!string.IsNullOrEmpty(jsonHeader.Message))
message = jsonHeader.Message;
httpContext.Response.StatusCode = 401;
httpContext.Response.ContentType = "application/json";
var jsonResponse = JsonSerializer.Serialize(new
{
error = message
});
await httpContext.Response.WriteAsync(jsonResponse);
return;
}
}
// Fallback to the default implementation.
await DefaultHandler.HandleAsync(requestDelegate, httpContext, authorizationPolicy, policyAuthorizationResult);
}
}
I was typing this on comment... but it's doesn't fit... so here is something we probably need to make clear before choosing a solution:
Authorization process happen at the upper middleware above controller
Yes, AuthorizationMiddleware was registered when we use app.UseAuthorization();, that quite far above controller layer, so it was returned long before the request can reach controller, so, any type of filter cannot be applied here.
Not specify an authentication scheme or policy would easily lead to un-stable behavior.
Imagine, Authentication process return an instance of User that stick with the request, but what would happen if the permission on cookie and basicAuth was difference, like cookie have myclaim, while basicAuth doens't ? Related process on both type of scheme was difference (like challenge on cookie would lead to /Account/Login and basicAuth to /Login ?). And various logic case that we could implement on each page.
I Know, this is not possible, but it would become a mess, not for the author of these code, but for those maintainers to come.
Json response for some specific process on client ?
This might sound detailed at first glance, but it would rather become burden soon, if some more authentication requirement raise after that (like Jwt). Covering each of these case on client would make user experience quite awkward (like, half-authentication and authorization).
And if It's un-avoidable in the project. Might I suggest create a default authentication scheme with ForwardDefaultSelector that would elected which authentication scheme to use for each request. And maintain a stable routing HashSet that would use to detect on which endpoint to set Json Response as wished on some upper level than AuthorizationMiddleware, by using middleware, ofcourse. Then, we narrow down to 2 centralize places to checkout the authorization.
Chaos came when we tried to make one thing to do somethings. At least in this case, I think we would breath easier when coming to debug phase.

Dropwizard Authentication with POST calls failing

I was trying out Dropwizard authentication in my code but facing some issue in POST call at runtime, although its working fine with GET. this is how I am using this in the GET call:
#Override
#GET
#Path("/auth")
public Response doAuth(#Auth User user) {
//do something
}
And then in Post call which is not working:
#Override
#POST
#Path("/")
public Response createLegalEntity(#Auth User user, LegalEntity createLegalEntity) {
// do something
}
While running it is throwing following error:
SEVERE: Missing dependency for method public javax.ws.rs.core.Response org.flipkart.api.LegalEntityResource.createLegalEntity(com.yammer.dropwizard.authenticator.User,org.flipkart.model.LegalEntity) at parameter at index 0
I am new to Dropwizard and not able to figure out the cause of the problem.
UPDATE
Here is how I have registered my ldap authentication configs:
final LdapConfiguration ldapConfiguration = configuration.getLdapConfiguration();
Authenticator<BasicCredentials, User> ldapAuthenticator = new CachingAuthenticator<>(
environment.metrics(),
new ResourceAuthenticator(new LdapAuthenticator(ldapConfiguration)),
ldapConfiguration.getCachePolicy());
environment.jersey().register(new AuthDynamicFeature(
new BasicCredentialAuthFilter.Builder<User>()
.setAuthenticator(ldapAuthenticator)
.setRealm("LDAP")
.buildAuthFilter()));
environment.jersey().register(new AuthValueFactoryProvider.Binder<>(User.class));
The most likely reason is that you have not configured that auth feature correctly. The one thing that most people forget about is the AuthValueFactoryProvider.Binder. An instance of this class also needs to be registed. This would definitely cause the error you are seeing, if unregistered.
// If you want to use #Auth to inject a custom Principal type into your resource
environment.jersey().register(new AuthValueFactoryProvider.Binder<>(User.class));
From Basic Authentication docs
See also:
My comment for Dropwizard issue regarding the same problem. You will get a good explanation of the what causes the problem.

RestEasy #ValidateRequest is not working

I am having below configuration for a RestEasy Rest WS
jaxrs-api-2.3.5.Final.jar,
resteasy-jaxrs-2.3.5.Final.jar,
resteasy-hibernatevalidator-provider-2.3.5.Final.jar,
hibernate-validator-4.3.2.Final.jar,
validation-api-1.0.0.GA.jar
I have added #ValidateRequest on class(tried on method as well) to validate any request input data before processing the request but i dont know why validation in not being invoked.
#Path(value = "/events")
#ValidateRequest
public class EventRestController {
#GET
#Produces({ MediaType.APPLICATION_XML, ACCEPT_HEADER })
public Response get(#QueryParam("componentSerialNumber") #NotNull String componentSerialNumber) {
System.out.println("powerChangeEvevnt.getComponentSerialNumber() " + componentSerialNumber);
return Response.ok().build();
}
}
i dont know what i am missing.
please suggest.
Turning on auto scanning of Rest resources and providers solved the issue, validation started working.
just set resteasy.scan parameter value to true in web.xml
i had explicitly registered all resources in a subclass extending javax.ws.rs.Application class but it was not considering HibernateValidator as a validator for validation. i found registering HibernateValidator as a validator quite complex, so just removed this explicitly registered configuration class and enabled Automatically scan.

Invoke a Controller Action from an Interceptor on Asp.Net MVC (Castle Windsor)

Is there any way this. I want to invoke an action with parameter (or parameterless at least) like below.
My situation is;
Interceptor not contains any reference from MVC, Interceptor is located at ApplicationService layer.
This is a service Interceptor.
public class ControllerInterceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
var retVal = (ResponseDTOBase) invocation.ReturnValue;
if (retVal.ResponseCode == UsrNotAuth)
{
//Invoke Controller Action With passsing parameter (retVal)
}
invocation.Proceed();
}
}
Any ideas ? Thanks.
May I offer you another approach for request authorization. MVC is a state machine in its core principle. State machines have actions, triggers and guards. There is already such a 'guard' in MVC for the very purpose of intercepting controller actions and checking for the user privileges. This is the AuthorizeAttribute. This class implements IAuthorizationFilter. Another aspect is that authorization and authentication should happen before they reach your services. What I mean exactly is that there are two types of authorization :
Action Authorization and
Data Authorization.
The first type of authorization you can implement with AuthorizeAttribute or your custom attribute implementation of IAuthorizationFilter + FilterAttribute. Here is an example implementation of such an attribute for a SPA (Single Page Application) that works with ajax requests :
The attribute :
[AttributeUsage( AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
public class LoggedOrAuthorizedAttribute : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
CheckIfUserIsAuthenticated(filterContext);
}
private void CheckIfUserIsAuthenticated(AuthorizationContext filterContext)
{
// If Result is null, we’re OK: the user is authenticated and authorized.
if (filterContext.Result == null)
return;
// If here, you’re getting an HTTP 401 status code. In particular,
// filterContext.Result is of HttpUnauthorizedResult type. Check Ajax here.
// User is logged in but this operation is not allowed
if (filterContext.HttpContext.User.Identity.IsAuthenticated && filterContext.HttpContext.Request.IsAjaxRequest())
{
//filterContext.HttpContext.Response.StatusCode = 401;
JsonNetResult jsonNetResult = new JsonNetResult();
jsonNetResult.Data = JsonUtils.CreateJsonResponse(ResponseMessageType.info, "msgOperationForbiddenYouAreNotInRole");
filterContext.Result = jsonNetResult;
//filterContext.HttpContext.Response.End();
}
}
}
If you use pure MVC there is an example implementation here.
The usage :
In your controller
[LoggedOrAuthorized(Roles = Model.Security.Roles.MyEntity.Create)]
public ActionResult CreateMyEntity(MyEntityDto myEntityDto)
{
...
}
You can apply this on every controller action and block the user even before the controller is reached.
You can supply Loggers and other 'plumbing' through Castle Windsor inside your filters in order to record the events.
A very good and important links and comments are available in this answer of a similar question. These links provide very good guide for proper implementation too.
The other type of authorization - Data Access Authorization can be handled in the service or in the controller. I personally prefer to handle all kinds of authorization as soon as possible in the pipeline.
General practice is not to show to the user any data or action that he is not authorize to view or to execute commands upon it. Of course you have to double check this because the user can modify the POST and GET requests.
You can make simple interface with implementation IDataAccessService and control data access by passing user id and entity id to it.
Important thing is that you should not throw exception when the user is not authorized because this is no exception at all. Exception means that your program is in an unexpected state which prohibits its normal execution. When a user is not authorized this is not something unexpected - it is very well expected. That is why in the example implementation a message is returned rather then exception.
Another subtlety is that "exceptions" are handled differently by the .NET framework and they cost a lot more resources. This means that your site will be very vulnerable to easy DDOS outages or even they can perform not as they can. General rule is that if you control your expected program flow through exceptions you are not doing it properly - redesign is the cure.
I hope this guides you to the right implementation in your scenario.
Please provide the type of the authorization you want to achieve and parameters you have at hand so I can suggest a more specific implementation.

Why does my ServiceStack AuthProvider never call Authenticate(), even when IsAuthorized() returns false?

I'm writing an AuthProvider for ServiceStack to authenticate against our own OAuth2 server, and having problems with the way ServiceStack interacts with my provider.
According to https://groups.google.com/d/msg/servicestack/e3kkh-qRDYs/DF9Y05ibl-MJ
There are generally 2 ways for extending, if you want to provide your own OAuth implementation you would sub class AuthProvider (or implement IAuthProvider) and override the Authenticate() method which holds the entire implementation of your service. The AuthService now has no real implementation of its own, it just checks the Auth Provider .IsAuthorized() method to see if the user is already authenticated, if not it calls the Authenticate() method. [my emphasis]
My entire auth provider right now looks like this:
using System;
using ServiceStack.ServiceInterface;
using ServiceStack.ServiceInterface.Auth;
namespace SpotAuth.ResourceServer.Services {
public class SpotlightOAUthProvider : AuthProvider {
public override bool IsAuthorized(IAuthSession session, IOAuthTokens tokens, Auth request = null) {
return (false);
}
public override object Authenticate(IServiceBase authService, IAuthSession session, Auth request) {
// A breakpoint on this line is never reached; the service just returns Unauthorized.
throw new NotImplementedException();
}
}
}
Why is the Authenticate method never being called? The forum post linked above is nearly a year old but I can't find anything suggesting this behaviour has been deprecated.
This answer probably comes a bit late, but I just stumbled upon your question now.
A few weeks before you asked your question, I tried to implement my own AuthProvider and had a similar problem:
How to get ServiceStack authentication to work? (with iPhone clients)
(near the bottom of the question, there's my MyBasicAuthProvider)
In the end I found out what I did wrong, and I think you made the same mistake as I did:
I needed to override TryAuthenticate instead of Authenticate.
As soon as I changed that, my provider worked.