Grails spring Security add authentication method - grails

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.

Related

How to implement switch user in spring security rest using grails 2.4.3

I need to implement switch user functionality using spring security rest plugin in Grails 2.4.3
Config.groovy changes.
Enable Switch User Functionality
grails.plugin.springsecurity.useSwitchUserFilter = true
grails.plugin.springsecurity.switchUser.switchFailureUrl="/admin/switchFailed"
Configure the Roles for Switch User, Here we are only allowing users with ADMIN role to switch.
grails.plugin.springsecurity.interceptUrlMap = [
'/j_spring_security_switch_user': ['isFullyAuthenticated()', 'ROLE_ADMIN'],
'/j_spring_security_exit_user': ['isFullyAuthenticated()', 'ROLE_ADMIN']
]
Rest Request
To Switch a User via Rest, Send a HTTP Post request to the following URL with username parameter.
/j_spring_security_switch_user?j_username={userNameToSwitch}
Update:
Above solution is not working with Rest, as Rest uses Access Tokens instead of Session.
Here is how we can achieve it.
Add a new property "originalUsername" in AuthToken domain
Implement a new SwitchFilter similar to Springs SwitchFilter
This new filter will set the impersonating users username in "username" column and updates the originalUsername with current logged username.
Define and add the filter to filterChain in
resources.groovy
restTokenValidationFilter(SwitchFilter) {
// injections
}
SpringSecurityUtils.registerFilter 'restSwitchFilter', SecurityFilterPosition.ANONYMOUS_FILTER.order + 1

How to customize rolePrefix in Grails using Spring Security plugin?

I am working on a grails 2.3.8 project and trying to customize the Role Hierarchy. I am trying to change the default value of rolePrefix = 'ROLE_' in resources.groovy with rolePrefix = 'PERM_'. I understand that to make this work, I need to make the following changes in my Config.groovy into something like:
grails.plugins.springsecurity.userLookup.userDomainClassName = 'tpo.core.acl.AdminAccount'
grails.plugins.springsecurity.userLookup.authorityJoinClassName = 'tpo.core.acl.AdminAccountPermission'
grails.plugins.springsecurity.authority.className = 'tpo.core.acl.Permission'
And to establish hierarchy, I need to add this too in my Config.groovy
grails.plugins.springsecurity.roleHierarchy = '''
PERM_ACCOUNT_ALL > PERM_ACCOUNT_CREATE
PERM_ACCOUNT_ALL > PERM_ACCOUNT_READ
PERM_ACCOUNT_ALL > PERM_ACCOUNT_UPDATE
PERM_ACCOUNT_ALL > PERM_ACCOUNT_DELETE
'''
So in my Controller, it is something like,
#Secured(['PERM_ACCOUNT_ALL'])
def index() {
redirect(action: "list", params: params)
}
When I try to run my application, and access my controller's index() action, I was prompted to log in, this is expected because of the presence of #Secured(), but having successfully logged in, I was not yet able to access the index() action, and it displayed, Sorry, you're not authorized to view this page. The permission was assigned to the user that I used to logged in, but still, I was not able to access it.
Where am I missing?
There's a lot more to it than that :)
The reason that the plugin doesn't allow this change is to support the standard voters. Currently there are three styles of strings that can be used to specify access rules - role names, SPeL expressions, and the funky "IS_AUTHENTICATED" ones - IS_AUTHENTICATED_ANONYMOUSLY, IS_AUTHENTICATED_FULLY, and IS_AUTHENTICATED_REMEMBERED. Additionally there's a new way that was added for the 2.0 release - using a Closure and any arbitrary Groovy code inside of it, but that's unrelated to role names.
Each of the registered voters is queried to determine if they "support" (i.e. can vote on) each of these tokens. The logic is currently rather straightforward - the "IS_AUTHENTICATED_..." strings are handled by one voter, strings starting with "ROLE_" are handled by another, and everything else is assumed to be a SPeL expression.
To be honest, I think since roles would have to have been "registered" at startup anyway (to specify what access rules are allowed for each role in annotations, Config.groovy, etc.) that the role voter could do more than just check that the string starts with some prefix - it could look at its collection of known role names. So it probably wouldn't be too much work to add support for custom role prefixes for the 2.0 release, and I'll look into that. But for now, the plugin is as customizable as much as possible in every way except for this one exception.

Grails Filters vs Interceptor

I have been studying Grails for quite a while now. And scanned a little bit about Filters and Interceptors. Both have almost the same functionality of tracking the sessions or redirecting unauthorized users in a particular controller.
But I'm confused when and why should I use Filter than Interceptor and vice versa.
Given that the Inceptors have two controller methods beforeInterceptor and afterInterceptor and for the Filters a three common closures before, after and afterView.
My questions is what are the pros and cons of using Filter against Interceptor or vise versa. In this manner we, developers, can decide when, where, and why we should use either Filter or Interceptor in a particular Controller to do some tracking, redirect, etc.
Use one or both interceptors in a controller when the interception logic only applies to that controller.
Use a filter when the logic applies to multiple (or all) controllers, or when you need to do something after the view is rendered (there's no interceptor equivalent of afterView), or if you just want to keep everything centralized in one place instead of spread across separate controller files.
The Old Filters (From Grails 2) are deprecated in Grails 3. The replacement to the Filters are Interceptors.
The use of interceptors is for actions such as: authentication, loggin, etc.
The interceptors (as their name implies) are intercepting the incoming web requests and trigger a related actions. The actions are defined in the related Controller.
The Interceptors have some major benefits (over the Filters) such as support for static compilation, and enable flexible configurations.
These are the main 3 methods of the Interceptor:
- boolean before() { true }
- boolean after() { true }
- void afterView() { }
The Iterceptors are configured as Spring Beans (in the Spring application context) and are configured to be auto-wired by their names.

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.

Using Pre/Post Spring-Security Annotations with Grails

I'm developing a Grails (Version 1.3.3) Web-Application using the Grails Spring-Security Plugin, Spring-Security-Core-1.0.1 (which, in turn, uses spring-security-3.0.2.RELEASE).
I would like to provide Spring-Security annotation-based access control on actions within a controller.
I have been able to successfully do basic authentication using the following annotations:
#Secured("hasAnyRole('ROLE_USER')")
def list = {
...
}
This works - providing access to the list action/view only to those with the ROLE_USER role.
However, the set of which roles are allowed to perform certain controller-actions may change over time and is a function of the system's overall state. That is, the set of roles allowed to perform a given action might be returned by a service or domain-object method.
One way I might be able to do something like this would be to use Spring-Security's "Expression Based Access Control" (#Pre and #Post annotations), something like the example at the Spring Security Documentation:
#PreAuthorize("hasPermission(#contact, 'admin')")
public void deletePermission(Contact contact, Sid recipient, Permission permission);
In this example for access control decisions, one can gain access to the objects sent to the method (eg contact) using the #contact syntax.
However, I can't get #PreAuthorize (or #RolesAllowed) annotations to work on a Grails controller-action. If I annotate the list action with #PreAuthorize (rather than #Secured, as above), I get the following error:
Annotation
#org.springframework.security.access.prepost.PreAuthorize
is not allowed on element FIELD
This isn't surprising -- the action is a Groovy closure (a field with executable code), rather than a method. However, I've also tried using the annotation on methods, called from the closure, like:
def list = {
testMethod()
....
}
#PreAuthorize("hasRole('ROLE_USER')")
public boolean testMethod(){
println "testMethod succeess"
return true;
}
While this doesn't throw any errors, it also doesn't appear to provide any access control. ("testMethod success" is printed whether or not the user has ROLE_USER).
So, I've tried a few different things (and read the documentation), but haven't been able to work out a nice way of using #PreAuthorize annotations with a Grails controller-action. Is this possible? Is there a better way in a Grails app to use Spring-Security-Annotations to provide access-control that is a function of the state of the system?
You need to use the ACL plugin to use those annotations, but they won't work on controller actions for the reasons you point out. #Secured works because I created a copy of the Spring Security annotation that allows it to be placed on fields as well as methods and classes, and I look for them and wire them up explicitly. You'll need to use annotated services that you call from your controllers.

Resources