2017-06-01 85 views
0

如何使用authority-string獲取特定角色的實例? 我幾乎所有的東西,但我總是得到空的結果。 贊:Role.get('ROLE_ADMIN')返回null。Grails在spring-scurity-core中無法獲得Role-class的實例

在usercontroller中定義了一個應該爲指定用戶添加/刪除角色的操作。下面的代碼包含了很多testcode和everyhing看起來工作,只是我無法從角色類獲得實例

def userroles() { 
    def user = User.get(params.id) 
    List<String> userRoles = roleNamesFromUser(user) 
    List<String> uRoles = roleNamesFromParams() 
    println(">> ROLES >>> params: "+uRoles) 
    println(">> ROLES >>> userRoles: "+userRoles) 

    for (uRole in uRoles) { 
     println("#### Params: "+uRole) 
     if (uRole in userRoles) { 
      println("#### Role already used: "+uRole) 

     } else { 
      println("#### userRole to be Created1: "+uRole) 
      def role = Role.findByAuthority(uRole) 
//    println("#### userRole to be Created2: "+role.authority) 
//    UserRole.create user, role 
      def ur = new UserRole(user:user, role: role).save(flush:true, failOnError:true) 
      println("#### Role Created: "+ur.role.authority+" - username: "+ur.user.username) 
     } 
    } 
    for (role in userRoles) { 
     if (role in uRoles) { 
      println("#### Role already exist: "+role) 

     } else { 
      Role.findByAuthority(uRole).delete() 
      println("#### Role deleted: "+role) 
     } 
    } 
    userRoles = roleNamesFromUser(user) 
    for (role in userRoles) { 
     println("#### After update - Role: "+role) 
    } 


    UserRole.withSession { 
     it.flush() 
     it.clear() 
    } 

    redirect action:"index" 
} 
protected List<String> roleNamesFromParams() { 
params.keySet().findAll { it.contains('ROLE_') && params[it] == 'on' } as List 
} 
protected List<String> roleNamesFromUser(User user) { 
    def ur = user.getAuthorities().toList() 
    def List<String> ul = new ArrayList<String>() 
    def String auth 
    for(int i=0; i<ur.size; i++){ 
     auth = ur[i].authority 
     ul.add(auth) 
    } 
    return ul 
} 

控制檯顯示這在運行:

>> ROLES >>> params: [ROLE_ADMIN, ROLE_SALES, ROLE_SUPPLIER] 
>> ROLES >>> userRoles: [ROLE_ADMIN] 
%%%%% ROLE_ADMIN %%%%%#### Params: ROLE_ADMIN 
#### Role already used: ROLE_ADMIN 
#### Params: ROLE_SALES 
#### userRole to be Created1: ROLE_SALES 
2017-06-01 15:40:34.388 ERROR --- [nio-8080-exec-1] o.g.web.errors.GrailsExceptionResolver : ValidationException occurred when processing request: [POST] /user/userroles - parameters: 
version: 0 
id: 9 
_ROLE_ADMIN: 
ROLE_ADMIN: on 
_ROLE_USER: 
_ROLE_SALES: 
ROLE_SALES: on 
_ROLE_SUPPLIER: 
ROLE_SUPPLIER: on 
Validation Error(s) occurred during save(): 
- Field error in object 'com.torntrading.security.UserRole' on field 'role': rejected value [null]; codes [com.torntrading.security.UserRole.role.nullable.error.com.torntrading.security.UserRole.role,com.torntrading.security.UserRole.role.nullable.error.role,com.torntrading.security.UserRole.role.nullable.error.com.torntrading.security.Role,com.torntrading.security.UserRole.role.nullable.error,userRole.role.nullable.error.com.torntrading.security.UserRole.role,userRole.role.nullable.error.role,userRole.role.nullable.error.com.torntrading.security.Role,userRole.role.nullable.error,com.torntrading.security.UserRole.role.nullable.com.torntrading.security.UserRole.role,com.torntrading.security.UserRole.role.nullable.role,com.torntrading.security.UserRole.role.nullable.com.torntrading.security.Role,com.torntrading.security.UserRole.role.nullable,userRole.role.nullable.com.torntrading.security.UserRole.role,userRole.role.nullable.role,userRole.role.nullable.com.torntrading.security.Role,userRole.role.nullable,nullable.com.torntrading.security.UserRole.role,nullable.role,nullable.com.torntrading.security.Role,nullable]; arguments [role,class com.torntrading.security.UserRole]; default message [Property [{0}] of class [{1}] cannot be null] 
. Stacktrace follows: 

java.lang.reflect.InvocationTargetException: null 
    at org.grails.core.DefaultGrailsControllerClass$ReflectionInvoker.invoke(DefaultGrailsControllerClass.java:210) 
    at org.grails.core.DefaultGrailsControllerClass.invoke(DefaultGrailsControllerClass.java:187) 
    at org.grails.web.mapping.mvc.UrlMappingsInfoHandlerAdapter.handle(UrlMappingsInfoHandlerAdapter.groovy:90) 
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963) 
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897) 
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) 
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872) 
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) 
    at org.springframework.boot.web.filter.ApplicationContextHeaderFilter.doFilterInternal(ApplicationContextHeaderFilter.java:55) 
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:317) 
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:127) 
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91) 
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) 
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:115) 
    at grails.plugin.springsecurity.web.UpdateRequestContextHolderExceptionTranslationFilter.doFilter(UpdateRequestContextHolderExceptionTranslationFilter.groovy:64) 
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) 
    at grails.plugin.springsecurity.web.filter.GrailsAnonymousAuthenticationFilter.doFilter(GrailsAnonymousAuthenticationFilter.groovy:53) 
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) 
    at org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter.doFilter(RememberMeAuthenticationFilter.java:158) 
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) 
    at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:169) 
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) 
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:200) 
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) 
    at grails.plugin.springsecurity.web.authentication.logout.MutableLogoutFilter.doFilter(MutableLogoutFilter.groovy:62) 
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) 
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105) 
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) 
    at grails.plugin.springsecurity.web.SecurityRequestHolderFilter.doFilter(SecurityRequestHolderFilter.groovy:58) 
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) 
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:214) 
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:177) 
    at org.grails.web.servlet.mvc.GrailsWebRequestFilter.doFilterInternal(GrailsWebRequestFilter.java:77) 
    at org.grails.web.filters.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:67) 
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) 
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) 
    at java.lang.Thread.run(Thread.java:745) 
Caused by: grails.validation.ValidationException: Validation Error(s) occurred during save(): 
- Field error in object 'com.torntrading.security.UserRole' on field 'role': rejected value [null]; codes [com.torntrading.security.UserRole.role.nullable.error.com.torntrading.security.UserRole.role,com.torntrading.security.UserRole.role.nullable.error.role,com.torntrading.security.UserRole.role.nullable.error.com.torntrading.security.Role,com.torntrading.security.UserRole.role.nullable.error,userRole.role.nullable.error.com.torntrading.security.UserRole.role,userRole.role.nullable.error.role,userRole.role.nullable.error.com.torntrading.security.Role,userRole.role.nullable.error,com.torntrading.security.UserRole.role.nullable.com.torntrading.security.UserRole.role,com.torntrading.security.UserRole.role.nullable.role,com.torntrading.security.UserRole.role.nullable.com.torntrading.security.Role,com.torntrading.security.UserRole.role.nullable,userRole.role.nullable.com.torntrading.security.UserRole.role,userRole.role.nullable.role,userRole.role.nullable.com.torntrading.security.Role,userRole.role.nullable,nullable.com.torntrading.security.UserRole.role,nullable.role,nullable.com.torntrading.security.Role,nullable]; arguments [role,class com.torntrading.security.UserRole]; default message [Property [{0}] of class [{1}] cannot be null] 

    at org.grails.orm.hibernate.AbstractHibernateGormInstanceApi.save(AbstractHibernateGormInstanceApi.groovy:131) 
    at org.grails.datastore.gorm.GormEntity$Trait$Helper.save(GormEntity.groovy:151) 
    at com.torntrading.security.UserController$$EQLIup0W.$tt__userroles(UserController.groovy:46) 
    at grails.transaction.GrailsTransactionTemplate$2.doInTransaction(GrailsTransactionTemplate.groovy:96) 
    at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:133) 
    at grails.transaction.GrailsTransactionTemplate.execute(GrailsTransactionTemplate.groovy:93) 
    ... 37 common frames omitted 

=== =================================

該數據庫包含此:

id version authority 
1 0 ROLE_ADMIN 
2 0 ROLE_USER 
3 0 ROLE_SALES 
4 0 ROLE_SUPPLIER 
+0

數據庫角色是否實際上以ROLE_開頭?我知道當我創建LDAP組時,我沒有使用ROLE_作爲前綴,但在爲用戶檢查角色時,我必須添加前綴,因此假設插件前綴(如果不存在)。 –

+0

是的,它的確如此。在我的問題的底部,有一個來自數據庫的打印輸出。 – larand

回答

0

有你試過這種方式:Role.findByAuthority("ROLE_ADMIN")

+0

是的!那樣做了!我已經嘗試過,但是授權字符串有問題。我不知道如何使用這個簡單的課程。經過一些失敗的測試後,我終於發現,我認爲是一個簡單的字符串,只包含'ROLE_ADMIN'我有'[UserRole authority:ROLE_ADMIN]'之類的東西。然後我測試了不同的解決方案,並忘記了「findByAuthority」只記得它不起作用。好吧,現在它可以工作,非常感謝,這是我遇到過的最令人沮喪的問題。 – larand