Spring Security Access Denied page with multiple security configs - spring-security

I have two security config in my application one for the UI and one for the rest API
I would like to add an access denied page to the UI but not for the rest api.
For the first configuration I have:
.antMatchers("/gui/**")
.hasAuthority(accessRight)
.and()
.exceptionHandling().accessDeniedPage("/gui/error")
.oauth2Login()
.userInfoEndpoint(createUserInfoEndpointCustomizer())
.and()
.oauth2ResourceServer()
For the second
.antMatchers("/api/**")
.hasAuthority(accessRight)
.and()
.oauth2Login()
.userInfoEndpoint(createUserInfoEndpointCustomizer())
.and()
.oauth2ResourceServer()
I would expect the access denied page to be returned only on the first case but it seems like I receive it in case I am trying to access the api as well.
Any idea?

You may want to create a DelegatingAccessDeniedHandler that holds multiple instances of AccessDeniedHandlers, one for UI and one for REST API and decides which internal instance to invoke basis 'Accept' header or requeste URL.

Related

What does "Challenge" term stand for?

ControllerBase class has Challenge method, that returns an object of the ChallengeResult class.
CookieAuthenticationOptions class has AutomaticChallenge property.
I believe ChallengeResult has something to do with external logins. But how does it actually work? Where does the term "Challenge" come from? What does lay inside this.
A ChallengeResult is an ActionResult that when executed, challenges the given authentication schemes' handler. Or if none is specified, the default challenge scheme's handler. Source code for ChallengeResult
So for example, you can do:
return Challenge(JwtBearerDefaults.AuthenticationScheme); //Can specify multiple schemes + parameters
This will challenge the JWT Bearer authentication handler.
In this handler's case, it sets the response status code to 401 to tell the caller they need authentication to do that action.
AutomaticChallenge (in ASP.NET Core 1.x) is the setting that says this is the default challenge handler. It means it will be called if no authentication scheme is specifically named.
In 2.x, this was changed such that you now specify the default challenge scheme or the higher-level default scheme.
services.AddAuthentication(o =>
{
o.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; //Default for everything
// o.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; //Default specifically for challenges
})
A challenge is basically a way of saying "I don't know who this user is, please verify their identity". So if the authentication handler triggered is e.g. the Facebook authentication handler, it will react to the challenge by issuing a redirect to the Facebook authentication page. A local account authentication handler might issue a redirect to the local sign-in page.
In the case of JWT Bearer authentication, the handler cannot do anything other than respond with a 401 status code and leave it up to the caller to authenticate themselves properly.
You can see this in action in OAuthHandler (HandleChallengeAsync), which Facebook auth uses (and Microsoft and Google authentication).
You typically return a Challenge when you don't know who the user is, and a Forbid if you know who they are, but they are not allowed to do the action they tried to do.

How to use PageOutPut Caching in MVC with Authorize attribute

We are using [Authorize] attribute on base controller which redirects each unauthenticated user to log in page and grants the access to every authenticated user which is working as expected. We are also using Azure manged cache service /distributed cache service to store certain data. Now we are trying to use the Page Output caching in some places but getting the exception below
When using a custom output cache provider like 'AFCacheOutputCacheProvider', only the following expiration policies and cache features are supported: file dependencies, absolute expirations, static validation callbacks and static substitution callbacks.
at System.Web.Caching.OutputCache.InsertResponse(String cachedVaryKey, CachedVary cachedVary, String rawResponseKey, CachedRawResponse rawResponse, CacheDependency dependencies, DateTime absExp, TimeSpan slidingExp) at System.Web.Caching.OutputCacheModule.OnLeave(Object source, EventArgs eventArgs) at System.Web.HttpApplication.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
I did search around this and found many posts mentioning that never use Authorize attribute with page output caching because of the logical reason that caching will not let you see the content of another users.
Here are few linked which we have already refereed, you can check those here and here - Why can't I combine [Authorize] and [OutputCache] attributes when using Azure cache (.NET MVC3 app)?
Isn't it the common requirement in applications where you have action methods protected with authorize attribute but you still want to cache the output of action methods (varying by params)?

How to make the top level endpoint public when authorization is used in eve?

I am working on a REST API with python-eve. I use authorization with a subclass of the default TokenAuth class as described in the documentation. However now a GET Request to / replies with error code 401 and the message "Please provide proper credentials".
I want a GET request to / to just return the default list of available resources without authorization.
For a regular endpoint I would just add GET to the public_methods property in the schema, but / does not have a schema, how can I make it a public endpoint again?
You could go the other way around. Set PUBLIC_METHODS to ['GET'] so home endpoint is accessible. Then you set public_methods to [] for every protected resource.

HTTP module vs action filter in asp.net-mvc

I am developing an application in asp.net MVC3 and I have the following questions:
When should I write an HTTP module and when should I write an action filter?
Filter are more MVC approach of doing thing whereas Http Module are more of ASP.NET way of doing thing. Both serve similar purpose by providing hook in the processing pipline.
HttpModule is more generic and when you want some thing to be processed on every request. Filters are useful for adding action specific behaviour.
If you want some thing to be executed only once per Http Request, you should use an HttpModule. ActionFilter may get executed several times during a request until and unless you check IsChildActionOn.
HttpModule are called before and after the request handler executes. They are intended to enable a developer to intercept, participate, or modify each request. There are 22 available events that can be subscribed to that enables the module to work on the request in various stages of the process. The events are useful for page developers who want to run code when key request pipeline events are raised. They are also useful if you are developing a custom module and you want the module to be invoked for all requests to the pipeline.
Filters are designed to inject logic in between MVC request life cycle. Specifically before and after de action is invoked, as well as, before and after the result is processed. Filters provide users with powerful ways to inspect, analyze, capture and instruments several things going around within MVC projects. As of MVC5, there are 5 types of filters :
Authentication
Authorization
Action
Result
Exception
So if you want to intercept, participate, or modify in a specific of the 22 events in the http request pipeline choose the modules. If your logic is is strictly related to the action method you better server overriding one of the following ActionFilterAttribute methods:
OnActionExecuting
OnActionExecutted
OnResultExecuting
OnResultExecuted
HttpModule is how IIS allows an Web application to override the default behavior or add custom logic by letting you attach event handlers to HttpApplication events.
Different IIS modes (Integrated or Classic) even use has different Web.config settings.Reference:
http://msdn.microsoft.com/en-us/library/ms227673(v=vs.100).aspx
Example: redirect non-www to www URLs
public void Init(HttpApplication application)
{
application.PreRequestHandlerExecute += this.Application_PreRequestHandlerExecute;
}
private void Application_PreRequestHandlerExecute(object sender, EventArgs e)
{
Uri requestUrl = HttpContext.Current.Request.Url;
string host = requestUrl.Authority.ToLower();
if (!host.StartsWith("www"))
{
HttpContext.Current.Response.Redirect(requestUrl.Scheme + "://www." + host + requestUrl.PathAndQuery);
HttpContext.Current.Response.End();
}
}
An Action Filter is an attribute decorating controllers or action methods. It is an abstraction layer between MVC routing and action methods. With action filters, we can apply same logic to multiple controllers or action methods. for example, custom logging.

Grails spring Security add authentication method

I have an application that requires the users to choose between 2 different authentication methods.
One being username/password authentication and the other being username/password/one-time-password.
i have created the additional authentication provider and it works well when overriding the daoAuthenticationProvider provider in my resources.groovy as done in http://burtbeckwith.com/blog/?p=1090
however now when i need my authentication method to live side by side with the standard daoAuthenticationProvider i am a bit stuck.
I know i have my custom authentication provider and a custom filter registered in resources.groovy. The question is how do i make a url("redirect /my_auth to the filter") be intercepted by my custom filter?
Instead of registering the filters in resources.groovy, you can do this using filterChain configurations in Config.groovy. Declare all the filters spring security will be using in filterchain.filterNames, including both the standard filters you want, as well as your custom ones:
grails.plugins.springsecurity.filterChain.filterNames = [
'securityContextPersistenceFilter', 'logoutFilter',
'authenticationProcessingFilter', 'firstCustomFilter','secondCustomFilter',
'rememberMeAuthenticationFilter', 'anonymousAuthenticationFilter',
'exceptionTranslationFilter', 'filterInvocationInterceptor'
]
Then map your custom filters to specific URLs - one way to do this using exclusions is as follows:
grails.plugins.springsecurity.filterChain.chainMap = [
'/customUrlOne/**': 'JOINED_FILTERS,-secondCustomFilter',
'/customUrlTwo/**': 'JOINED_FILTERS,-firstCustomFilter',
'/**': 'JOINED_FILTERS,-firstCustomFilter,-secondCustomFilter'
]
JOINED_FILTERS is the set of all filters you've declared in the first map. Under "/**", all filters except your custom filters which have been excluded will be active. Similarly, under the custom URLs, all filters, minus the excluded custom filter meant for the other URL will be active. This will ensure that traffic going to customUrlOne will be intercepted by firstCustomFilter, and traffic going to customUrlTwo will be intercepted by secondCustomFilter.

Resources