Groovy Metaclassを使用してBootstrapでShiro SecurityUtilsをock笑する
-
19-09-2019 - |
質問
さらに背景については、参照してください http://grails.markmail.org/message/62w2xpbgneapmhpd
shiro securityutils.getSubject()メソッドをbootstrap.groovyでock笑しようとしています。最新のShiroバージョンのサブジェクトビルダーは、Nimbleプラグインの現在のバージョン(私が使用している)で利用できないため、このアプローチを決定しました。私はSecurityUtils.Metaclassで遊んでみることにしましたが、私はメタラスがどのように機能するかについて非常に基本的な何かを見逃していると感じています。参照のために、ここに私の追跡可能なクラスがあります:
abstract class Trackable {
User createdBy
Date dateCreated
User lastUpdatedBy
Date lastUpdated
static constraints = {
lastUpdated(nullable:true)
lastUpdatedBy(nullable:true)
createdBy(nullable:true)
}
def beforeInsert = {
def subject
try {
subject = SecurityUtils.subject
} catch (Exception e) {
log.error "Error obtaining the subject. Message is [${e.message}]"
}
createdBy = (subject ? User.get( subject.principal ) :
User.findByUsername("admin"))
}
def beforeUpdate = {
def subject
try {
subject = SecurityUtils.subject
} catch (Exception e) {
log.error "Error obtaining the subject. Message is [${e.message}]"
}
lastUpdatedBy = (subject ? User.get( subject.principal ) :
User.findByUsername("admin"))
}
}
私のbootstrap.groovyで、私はこれを持っています:
def suMetaClass = new ExpandoMetaClass(SecurityUtils)
suMetaClass.'static'.getSubject = {[getPrincipal:{2}, toString:{"Canned Subject"}] as Subject}
suMetaClass.initialize()
SecurityUtils.metaClass = suMetaClass
そしてそれはうまくいきます...ある種。 bootstrap.groovyから被写体を印刷すると、「缶詰の被験者」が得られます。トラック可能なサブクラスのインスタンスを作成して保存しようとすると、次のようになります。
No SecurityManager accessible to this method, either bound to the org.apache.shiro.util.ThreadContext or as a vm static singleton. See the org.apache.shiro.SecurityUtils.getSubject() method JavaDoc for an explanation of expected environment configuration.
メタラスの仕組みについて不可欠なものがありませんか?
解決
何が起こっているのかを理解しました。私のブートストラップで私はこのようなことをしていました:
def init = { servletContext->
switch (Environment.current.name) {
case "local":
def suMetaClass = new ExpandoMetaClass(SecurityUtils)
suMetaClass.'static'.getSubject = {[getPrincipal:{2}, toString:{"Canned Subject"}] as Subject}
suMetaClass.initialize()
SecurityUtils.metaClass = suMetaClass
new TrackableSubClass().save()
//Create some other domain instances
SecurityUtils.metaClass = null
}
//Create a couple domain instances that aren't environment specific
}
いくつかのデバッグステートメントを追加し、私が見たエラーが初期閉鎖の終了時に起こっていることを確認しました。ハイバーネートセッションを洗い流す方法を再確認するためにグーグルをいくつかしました。次に、次の変更を加えました。
def sessionFactory
def init = { servletContext->
switch (Environment.current.name) {
case "local":
def suMetaClass = new ExpandoMetaClass(SecurityUtils)
suMetaClass.'static'.getSubject = {[getPrincipal:{2}, toString:{"Canned Subject"}] as Subject}
suMetaClass.initialize()
SecurityUtils.metaClass = suMetaClass
new TrackableSubClass().save()
//Create some other domain instances
sessionFactory.currentSession.flush()
SecurityUtils.metaClass = null
}
//Create a couple domain instances that aren't environment specific
}
それは問題を完全に解決したようで、今では追跡可能な扱いにくいトライ/キャッチブロックを削除できるはずです。 :-)
所属していません StackOverflow