Giter VIP home page Giter VIP logo

grails-shiro's Introduction

This is the OLD plugin Repo

Don't post issues here please.

New Grails Shiro plugin

The Grails 3 (Grails 3 & 4, Shiro 1.5+) plugin has been re-written and now lives at https://github.com/nerdErg/grails-shiro . The code here should be considered archived and not for current use (it contains some vulnerabilities and is not maintained)

You can find the plugin on the plugin portal at http://plugins.grails.org/plugin/nerderg/grails-shiro

OLD Grails 3 Shiro plugin

Build Status

Documentation is a work in progress.

Installation

To install this plugin you need to add this to your build.gradle dependencies.

compile 'org.grails.plugins:grails-shiro:3.3.0'

Configuration

To override default configuration of the shiro plugin you can simply add corresponding configuration keys to your application.groovy or application.yaml file.

grails {
  plugin {
    shirosecurity {
      session.mode = [null, 'native'] //default null
      filter {
        loginUrl = [url for your login page] //default "/auth/login"
        unauthorizedUrl = [url for your unauthorized page] //default "/auth/unauthorized"
        successUrl = [url for your success page] //default null
        basicAppName = [name to show in basic http auth] //not configured by default, it triggers basic auth
        filterChainDefinitions = optional, see [https://shiro.apache.org/static/1.4.0/apidocs/org/apache/shiro/spring/web/ShiroFilterFactoryBean.html#setFilterChainDefinitions-java.lang.String-]
      }
      authc.required = [boolean] //Get the config option that determines whether authentication is required for access control or not. By default, it is required.
      redirect.uri = [url for redirect when page needs authentication] //default "/auth/login?targetUri={urlRequested}"
    }
  }
}

Available codegen scripts

To help you get started, plugin provides convenient way to generate required classes. You can use them with your grails command or grails wrapper grailsw.

grails shiro-quick-start [--prefix your.package.name.ClassPrefix] - creates basic domain classes, database realm to authenticate your users against database and security interceptor and auth controller. Default prefix is shiro3.Shiro.

grails create-wildcard-realm [--prefix your.package.name.ClassPrefix] - creates a new database realm from a template that only works with wildcard permissions. Other types of permission are not supported.

grails create-security-interceptor [--prefix your.package.name.ClassPrefix] - creates a new security interceptor from a template.

grails create-ldap-realm [--prefix your.package.name.ClassPrefix] - creates a new ldap realm from a template.

grails create-db-realm [--prefix your.package.name.ClassPrefix] - creates a new database realm from a template that only works with database permissions. Other types of permission are not supported.

grails create-auth-controller [--prefix your.package.name.ClassPrefix] - creates a new authentication controller from a template.

grails-shiro's People

Contributors

animator013 avatar apandichi avatar bitdeli-chef avatar burtbeckwith avatar ksachdeva avatar lsborg avatar matthewjrose87 avatar miq avatar pledbrook avatar pmcneil avatar rosenfeld avatar yellowsnow avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

grails-shiro's Issues

servlet-api-2.5.jar

Hi Peter,
Having some troubles with 1.1.4.

If I don't explicitly exclude shiro-cas:

inherits("global") {
excludes 'shiro-cas'
}
...
compile ":shiro:1.1.4"

I am having a copy of servlet-api-2.5.jar stuck in my resultant war when built by Grails 2.1.0 (along with the Shiro CAS stuff of course).

Any thoughts on something I might be doing wrong here or if there is something screwy in the dependencies?

Problem when i use annotation, is there a bug?

In LegacyPermissionAnnotationHandler.java

try {
Constructor constructor = ann.type().getConstructor(new Class[] { String.class, String.class });
Object permission = constructor.newInstance(new Object[] { ann.target(), ann.actions() });

if (!getSubject().isPermitted((Permission) permission)) {
    String msg = "Calling Subject does not have required permission [" + permission + "].  " +
            "Method invocation denied.";
    throw new UnauthorizedException(msg);
}

}
catch (Exception ex) {
throw new RuntimeException(ex);
}

when the user has no permission , it will throw a UnauthorizedException, but it would been catched and in catch block there rethrow a new RuntimeException. And next, the ShiroFilter.groovy won't catch it ,the RuntimeException will cause a HTTP 500 error.
hope to fix, thx and forgive my pool English.

Deprecated API warning

Hi, i'm get this warning

Note: /home/rokkit/.grails/2.2.0/projects/askedon/plugins/shiro-1.1.4/src/java/org/apache/shiro/grails/LegacyShiroFilter.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Note: Some input files use unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

Reference to: http://jira.grails.org/browse/GPSHIRO-77

http://jira.grails.org/browse/GPSHIRO-77

In earlier versions of Grails actions were implemented with Closures. For these Closlures, the following snippet in the 'processController' function of ShiroAnnotationHandlerService is ok.
clazz.declaredFields.each { field ->
...
But now the preferred approach is to use methods for actions. If an action method is annoted with a Shiro annotation, the following error will occur:
Error 2014-02-21 15:20:45,836 [http-bio-8080-exec-4] ERROR errors.GrailsExceptionResolver - AuthorizationException occurred when processing request: [GET] /mworks/
Not authorized to invoke method: public java.lang.Object mworks.core.AppController.index(). Stacktrace follows:
Message: Not authorized to invoke method: public java.lang.Object mworks.core.AppController.index()
Line | Method
->> 90 | assertAuthorized in org.apache.shiro.authz.aop.AuthorizingAnnotationMethodInterceptor

Add API key handling and session creation control

Need to be able to define a SessionStorageEvaluator, Have a API key Realm and make it so REST clients lgo in using the API key each time. This allows you to use the same security code for users and API clients. Add HMAC support code for things that really need to be secure, not just authenticated.
Also needs an ApiKeyToken

A new JSESSIONID is created on every page refresh but not from all browsers

am using Grails 2.4.3 with shiro plugin 1.2.1 on Jetty 9.1.5 The problem is that a new JSESSIONID is generated every time a page is reloaded (Shiro should not do this).

But it gets really strange since this is not always the case: If I use Chrome, Firefox or IE from a Windows 7 machine, I get the problem. If I use Chrome or Firefox on a machine with Ubuntu, the behavior is the right one (the JSESSIONID cookie is kept even when the page is reloaded)

I tried to use a different cookie name as someone else suggested in one post but this did not fix the problem; the cookie with the new name was being generated again on every page refresh (by the way I had to downgrade the Shiro plugin version in order to do this)

The serverURL I use in my grails application is of the form http://subdomain2.subdomain1.com as it is suggested (no slash at the end)

I checked the requests from all the browsers and they all look the same (with the same headers except for the user-agent) so I don't really understand why the server creates a new session with every refresh in some cases and it does not on some others.

I have a HttpSessionListener on 'sessionCreated' so I can perfectly see that. ... but I don't understand why and this is driving me nuts. Any suggestions?

Hitting Ctrl+C during Grails Shiro config has left app completely broken!

Grails 2.4.5 and Grails Shiro 1.2.1 here.

I had Shiro configured and working perfectly (when I go to an authenticated URL - as defined by the security filter - Grails Shiro intercepts and redirects to login.gsp, etc.) Authentication/authrorization was working flawlessly (upon logging in, the MyAppDbRealm class was invoked to auth the user, etc.).

This morning I was doing some local dev and ran grails run-app. About half-way through the run-app, I realized I needed to change something and hit Ctrl+C while Grails was configuring Shiro (according to the console output). I am now completely unable to run-app and it seems that hitting Ctrl+C during Grails Shiro config has left the app in a broken/blocking state.

So now when I do grails run-app --stacktrace I get:

| Compiling 27 source files.....
| Error Error generating web.xml file (Use --stacktrace to see the full trace)
| Packaging Grails application.....
| Error Error generating web.xml file (NOTE: Stack trace has been filtered. Use --verbose to see entire trace.)
groovy.lang.MissingPropertyException: No such property: shiro for class: java.lang.String
    at ShiroGrailsPlugin$_closure4_closure30_closure34.doCall(ShiroGrailsPlugin.groovy:248)
    at ShiroGrailsPlugin$_closure4_closure30_closure34.doCall(ShiroGrailsPlugin.groovy)
    at ShiroGrailsPlugin$_closure4_closure30.doCall(ShiroGrailsPlugin.groovy:243)
    at ShiroGrailsPlugin$_closure4_closure30.doCall(ShiroGrailsPlugin.groovy)
    <enormous stack trace omitted for brevity>
    at gant.Gant.executeTargets(Gant.groovy:590)
| Error Error generating web.xml file

I've done everything I could think of (grails clean, grails clean-all, grails refresh-dependencies, etc.). Please advise as I am unable to do any dev work whatsoever!!!

How to specify a session timeout?

I'm sorry to ask this here, but I couldn't find how to ask questions about this plugin in the README or in the FAQ section of the plugin page.

A client of mine is requesting me to change the application to set a timeout of, say, 30 minutes of idle time, even if the browser window remains open when "remember me" is not checked. Does Shiro support this use case? If so, how can I set up this timeout for usage with this plugin?

Is there some grails-shiro specific discussion list I couldn't find?

please document how to specify actions for the unauthorization handling action

Shiro will redirect to login page when session expired or any other situation that would led to unauthorized access.

This is handy but sometimes we need more control over the process, specially when building AJAX applications.

Devise (for Rails) will by default respond to XHR requests with a JSON {error: 'unauthorized message'} and a 401 status that I can handle on JavaScript and respond properly instead of getting a redirect response.

I'd like to be able to do the same with Shiro.

Could you please explain how to set up Shiro so that I can handle unauthorized actions myself instead of simply redirecting to log-in page?

I could only find documentation on changing the log-in URL here (I find it a bit confusing):

http://shiro.apache.org/web.html#Web-DefaultFilters

If I understand correctly I should implement AuthenticatingFilter and set the url section of the ini section to point to my filter. Is that right?

http://shiro.apache.org/static/current/apidocs/org/apache/shiro/web/filter/authc/AuthenticatingFilter.html

In that case I would loose the control I have using the SecurityFilters.groovy, right?

Is there a Groovy way to set up this and keep using this plugin DSL on SecurityFilters?

Sometimes the signIn action won't respond

This has always happened on my application but I never took time to debug it specially because it is not reproducible.

But often users report that they got a timeout response from the nginx proxy server when authenticating.

I experienced that both on production and in my development computer sometimes already. nginx will send the timeout message if the server doesn't respond in 60s. In my local computer it just takes forever.

What I have to do when that happens is pressing the log-in button again and then it usually works.

It seems there is a deadlock somewhere in the authentication logic... Do you have any idea what might be causing this behavior?

Send 401/403 for AJAX requests

At the moment on UnauthenticatedException plugin redirects to login action. Could you add logic that for AJAX send response 401/403 http status code?

java.lang.StringIndexOutOfBoundsException due to bad forwardURI?

Hi folks:

We are experiencing a strange error after having deployed our app to a new environment. It must be related to the configuration of the server but it's presenting as an exception from the GrailsShiroPlugin. ShiroGrailsPlugin.groovy:440 is the line that separates the forwardURI from the context. In this case we have the app deployed on the root context.

Note that this deployment works well in our development environment, but not in the target cluster, and we're looking for assistance in helping to debug the environment (or if anyone has seen this before)?

Dan

java.lang.StringIndexOutOfBoundsException: String index out of range: 2
        at java.lang.String.substring(String.java:1907)
        at ShiroGrailsPlugin.accessControlMethod(ShiroGrailsPlugin.groovy:440)
        at ShiroGrailsPlugin$_closure3$_closure24.doCall(ShiroGrailsPlugin.groovy:236)
        at x.x.x.SecurityFilters$_closure1$_closure5$_closure9.doCall(SecurityFilters.groovy:100)
        at org.apache.shiro.web.servlet.AbstractShiroFilter.executeChain(AbstractShiroFilter.java:449)
        at org.apache.shiro.web.servlet.AbstractShiroFilter$1.call(AbstractShiroFilter.java:365)
        at org.apache.shiro.subject.support.SubjectCallable.doCall(SubjectCallable.java:90)
        at org.apache.shiro.subject.support.SubjectCallable.call(SubjectCallable.java:83)
        at org.apache.shiro.subject.support.DelegatingSubject.execute(DelegatingSubject.java:383)
        at org.apache.shiro.web.servlet.AbstractShiroFilter.doFilterInternal(AbstractShiroFilter.java:362)
        at org.apache.shiro.web.servlet.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:125)
        at com.brandseye.cors.CorsFilter.doFilter(CorsFilter.java:100)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
        at java.lang.Thread.run(Thread.java:744)

Problem with shiro and tomcat CometProcessor

Hi,

First, thanks for the great work on the plugin so far. It works very nicely for regular webapps.

Unfortunately it looks like I'm pushing the boundaries of the default configuration and need a little advice. My grails application is using atmosphere (directly, not using grails plugin) to provide web-sockets + fallback support.

This worked fine initially as tomcat with the default configuration uses blocking IO to serve the request. However as soon as I set grails.tomcat.nio = true in my BuildConfig.groovy the requests that Atmosphere handle are now processed with tomcat's comet support. In this scenario tomcat will only run servlet filters that implement CometFilter, which DelegatingFilterProxy does not, therefore shiro is not initialised and my code blows up with the following exception.

2012-10-25 17:05:46,744 [http-nio-8080-exec-7] ERROR StackTrace - Full Stack Trace:
org.apache.shiro.UnavailableSecurityManagerException: No SecurityManager accessible to the calling code, either bound to the org.apache.shiro.util.ThreadContext or as a vm static singleton. This is an invalid application configuration.
at org.apache.shiro.SecurityUtils.getSecurityManager(SecurityUtils.java:123)
at org.apache.shiro.subject.Subject$Builder.(Subject.java:627)
at org.apache.shiro.SecurityUtils.getSubject(SecurityUtils.java:56)
at com.myproject.MyAsynchHandler$$ENmrzGbI.onRequest(MyAsynchHandler.groovy:27)
at org.atmosphere.cpr.AsynchronousProcessor.action(AsynchronousProcessor.java:256)
at org.atmosphere.cpr.AsynchronousProcessor.suspended(AsynchronousProcessor.java:166)
at org.atmosphere.container.Tomcat7CometSupport.service(Tomcat7CometSupport.java:85)
at org.atmosphere.container.Tomcat7AsyncSupportWithWebSocket.doService(Tomcat7AsyncSupportWithWebSocket.java:59)
at org.atmosphere.container.TomcatWebSocketUtil.doService(TomcatWebSocketUtil.java:82)
at org.atmosphere.container.Tomcat7AsyncSupportWithWebSocket.service(Tomcat7AsyncSupportWithWebSocket.java:55)
at org.atmosphere.cpr.AtmosphereFramework.doCometSupport(AtmosphereFramework.java:1293)
at org.atmosphere.cpr.AtmosphereServlet.event(AtmosphereServlet.java:348)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:680)

I believe that the Shiro team has done some work necessary to support this by splitting out some of the logic from the ServletFilter to a context-listener (see documentation for web.xml configuration here http://shiro.apache.org/web.html#Web-%257B%257Bweb.xml%257D%257D ).

I've tried updating my shiro pluging to 1.2.0-SNAPSHOT and performing the bare minimum changes to AuthController to get my project to build, however this does not install a context listener in web.xml.

I've tried manually configuring the EnvironmentLoaderListener in my web.xml but this dies on startup due to there not being a shiro.ini. Does this mean that the plugin needs to provide it's own listener that is aware of the groovy configuration?

Once there is a listener in place that configures things correctly then I can use then if things don't work automagically via SecurityUtils then I can always use WebUtil to get hold of the security manager and check authentication manually.

Am I going down the right path here? Is this something that should be relatively easy to support in the plugin or should I start looking at using shiro 1.2 without the plugin first?

Shiro CAS support as a separate plugin

I'm going to be working on taking the code from #10 and updating it to work as a separate plugin. I'm posting here so that anyone who might care might have some visibility. It looks like (as of 1831f12) there probably aren't any remaining traces of that implementation in the grails-shiro codebase, so I don't expect there will be further code changes needed under this ticket, unless I find new extension points that are needed to make it work.

refactor the realms

The Relams (pretty much all this code) are a little weak in typing and need a refactor.
LDAP Realm could do with authorization code, groups/roles

Session is lost on 1.1

I've recently upgraded the shiro plugin from 1.1-SNAPSHOT to 1.1.3. After some tweaks to make the salt work in the new version, I've realized that the session is being lost among requests.

It doesn't matter if I use

session.something = 'another thing' // and get with session.something

or

SecurityUtils.subject.session.setAttribute('something', 'another thing') // and get with getAttribute('something')

I can read the session while in the same request, but that is not useful, right? :)

I've tried all session modes I could find mention in the internet ('native', 'shiro', 'http'). Same behavior in all of them.

I'm also using the remember-me feature and set security.shiro.authc.required = false.

It was working with Shiro 1.1-SNAPSHOT. Any hint on what might be happening here?

How to convert from SpringSecurityCore to GrailsShiro?

How to convert a pretty standard and simple Grails 2.3.11 application protected with SpringSecurityCore to GrailsShiro?

We were able to map the users and the roles, and also bootstrap everything as described in the docs, but how to map the rules in order for the app to behave the same?

The actual application has the following roles and static rules in Config.groovy:

// roles hierarchies
grails.plugin.springsecurity.roleHierarchy = '''
   ROLE_ADMIN > ROLE_USER
   ROLE_MANAGER> ROLE_USER
   ROLE_REPORTER > ROLE_USER
   ROLE_DEVELOPER > ROLE_USER
''' 
// ...
grails.plugin.springsecurity.controllerAnnotations.staticRules = [
    '/':                              ['permitAll'],
    '/index':                         ['permitAll'],
    '/index.gsp':                     ['permitAll'],
    '/assets/**':                     ['permitAll'],
    '/**/js/**':                      ['permitAll'],
    '/**/css/**':                     ['permitAll'],
    '/**/images/**':                  ['permitAll'],
    '/**/favicon.ico':                ['permitAll'],
    '/help/**':                       ['permitAll'], // not a controller, just a help directory with HTML files
    '/dbconsole/**':                  ['ROLE_ADMIN'], // H2 db console needs to be accessible too
    '/**/delete/**':                  ['ROLE_ADMIN'], // all delete operations can be performed only by Admins 
    '/manage/**':                     ['ROLE_MANAGER'], 
    '/report/**':                     ['ROLE_REPORTER'], 
    '/develop/**':                    ['ROLE_DEVELOPER'], 
    '/status/**':                     ['ROLE_USER'], 
    '/user/**':                       ['ROLE_USER'], 
    '/profile/**':                    ['ROLE_USER'], 
    '/auditLogEvent/**':              ['ROLE_ADMIN'], // audit (from plug-in) should be used by admins only
    '/backup/**':                     ['ROLE_ADMIN'], 
    '/support/**':                    ['IS_AUTHENTICATED_REMEMBERED'] // even users without roles need support
]

Thank you.

The grails way to set cookie secure flag?

I'm looking for the grails way to set this setting, which normally would be in shiro.ini

securityManager.sessionManager.sessionIdCookie.secure = true

The source says "Use Grails' bean property override mechanism", but I'm not sure how to do that.

Exclude dependency on servlet-api 2.5 - causes compilation failure with Grails 2.3.0

See comments on this jira http://jira.grails.org/browse/GPCACHE-33

shiro-web:1.2.0 has dependency on servlet api 2.5, which is brought into grails application as transitive dependency. Grails 2.3 comes with servlet 3 by default,
Having servlet-api 2.5 in classpath causes compilation failures for cache plugin, as it uses servlet 3 specific classes.

I think shiro should exclude dependencies on "servlet-api", "jsp-api", "jstl" - as grails already provides it.

Issue in upgrading 1.1.4 to 1.2.1. No SecurityManager accessible.

I'm trying to upgrade my application's grails version from 2.3 to 2.4. So I'm upgrading shiro plugin from version 1.1.4 to 1.2.1 too. I'm getting this error "No SecurityManager accessible to the calling code, either bound to the org.apache.shiro.util.ThreadContext or as a vm static singleton".

It looks like SecurityManager is not initialized. Previously I didn't inject that in the spring context of my application and plugin did all the things correctly. Any changes you have done in 1.2.1 related to this? With the new version, do I have to initialize SecurityManager in my application's context?

1.1.4 transitive dependencies are not resolved

  • grails create-app shiro-test
  • add compile ":shiro:1.1.4" to BuildConfig

And try to compile the app, it fails to compile shiro plugin classes.

Now add this deps to your BuildConfig.groovy

            compile 'org.apache.shiro:shiro-core:1.2.0',
             'org.apache.shiro:shiro-web:1.2.0',
              'org.apache.shiro:shiro-ehcache:1.2.0',
               'org.apache.shiro:shiro-quartz:1.2.0',
               'org.apache.shiro:shiro-spring:1.2.0',
                'org.apache.shiro:shiro-cas:1.2.0', {
                       excludes 'ejb', 'jsf-api', 'jms', 'connector-api', 'ehcache-core', 'slf4j-api'
                   }

Compile again, and it would work.

So even if shiro-1.1.4 plugin is exporting this deps. Why grails isn’t picking it up ?

Is it some thing that needs to fix in shiro, or it’s a bug with grails.. or I am missing some thing here !!

This issue does not reproduce for shiro 1.1.3 or shiro-1.2.0-SNAPSHOT

I am on win7, grails 2.2.4

See this http://grails.1312388.n4.nabble.com/What-s-wrong-with-shiro-1-1-4-transitive-dependencies-td4647414.html

Shiro authentication and authorization too?

Hi,

I the docs is mentioned:
"The majority of the authentication and authorization work is still done by Spring Security. "

Any chance having Shiro based authentication and authorization too? The whole point of using Shiro is to have those done by Shiro :( .

Thank you.

create encryption key for rememberMe manager

on this line, the shiro plugin creates a remember me manager using the default settings from shiro. Unfortunately this means it is using a hardcoded cypher key to encrypt and decrypt the cookie as seen in this line. In theory, a malicious hacker with knowledge of a user name could create a serialized PrincipalCollection with the hard coded key and appear remembered to a web application. This is of course easy to fix; just do something like shiroRememberMeManager.setCypherKey(myKey) in a bootstrap file. That said I suspect most users of this plugin are blindly using it, assuming it is more secure than this out of the box.

So I propose that a key file be generated by default and placed under ~/.grails and used to encrypt the cookie. Maybe allow the user to put a key in the Config instead. The above vulnerability may never happen due to its complexity, but the fix is pretty easy. At very least the vulnerability and work around should be documented beyond this issue.

I have to disclose that I am not a security expert and I could be way off the mark here. So if I am missing something, please tell me.

Unable to resolve class

Upgrading a Grails 1 to Grails 2. I've updated BuildConfig.groovy and ran grails refresh-dependencies but receiving "unable to resolve class org.apache.shiro.web.WebUtils" on startup.

Experimented with setting legacyResolve to true, but no joy.

Any ideas or suggestions?

BuildConfig.groovy

    plugins {
        // plugins for the build system only
        build ":tomcat:7.0.55.3" // or ":tomcat:8.0.22"

    ...
        compile "org.grails.plugins:shiro:1.2.1"

Testing AuthController fails with UnavailableSecurityManagerException

I'm having trouble setting up Shiro in my Grails application, specifically about configuration, and testing. I'm trying to set up an ini-based SecurityManager based on the quick start tutorial from official Shiro documentation, but the plugin docs doesn't describe how to do it. Deciding that I just go with the defaults (using the default DbRealm), I wrote a unit test to verify if AuthController works. However, my test fails with UnavailableSecurityManagerException.

Two issues here actually,

  1. How do I configure SecurityManager?
  2. Why am I getting the exception when testing controller.signIn()?

Edit:
My test passed when I run grails test-app integration instead of just grails test-app. So, I think the question now is, how do I unit test the AuthController?

Edit 2:
Apparently, integration tests passed because there were no integration tests to run in the first place.

Edit 3:
Transformed the unit test into an integration test but I'm still having the same issues.

error on using shiro:hasPermission tag

I get the following issue when I am using shiro:hasPermission in my GSP. I am able to use all other tags like shiro:user shiro:hasRole.

But on using shiro:hasPermission I get the following error - '
Error executing tag shiro:hasPermission: failed to lazily initialize a collection of role

Can't use custom cache manager with Grails 2.3.0

We currently use a Redis implementation for the session cache manager and it is broken with latest version of this plugin and Grails 2.3.0.

While investigating I noticed the problem is that Shiro's DefaultSerializer can't deserialize a SimpleSession object once Grails injects a GrailsFlashScope object.

Try this on grails console and you'll understand:

def session = new org.apache.shiro.session.mgt.SimpleSession()
session.setAttribute 'test', 'simple value'
//session.setAttribute 'org.codehaus.groovy.grails.FLASH_SCOPE', new org.codehaus.groovy.grails.web.servlet.GrailsFlashScope()
def s = new org.apache.shiro.io.DefaultSerializer()
s.deserialize(s.serialize(session))

Uncomment the line (simulating what Grails does) and you'll see an exception while trying to deserialize.

This works for Shiro 1.1.0. I suspect the reason is that the original DefaultSerializer implementation works with both Grails classes and Shiro's SimpleSession. But since Shiro 1.2.0 the DefaultSerializer implementation changed and the old implementation doesn't work with the newer SimpleSession deserialization.

My current solution is to use a fork of this plugin in my project and rollback the dependencies to 1.1.0 since an older version of this plugin won't work always with Grails 2.3.0.

I'd love to see a better solution for those relying on a not-in-memory session cache manager.

Any ideas?

GettingStarted and Bootstrap example code - Sha256Hash password lack of salt creates security risk for plugin users

I just used this plugin in a grails 2.5 project. I was going through the code, and I see that the GettingStarted and Bootstrap password hashing implementation introduces security risks, as documented by the Shiro Project:
"
Salting and Multiple Hash Iterations

Because simple hashing is usually not good enough for secure applications, this class also supports 'salting' and multiple hash iterations. Please read this excellent Hashing Java article to learn about salting and multiple iterations and why you might want to use them. (Note of sections 5 "Why add salt?" and 6 "Hardening against the attacker's attack"). We should also note here that all of Shiro's Hash implementations (for example, Md5Hash, Sha1Hash, etc) support salting and multiple hash iterations via overloaded constructors.
Real World Case Study

In April 2010, some public Atlassian Jira and Confluence installations (Apache Software Foundation, Codehaus, etc) were the target of account attacks and user accounts were compromised. The reason? Jira and Confluence at the time did not salt user passwords and attackers were able to use dictionary attacks to compromise user accounts (Atlassian has since fixed the problem of course).
The lesson?

ALWAYS, ALWAYS, ALWAYS SALT USER PASSWORDS!
"
http://shiro.apache.org/static/current/apidocs/org/apache/shiro/authc/credential/HashedCredentialsMatcher.html

grails 3.1.x: No such property: filtersClasses for class: grails.core.DefaultGrailsApplication

This fork is close to running in grails 3.1.4:
edwardotis@1507bee

It comes up with an error because grails 3.1 removed filters. Apparently there is a new way called interceptors. Any ideas on how to move forward on this or should we stick with 3.0.x?

Shiro Configured
ERROR org.springframework.boot.SpringApplication - Application startup failed
org.grails.core.exceptions.GrailsConfigurationException: Error configuring dynamic methods for plugin [shiro:1.2.4-SNAPSHOT]: No such property: filtersClasses for class: grails.core.DefaultGrailsApplication
    at grails.plugins.DefaultGrailsPluginManager.doDynamicMethods(DefaultGrailsPluginManager.java:714)
    at grails.boot.config.GrailsApplicationPostProcessor.onApplicationEvent(GrailsApplicationPostProcessor.groovy:227)
    at grails.boot.config.GrailsApplicationPostProcessor.onApplicationEvent(GrailsApplicationPostProcessor.groovy)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:163)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:136)
    at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:381)
    at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:335)
    at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:855)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.finishRefresh(EmbeddedWebApplicationContext.java:140)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:541)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:766)
    at org.springframework.boot.SpringApplication.createAndRefreshContext(SpringApplication.java:361)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:307)
    at grails.boot.GrailsApp.run(GrailsApp.groovy:55)
    at grails.boot.GrailsApp.run(GrailsApp.groovy:365)
    at grails.boot.GrailsApp.run(GrailsApp.groovy:354)
    at grails.boot.GrailsApp$run.call(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:133)
    at grails314shiroexample.Application.main(Application.groovy:8)
Caused by: groovy.lang.MissingPropertyException: No such property: filtersClasses for class: grails.core.DefaultGrailsApplication
    at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:53)
    at org.codehaus.groovy.runtime.callsite.PogoGetPropertySite.getProperty(PogoGetPropertySite.java:52)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callGetProperty(AbstractCallSite.java:296)
    at shiro.ShiroGrailsPlugin.doWithDynamicMethods(ShiroGrailsPlugin.groovy:290)
    at org.grails.plugins.DefaultGrailsPlugin.doWithDynamicMethods(DefaultGrailsPlugin.java:750)
    at grails.plugins.DefaultGrailsPluginManager.doDynamicMethods(DefaultGrailsPluginManager.java:711)
    ... 21 common frames omitted

Config keys

Now the config namespace is security.shiro, I think grails.plugin.shirosecurity is more grails way.

How are the default permissions granted (It is a question, not an issue)

I'm going through the plugin's code since one week now, I just trying to figure out how the SecuritManager is setup.

First, I don't see any example that explain how to use the DSL in the controllers's static accessControl closure. The role I define using the role method in AccessControlBuilder should be an existing role in the database ? if not how is it stored ? Same question for permission.

Second, I don't see where the default permissions are granted to roles or subjects, I mean the controller:action[:id] used when the accessControl closure is null.
To be more specific, consider this snippet from ShiroGrailsPlugin.groovy, in the accessControlMethod method:

    def isPermitted
    if (c == null) {
        // Check that the user has the required permission for the target controller/action.
        def permString = new StringBuilder()
        permString << filter.controllerName << ':' << (filter.actionName ?: "index")
        // Add the ID if it's in the web parameters.
        if (filter.params.id) permString << ':' << filter.params.id

        isPermitted = subject.isPermitted(permString.toString())
    } else {
       ...
   }

How isPermitted = subject.isPermitted(permString.toString()) can return true, even when I don't have any permissions in the database.

Again, sorry for this question, I am just trying to understand the code.

Thanks.

Upgrade script error on Windows when upgrading grails

I upgraded a grails app using the plugin (v 1.2.0) from 2.3.4 to 2.3.5. And saw this error (seems to do with WIndows-style path):

| Executing shiro-1.2.0 plugin upgrade script
| Error Error executing script Upgrade: org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
Script1.groovy: 1: unexpected char: '\' @ line 1, column 20.
   def pluginDir = 'C:\Users\Ben\Documents\GitHub\my-app\target\work\plugins\shiro-1.2.0'
                      ^

1 error
 (Use --stacktrace to see the full trace)

Error doesn't seem to have affected anything, as the app still works fine under grails 2.3.5, but it was unclear whether the application upgrade progress had been halted due to the shiro error.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.