本文介绍了从android http post登录到grails 3 spring security的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 例如:我在端口8080上运行我的grails应用程序, localhost:8080 然后我使用 POSTMAN 并传递这样的参数.. 它像这样的成功.. 但为什么我无法登录我的Android应用程序。 像这样.. public static String performPostCall(String requestURL, HashMap< String,String> postDataParams){ Log.d(url =,requestURL); 网址; String response =; 尝试{ url = new URL(requestURL); HttpURLConnection conn =(HttpURLConnection)url.openConnection(); conn.setReadTimeout(45000); conn.setConnectTimeout(45000); conn.setRequestMethod(POST); conn.setRequestProperty(Content-Type,form-data); conn.setDoInput(true); conn.setDoOutput(true); OutputStream os = conn.getOutputStream(); BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(os,UTF-8)); writer.write(getPostDataString(postDataParams)); writer.flush(); writer.close(); os.close(); int responseCode = conn.getResponseCode(); System.out.println(。toString()=+ responseCode); System.out.println(。HttpsURLConnection.HTTP_OK =+ HttpsURLConnection.HTTP_OK); if(responseCode == HttpsURLConnection.HTTP_OK){ String line; BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); ((line = br.readLine())!= null){ response + = line; while } } else { response =; } } catch(Exception e){ e.printStackTrace(); } 返回响应; private static String getPostDataString(HashMap< String,String> params)throws UnsupportedEncodingException { StringBuilder result = new StringBuilder(); boolean first = true; (Map.Entry< String,String> entry:params.entrySet()){ Log.d(entry.getKey()=,entry.getKey()); Log.d(entry.getValue()=,entry.getValue()); if(first) first = false; else result.append(&); result.append(URLEncoder.encode(entry.getKey(),UTF-8)); result.append(=); result.append(URLEncoder.encode(entry.getValue(),UTF-8)); } System.out.println(tetstes =+ result.toString()); return result.toString(); } 然后 protected void void doInBackground(Void ... params){ // TODO自动生成的方法存根 HashMap< String,String>参数= new HashMap< String,String>(); parameter.put(username,username); parameter.put(password,password); try { response = MyHttpURLConnection.performPostCall(URL,parameter); } catch(Exception e){ System.out.println(assdfdsf =+ e); // TODO自动生成的catch块 e.printStackTrace(); } 返回null; } 它始终在 def ajaxSuccess SpringSecurityServlet.getCurrentUser()像这样。 def ajaxSuccess(){ // printlnadf =+ springSecurityService.authentication.username printlncookies =+ session.id def cifus = springSecurityService.getCurrentUser() printlncifus =+ cifus // printlnadf =+ springSecurityService。 principal.id def user = com.vastpalaso.security.User.findByUsername(springSecurityService.authentication.name) def userDetails = com.vastpalaso.security.UserDetails.findByUser(user) def cifUser = corporateUserService.getCurrentCifUser() printlnuser =+ user // printlncif user =+ cifUser // printlncif user =+ cifUser .cif.corpName // if(cifUser){ // session.setAttribute(company,cifUser.cif.corpName) // if(new Date()> cifUser.cif.expireDate){ // redirect(controller:error,action:serverError) //} //} // // if(userDetails.isLogin.equals 1)){ // def sessionx = HttpSessionCollector.find(userDetails.sessionId) // if(sessionx){ // sessionx.invalidate() / / HttpSessionCollector.remove(userDetails.sessionId) //} //} 尝试{ def ipAddress = request。 (!ipAddress){ ipAddress = request.getHeader(X-Forwarded-For)} if(!ipAddress)getHeader(Client-IP) { ipAddress = request.getRemoteAddr()} 尝试{ cifService.resetTryLoginAddInfo(use (例外e){ printlne =+ e } session.setAttribute(别名 ,userDetails.userAlias) session.setAttribute(fullName,userDetails.firstName ++ userDetails.lastName) session.setAttribute(change,userDetails.forceChangePassword) session。 (userDetails.language!= null){ session [org.springframework.web.servlet.i18n.SessionLocaleResolver。 LOCALE(userDetails.language)} else { session [org.springframework.web.servlet.i18n.SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME] = new Locale(id)} buildMenuList() if(params.callback){ render$ {params.callback}($ {[ )成功:true,id:userDetails.id,更改:userDetails.forceChangePassword,用户名:springSecurityService.authentication.name,全名:(userDetails.firstName ++ userDetails.lastName)]作为JSON})} else { render([success:true,id:userDetails.id,change:userDetails.forceChangePassword,username:springSecurityService.authentication.name,fullName:(userDetails.firstName ++ userDetails.lastName) ]作为JSON)} } //捕获未知的RuntimeException,重定向到Error 500服务器错误页面 catch(RuntimeException e){ logger.error(e .getMessage(),e)重定向(controller:error,action:serverError) return } render([success:true,username:authentication。名称]为JSON)} 但我总是得到这个错误日志。 DEBUG org.springframew ork.security.web.FilterChainProxy - / login / ajaxSuccess到达附加过滤器链的末尾;进行原始链接 cookies = F866B5D4267DD54163C93FD3DB1EADB5 cifus = null 错误org.grails.web.errors.GrailsExceptionResolver - 处理请求时发生MissingPropertyException:[GET] / login / ajaxSuccess 没有这样的属性:id为class:org.springframework.security.core.userdetails.User。 Stacktrace如下: groovy.lang.MissingPropertyException:没有这样的属性:id为class:org.springframework.security.core.userdetails.User at com.vastpalaso.CorporateUserService.getCurrentCifUser(CorporateUserService.groovy:950 )〜[main /:na] at accounter.LoginController $$ EQ0tGOPB.ajaxSuccess(LoginController.groovy:168)〜[na:na] at grails.plugin.springsecurity.web.UpdateRequestContextHolderExceptionTranslationFilter.doFilter (GrailsAnonymousAuthenticationFilter.groovy:53)〜[spring-security-core-3.1.1.jar:na] spring-security-core-3.1.1.jar:na] 在grails.plugin.springsecurity.web.authentication.logout.MutableLogoutFilter.doFilter(MutableLogoutFilter.groovy:62)〜[spring-security-core-3.1 .1.jar:na]在grails.plugin.springsecurity.web.SecurityRequestHolderFil上 [java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)〜[na] :1.8.0_111] at java.util.concurrent.ThreadPoolExecutor $ Worker.run(ThreadPoolExecutor.java:617)〜[na:1.8.0_111] at java.lang.Thread.run(Thread .java:745)[na:1.8.0_111] DEBUG org.springframework.security.web.context.HttpSessionSecurityContextRepository - SecurityContext为空或内容为匿名 - 上下文不会存储在HttpSession中。 DEBUG org.springframework.security.web.context.HttpSessionSecurityContextRepository - SecurityContext为空或内容为匿名 - 上下文不会存储在HttpSession中。 DEBUG org.springframework.security.web.context.SecurityContextPersistenceFilter - SecurityContextHolder现在已被清除,因为请求处理已完成 DEBUG org.springframework.security.web.context.SecurityContextPersistenceFilter - SecurityContextHolder现已清除,因为请求处理已完成 这是日志 DEBUG org.springframework.security.web.FilterChainProxy - / login / authenticate?spring-security-redirect = / login / ajaxSuccess在附加过滤器链中的位置1的9处;在过滤器的另一个链中,位置1的第1个位置上的spring-security-redirect = / login / authenticate?spring-security-redirect = / login / ajaxSuccess过滤器:'SecurityRequestHolderFilter' DEBUG org.springframework.security.web.FilterChainProxy;在另一个过滤器链中,第2个位置的第2个位置为/admin/ajaxSuccess。在另一个过滤器链中,在位置2的9位置处弹出安全重定向= / login / authenticate?spring-security-redirect = / login / ajaxSuccess。发射过滤器:'SecurityContextPersistenceFilter' DEBUG org.springframework.security.web.context.HttpSessionSecurityContextRepository - 目前不存在HttpSession DEBUG org.springframework.security.web.context.HttpSessionSecurityContextRepository - 目前不存在HttpSession DEBUG org.springframework.security.web.context.HttpSessionSecurityContextRepository - HttpSession中没有SecurityContext:null。一个新的将被创建。 DEBUG org.springframework.security.web.context.HttpSessionSecurityContextRepository - HttpSession中没有SecurityContext可用:null。一个新的将被创建。 DEBUG org.springframework.security.web.FilterChainProxy - / login / authenticate?spring-security-redirect = / login / ajaxSuccess在附加过滤器链中位置3的9处;在另一个过滤器链中,在位置3中的第3位上弹出过滤器:'MutableLogoutFilter' DEBUG org.springframework.security.web.FilterChainProxy - / login / authenticate?spring-security-redirect = / login / ajaxSuccess发射过滤器:'MutableLogoutFilter' DEBUG org.springframework.security.web.util.matcher.AntPathRequestMatcher - 检查请求匹配:'/ login / authenticate';针对'/ logoff' DEBUG org.springframework.security.web.util.matcher.AntPathRequestMatcher - 检查请求匹配:'/ login / authenticate'; '/ logoff' DEBUG org.springframework.security.web.FilterChainProxy - / login / authenticate?spring-security-redirect = / login / ajaxSuccess在9位的第4位,位于附加的过滤器链中;在另外的过滤器链中,第9位的第4位的spring-security-redirect = / login / authenticate?spring-security-redirect = / login / authenticate?开发过滤器:'GrailsUsernamePasswordAuthenticationFilter' DEBUG org.springframework.security.authentication.ProviderManager - 使用org.springframework.security.authentication.dao.DaoAuthenticationProvider进行身份验证尝试 DEBUG org.springframework.security.authentication.ProviderManager - 使用org.springframework.security.authentication.dao.DaoAuthenticationProvider 进行身份验证尝试DEBUG org.springframework.security.authentication.dao.DaoAuthenticationProvider - 未找到用户 DEBUG org.springframework.security.authentication.dao .DaoAuthenticationProvider - 用户'找不到 DEBUG org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices - 交互式登录尝试失败。 DEBUG org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices - 交互式登录尝试失败。 DEBUG org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices - 取消cookie DEBUG org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices - 取消cookie DEBUG org.springframework .security.web.context.HttpSessionSecurityContextRepository - SecurityContext为空或内容为匿名 - 上下文不会存储在HttpSession中。 DEBUG org.springframework.security.web.context.HttpSessionSecurityContextRepository - SecurityContext为空或内容为匿名 - 上下文不会存储在HttpSession中。 DEBUG org.springframework.security.web.context.SecurityContextPersistenceFilter - SecurityContextHolder现在已被清除,因为请求处理已完成 DEBUG org.springframework.security.web.context.SecurityContextPersistenceFilter - SecurityContextHolder现已清除,因为请求处理已完成 DEBUG org.springframework.security.web.util.matcher.AntPathRequestMatcher - 检查请求匹配:'/ login / authfail';反对'/ assets / **' DEBUG org.springframework.security.web.util.matcher.AntPathRequestMatcher - 检查请求的匹配:'/ login / authfail';反对'/ assets / **' DEBUG org.springframework.security.web.util.matcher.AntPathRequestMatcher - 检查请求的匹配:'/ login / authfail';反对'/ ** / js / **' DEBUG org.springframework.security.web.util.matcher.AntPathRequestMatcher - 检查请求匹配:'/ login / authfail';反对'/ ** / js / **' DEBUG org.springframework.security.web.util.matcher.AntPathRequestMatcher - 检查请求匹配:'/ login / authfail';针对'/ ** / css / **' DEBUG org.springframework.security.web.util.matcher.AntPathRequestMatcher - 检查请求匹配:'/ login / authfail';针对'/ ** / css / **' DEBUG org.springframework.security.web.util.matcher.AntPathRequestMatcher - 检查请求匹配:'/ login / authfail';反对'/ ** / images / **' DEBUG org.springframework.security.web.util.matcher.AntPathRequestMatcher - 检查请求匹配:'/ login / authfail';反对'/ ** / images / **' DEBUG org.springframework.security.web.util.matcher.AntPathRequestMatcher - 检查请求匹配:'/ login / authfail';反对'/**/favicon.ico' DEBUG org.springframework.security.web.util.matcher.AntPathRequestMatcher - 检查请求匹配:'/ login / authfail';反对'/**/favicon.ico' DEBUG org.springframework.security.web.util.matcher.AntPathRequestMatcher - 通过通用模式匹配'/ login / authfail'/ **' DEBUG org.springframework.security.web.util.matcher.AntPathRequestMatcher - 通过通用模式'/ **'匹配请求'/ login / authfail' DEBUG org.springframework.security.web.FilterChainProxy - / login / authfail?在额外的过滤器链中,位置1处的login_error = 1;安装过滤器:'SecurityRequestHolderFilter' DEBUG org.springframework.security.web.FilterChainProxy - / login / authfail?login_error = 1位于附加过滤器链中的第1位;安装过滤器:'SecurityRequestHolderFilter' DEBUG org.springframework.security.web.FilterChainProxy - / login / authfail?login_error = 1在附加过滤器链中位置2的9处;在另外的过滤器链中,在9的位置2上的/ login / authfail?login_error = 1;发射过滤器:'SecurityContextPersistenceFilter' DEBUG org.springframework.security.web.context.HttpSessionSecurityContextRepository - 目前不存在HttpSession DEBUG org.springframework.security.web.context.HttpSessionSecurityContextRepository - 目前不存在HttpSession DEBUG org.springframework.security.web.context.HttpSessionSecurityContextRepository - HttpSession中没有SecurityContext:null。一个新的将被创建。 DEBUG org.springframework.security.web.context.HttpSessionSecurityContextRepository - HttpSession中没有SecurityContext可用:null。一个新的将被创建。 DEBUG org.springframework.security.web.FilterChainProxy - / login / authfail?login_error = 1位于附加过滤器链中的第9位;在另一个过滤器链中,位于第3位的第3个位置处的登录错误= / login / authfail?login_error = 1;发射过滤器:'MutableLogoutFilter' DEBUG org.springframework.security.web.util.matcher.AntPathRequestMatcher - 检查请求匹配:'/ login / authfail';反对'/注销' DEBUG org.springframework.security.web.util.matcher.AntPathRequestMatcher - 检查请求匹配:'/ login / authfail';反对'/ logoff' DEBUG org.springframework.security.web.FilterChainProxy - / login / authfail?login_error = 1在第9位的另一个过滤器链中;在另外的过滤器链中,9位的第4位的login_error = 1; / login / authfail?login_error = 1。在另一个过滤器链中,位于第5位的9个位置处的登录错误= 1; / login / authfail?login_error = 1;在另一个过滤器链中,在第9位的第5个位置使用/ login / authfail?login_error = 1;在另外的过滤器链中,位于第9位的第6位的login_error = 1; / login / authfail?login_error = 1。在另外的过滤器链中,位置9的位置6处的登录错误= / login / authfail?login_error = 1;在另外的过滤器链中,在第9位的第7位登录错误= / login / authfail?login_error = 1;在另外的过滤器链中,在第9位的第7个位置处登录错误= / login / authfail?login_error = 1;开发过滤器:'GrailsAnonymousAuthenticationFilter' INFO org.springframework.security.core.SpringSecurityCoreVersion - 您正在运行Spring Security Core 4.0.3.RELEASE INFO org.springframework.security.core.SpringSecurityCoreVersion - 您是使用Spring Security Core 4.0.3.RELEASE DEBUG运行org.springframework.security.web.FilterChainProxy - / login / authfail?login_error = 1在附加过滤器链中第9位的第8位; FilterRequestContextHolderExceptionTranslationFilter' DEBUG org.springframework.security.web.FilterChainProxy - / login / authfail?login_error = 1位于附加过滤器链中的第8位; FilterRequestContextHolderExceptionTranslationFilter' DEBUG org.springframework.security.web.FilterChainProxy - / login / authfail?login_error = 1在附加过滤器链中第9位的9位; FilterSecurityInterceptor DEBUG org.springframework.security.web.FilterChainProxy - / login / authfail?login_error = 1在附加过滤器链中第9位的9位;点击Filter:'FilterSecurityInterceptor' DEBUG org.springframework.security.web.access.intercept.FilterSecurityInterceptor - 安全对象:FilterInvocation:URL:/ login / authfail?login_error = 1;属性:[IS_AUTHENTICATED_ANONYMOUSLY] DEBUG org.springframework.security.web.access.intercept.FilterSecurityInterceptor - 安全对象:FilterInvocation:URL:/ login / authfail?login_error = 1;属性:[IS_AUTHENTICATED_ANONYMOUSLY] DEBUG org.springframework.security.web.access.intercept.FilterSecurityInterceptor - 先前已验证:grails.plugin.springsecurity.authentication.GrailsAnonymousAuthenticationToken@f23b441a:主体:org.springframework.security.core.userdetails .User @ dc730200:用户名:__grails.anonymous.user__;密码保护];启用:false; AccountNonExpired:false; credentialsNonExpired:false; AccountNonLocked:false;授予权限:ROLE_ANONYMOUS;证书:[PROTECTED];已验证:true;详细信息:org.springframework.security.web.authentication.WebAuthenticationDetails@ffffe21a:RemoteIpAddress:192.168.100.9; SessionId:null;授予权限:ROLE_ANONYMOUS DEBUG org.springframework.security.web.access.intercept.FilterSecurityInterceptor - 先前已验证:grails.plugin.springsecurity.authentication.GrailsAnonymousAuthenticationToken@f23b441a:Principal:org.springframework.security.core.userdetails。 User @ dc730200:用户名:__grails.anonymous.user__;密码保护];启用:false; AccountNonExpired:false; credentialsNonExpired:false; AccountNonLocked:false;授予权限:ROLE_ANONYMOUS;证书:[PROTECTED];已验证:true;详细信息:org.springframework.security.web.authentication.WebAuthenticationDetails@ffffe21a:RemoteIpAddress:192.168.100.9; SessionId:null;授予的权限:ROLE_ANONYMOUS DEBUG org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl - getReachableGrantedAuthorities() - 从角色[ROLE_ANONYMOUS]可以在零个或多个步骤中达到[ROLE_ANONYMOUS]。 DEBUG org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl - getReachableGrantedAuthorities() - 从角色[ROLE_ANONYMOUS]可以在零个或多个步骤中达到[ROLE_ANONYMOUS]。 DEBUG org.springframework.security.web.access.intercept.FilterSecurityInterceptor - 授权成功 DEBUG org.springframework.security.web.access.intercept.FilterSecurityInterceptor - 授权成功 DEBUG org.springframework .security.web.access.intercept.FilterSecurityInterceptor - RunAsManager未更改身份验证对象 DEBUG org.springframework.security.web.access.intercept.FilterSecurityInterceptor - RunAsManager未更改身份验证对象 DEBUG org.springframework .security.web.FilterChainProxy - / login / authfail?login_error = 1到达附加过滤器链的末尾;继续使用原始链 DEBUG org.springframework.security.web.FilterChainProxy - / login / authfail?login_error = 1到达附加过滤器链的末尾;继续使用原始链 DEBUG org.springframework.security.web.context.HttpSessionSecurityContextRepository - SecurityContext为空或内容为匿名 - 上下文不会存储在HttpSession中。 DEBUG org.springframework.security.web.context.HttpSessionSecurityContextRepository - SecurityContext为空或内容为匿名 - 上下文不会存储在HttpSession中。 DEBUG org.springframework.security.web.context.HttpSessionSecurityContextRepository $ SaveToSessionResponseWrapper - 在上跳过调用DEBUG org.springframework.security.web.context.HttpSessionSecurityContextRepository $ SaveToSessionResponseWrapper - 在上跳过调用ERROR org .grails.web.errors.GrailsExceptionResolver - 处理请求时发生CannotRedirectException:[GET] / login / authfail - 参数: login_error:1 这里不能发出重定向(..)。响应已被提交或者通过另一个重定向或直接写入响应.. Stacktrace如下: grails.web.mapping.mvc.exceptions.CannotRedirectException:无法在此处发出重定向(..)。该响应已通过另一重定向或直接写入响应提交。 application.groovy grails.plugin.springsecurity.userLookup.userDomainClassName ='com.vastpalaso.security.User' grails.plugin.springsecurity.userLookup.authorityJoinClassName ='com.vastpalaso.security.UserRole' grails.plugin.springsecurity.authority.className ='com.vastpalaso.security.Role' grails.plugin.springsecurity.requestMap.className ='com.vastpalaso.security.RequestMap' grails。 plugin.springsecurity.securityConfigType ='Requestmap' grails.plugin.springsecurity.controllerAnnotations.staticRules = [ [pattern:'/',access:['permitAll']], [pattern :'/ error',access:['permitAll']], [pattern:'/ index',access:['permitAll']], [pattern:'/index2.gsp', access:['permitAll']], [pattern:'/ shutdown',access:['permitAll']], [pattern:'/ assets / **',access:['permitAll']], [pattern:'/ ** / js / **',access:['permitAll']], [pattern:'/ * * / css / **',access:['permitAll']], [pattern:'/ ** / images / **',access:['permitAll']], [pattern :'/**/favicon.ico',access:['permitAll']] ] grails.plugin.springsecurity.filterChain.chainMap = [ [pattern: '/ assets / **',过滤器:'none'], [pattern:'/ ** / js / **',过滤器:'none'], [pattern:'/ * * / css / **',filters:'none'], [pattern:'/ ** / images / **',filters:'none'], [pattern:'/ * * / favicon.ico',filters:'none'], [pattern:'/ **',filters:'JOINED_FILTERS'] ] 在我添加以下代码后,我的错误日志变为像这样 lockquote org.springframework.security.authentication。 dao.DaoAuthenticationProvider 未找到用户 关于提供的链接幻灯片6它说发射organizationFilter 当您查看安全过滤器。它们实际上就是我前面提到的那些静态规则。 所以有一些冲突存在,规则被绕过,然后尝试登录(没有用户凭证) 。 这里所有的日志只是一个正确解释的问题。 正确.. 注释掉这首 // grails.plugin.springsecurity.securityConfigType ='Requestmap' //然后添加 grails.plugin.springsecurity.controllerAnnotations.staticRules = [ [pattern:'/',access:['permitAll']], [pattern:'/ error',access:['permitAll'] ], [pattern:'/ index',access:['permitAll']], [pattern:'/index2.gsp',access:['permitAll']], [pattern:'/ shutdown',access:['permitAll']], [pattern:'/ assets / **',access:['permitAll ]], [pattern:'/ ** / js / **',access:['permitAll']], [pattern:'/ ** / css / **',access: ['permitAll']], [pattern:'/ ** / images / **',access:['permitAll']], [pattern:'/**/favicon.ico' ,access:['permitAll']], [pattern:'/ login / ajaxSuccess',access:['permitAll']], [pattern:'/ login / ajaxSuccess / **', access:['permitAll']], [pattern:'/ ** / ajaxSuccess / **',access:['permitAll']] ] 我在底部添加了3条新规则,第一条应该解决问题。但我只是把它们加了进去。然后在它上面的行你已经从注释改变到 Requestmap ,但是你有 controllerAnnotations.staticRules 你需要支付注意这里的细节。 如果你设置了某些东西,那么你需要相关的配置。 请注意,如果您希望坚持使用Requestmap,那么您可能需要配置 pre $ grafclugin.springsecurity。 interceptUrlMap = [ [pattern:'/',access:['permitAll']], [pattern:'/ something / **',access:['ROLE_ADMIN','ROLE_USER']] , [pattern:'/ **',access:['permitAll']],] 现在我会坚持使用 securityConfigType:Annotation i am trying to create an android application to do something with my database.for example: i run my grails app on port 8080, localhost:8080 then i use POSTMAN and pass paramter like this..it success with like this..but why i fail to login with my android application .like this..public static String performPostCall(String requestURL, HashMap<String, String> postDataParams) { Log.d("url = ",requestURL); URL url; String response = ""; try { url = new URL(requestURL); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(45000); conn.setConnectTimeout(45000); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "form-data"); conn.setDoInput(true); conn.setDoOutput(true); OutputStream os = conn.getOutputStream(); BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(os, "UTF-8")); writer.write(getPostDataString(postDataParams)); writer.flush(); writer.close(); os.close(); int responseCode=conn.getResponseCode(); System.out.println(".toString() = "+responseCode); System.out.println(".HttpsURLConnection.HTTP_OK = "+HttpsURLConnection.HTTP_OK); if (responseCode == HttpsURLConnection.HTTP_OK) { String line; BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream())); while ((line=br.readLine()) != null) { response+=line; } } else { response=""; } } catch (Exception e) { e.printStackTrace(); } return response; } private static String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException{ StringBuilder result = new StringBuilder(); boolean first = true; for(Map.Entry<String, String> entry : params.entrySet()){ Log.d("entry.getKey() = ",entry.getKey()); Log.d("entry.getValue() = ",entry.getValue()); if (first) first = false; else result.append("&"); result.append(URLEncoder.encode(entry.getKey(), "UTF-8")); result.append("="); result.append(URLEncoder.encode(entry.getValue(), "UTF-8")); } System.out.println("tetstes = "+result.toString()); return result.toString(); }then protected Void doInBackground(Void... params) { // TODO Auto-generated method stub HashMap<String, String> parameter = new HashMap<String, String>(); parameter.put("username", username); parameter.put("password", password); try { response = MyHttpURLConnection.performPostCall(URL, parameter); } catch (Exception e) { System.out.println("assdfdsf = "+e); // TODO Auto-generated catch block e.printStackTrace(); } return null; }it always fail in def ajaxSuccess because i cannot get SpringSecurityServyce.principal.idi tried to get springSecurityService.getCurrentUser() like this..def ajaxSuccess() {// println "adf = "+springSecurityService.authentication.username println "cookies = "+session.id def cifus = springSecurityService.getCurrentUser() println "cifus = "+cifus// println "adf = "+springSecurityService.principal.id def user = com.vastpalaso.security.User.findByUsername(springSecurityService.authentication.name) def userDetails = com.vastpalaso.security.UserDetails.findByUser(user) def cifUser = corporateUserService.getCurrentCifUser() println "user = "+user// println "cif user = "+cifUser// println "cif user = "+cifUser.cif.corpName// if(cifUser){// session.setAttribute("company",cifUser.cif.corpName)// if(new Date() >cifUser.cif.expireDate ){// redirect(controller: "error", action: "serverError")// }// }//// if (userDetails.isLogin.equals("1")) {// def sessionx = HttpSessionCollector.find(userDetails.sessionId)// if (sessionx) {// sessionx.invalidate()// HttpSessionCollector.remove(userDetails.sessionId)// }// } try { def ipAddress = request.getHeader("Client-IP") if (!ipAddress) { ipAddress = request.getHeader("X-Forwarded-For") } if (!ipAddress) { ipAddress = request.getRemoteAddr() } try{ cifService.resetTryLoginAddInfo(userDetails, ipAddress, session.id) }catch (Exception e){ println "e = "+e } session.setAttribute("alias", userDetails.userAlias) session.setAttribute("fullName", userDetails.firstName + " " + userDetails.lastName) session.setAttribute("change", userDetails.forceChangePassword) session.setAttribute("userType", userDetails.userType) if(userDetails.language != null){ session[org.springframework.web.servlet.i18n.SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME] = new Locale(userDetails.language) } else{ session[org.springframework.web.servlet.i18n.SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME] = new Locale("id") } buildMenuList() if (params.callback) { render"${params.callback} (${[success: true,id: userDetails.id ,change: userDetails.forceChangePassword, username: springSecurityService.authentication.name, fullName: (userDetails.firstName + " " + userDetails.lastName)] as JSON})" } else { render([success: true,id: userDetails.id, change: userDetails.forceChangePassword, username: springSecurityService.authentication.name, fullName: (userDetails.firstName + " " + userDetails.lastName)] as JSON) } } //catch unknown RuntimeException, redirect to Error 500 server Error page catch (RuntimeException e) { logger.error(e.getMessage(), e) redirect(controller: "error", action: "serverError") return } render([success: true, username: authentication.name] as JSON) }but i always get this error log.DEBUG org.springframework.security.web.FilterChainProxy - /login/ajaxSuccess reached end of additional filter chain; proceeding with original chaincookies = F866B5D4267DD54163C93FD3DB1EADB5cifus = nullERROR org.grails.web.errors.GrailsExceptionResolver - MissingPropertyException occurred when processing request: [GET] /login/ajaxSuccessNo such property: id for class: org.springframework.security.core.userdetails.User. Stacktrace follows:groovy.lang.MissingPropertyException: No such property: id for class: org.springframework.security.core.userdetails.User at com.vastpalaso.CorporateUserService.getCurrentCifUser(CorporateUserService.groovy:950) ~[main/:na] at accounter.LoginController$$EQ0tGOPB.ajaxSuccess(LoginController.groovy:168) ~[na:na] at grails.plugin.springsecurity.web.UpdateRequestContextHolderExceptionTranslationFilter.doFilter(UpdateRequestContextHolderExceptionTranslationFilter.groovy:64) ~[spring-security-core-3.1.1.jar:na] at grails.plugin.springsecurity.web.filter.GrailsAnonymousAuthenticationFilter.doFilter(GrailsAnonymousAuthenticationFilter.groovy:53) ~[spring-security-core-3.1.1.jar:na] at grails.plugin.springsecurity.web.authentication.logout.MutableLogoutFilter.doFilter(MutableLogoutFilter.groovy:62) ~[spring-security-core-3.1.1.jar:na] at grails.plugin.springsecurity.web.SecurityRequestHolderFilter.doFilter(SecurityRequestHolderFilter.groovy:58) ~[spring-security-core-3.1.1.jar:na] at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) ~[na:1.8.0_111] at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) ~[na:1.8.0_111] at java.lang.Thread.run(Thread.java:745) [na:1.8.0_111]DEBUG org.springframework.security.web.context.HttpSessionSecurityContextRepository - SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.DEBUG org.springframework.security.web.context.HttpSessionSecurityContextRepository - SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.DEBUG org.springframework.security.web.context.SecurityContextPersistenceFilter - SecurityContextHolder now cleared, as request processing completedDEBUG org.springframework.security.web.context.SecurityContextPersistenceFilter - SecurityContextHolder now cleared, as request processing completedthis is the logDEBUG org.springframework.security.web.FilterChainProxy - /login/authenticate?spring-security-redirect=/login/ajaxSuccess at position 1 of 9 in additional filter chain; firing Filter: 'SecurityRequestHolderFilter'DEBUG org.springframework.security.web.FilterChainProxy - /login/authenticate?spring-security-redirect=/login/ajaxSuccess at position 1 of 9 in additional filter chain; firing Filter: 'SecurityRequestHolderFilter'DEBUG org.springframework.security.web.FilterChainProxy - /login/authenticate?spring-security-redirect=/login/ajaxSuccess at position 2 of 9 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'DEBUG org.springframework.security.web.FilterChainProxy - /login/authenticate?spring-security-redirect=/login/ajaxSuccess at position 2 of 9 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'DEBUG org.springframework.security.web.context.HttpSessionSecurityContextRepository - No HttpSession currently existsDEBUG org.springframework.security.web.context.HttpSessionSecurityContextRepository - No HttpSession currently existsDEBUG org.springframework.security.web.context.HttpSessionSecurityContextRepository - No SecurityContext was available from the HttpSession: null. A new one will be created.DEBUG org.springframework.security.web.context.HttpSessionSecurityContextRepository - No SecurityContext was available from the HttpSession: null. A new one will be created.DEBUG org.springframework.security.web.FilterChainProxy - /login/authenticate?spring-security-redirect=/login/ajaxSuccess at position 3 of 9 in additional filter chain; firing Filter: 'MutableLogoutFilter'DEBUG org.springframework.security.web.FilterChainProxy - /login/authenticate?spring-security-redirect=/login/ajaxSuccess at position 3 of 9 in additional filter chain; firing Filter: 'MutableLogoutFilter'DEBUG org.springframework.security.web.util.matcher.AntPathRequestMatcher - Checking match of request : '/login/authenticate'; against '/logoff'DEBUG org.springframework.security.web.util.matcher.AntPathRequestMatcher - Checking match of request : '/login/authenticate'; against '/logoff'DEBUG org.springframework.security.web.FilterChainProxy - /login/authenticate?spring-security-redirect=/login/ajaxSuccess at position 4 of 9 in additional filter chain; firing Filter: 'GrailsUsernamePasswordAuthenticationFilter'DEBUG org.springframework.security.web.FilterChainProxy - /login/authenticate?spring-security-redirect=/login/ajaxSuccess at position 4 of 9 in additional filter chain; firing Filter: 'GrailsUsernamePasswordAuthenticationFilter'DEBUG org.springframework.security.authentication.ProviderManager - Authentication attempt using org.springframework.security.authentication.dao.DaoAuthenticationProviderDEBUG org.springframework.security.authentication.ProviderManager - Authentication attempt using org.springframework.security.authentication.dao.DaoAuthenticationProviderDEBUG org.springframework.security.authentication.dao.DaoAuthenticationProvider - User '' not foundDEBUG org.springframework.security.authentication.dao.DaoAuthenticationProvider - User '' not foundDEBUG org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices - Interactive login attempt was unsuccessful.DEBUG org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices - Interactive login attempt was unsuccessful.DEBUG org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices - Cancelling cookieDEBUG org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices - Cancelling cookieDEBUG org.springframework.security.web.context.HttpSessionSecurityContextRepository - SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.DEBUG org.springframework.security.web.context.HttpSessionSecurityContextRepository - SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.DEBUG org.springframework.security.web.context.SecurityContextPersistenceFilter - SecurityContextHolder now cleared, as request processing completedDEBUG org.springframework.security.web.context.SecurityContextPersistenceFilter - SecurityContextHolder now cleared, as request processing completedDEBUG org.springframework.security.web.util.matcher.AntPathRequestMatcher - Checking match of request : '/login/authfail'; against '/assets/**'DEBUG org.springframework.security.web.util.matcher.AntPathRequestMatcher - Checking match of request : '/login/authfail'; against '/assets/**'DEBUG org.springframework.security.web.util.matcher.AntPathRequestMatcher - Checking match of request : '/login/authfail'; against '/**/js/**'DEBUG org.springframework.security.web.util.matcher.AntPathRequestMatcher - Checking match of request : '/login/authfail'; against '/**/js/**'DEBUG org.springframework.security.web.util.matcher.AntPathRequestMatcher - Checking match of request : '/login/authfail'; against '/**/css/**'DEBUG org.springframework.security.web.util.matcher.AntPathRequestMatcher - Checking match of request : '/login/authfail'; against '/**/css/**'DEBUG org.springframework.security.web.util.matcher.AntPathRequestMatcher - Checking match of request : '/login/authfail'; against '/**/images/**'DEBUG org.springframework.security.web.util.matcher.AntPathRequestMatcher - Checking match of request : '/login/authfail'; against '/**/images/**'DEBUG org.springframework.security.web.util.matcher.AntPathRequestMatcher - Checking match of request : '/login/authfail'; against '/**/favicon.ico'DEBUG org.springframework.security.web.util.matcher.AntPathRequestMatcher - Checking match of request : '/login/authfail'; against '/**/favicon.ico'DEBUG org.springframework.security.web.util.matcher.AntPathRequestMatcher - Request '/login/authfail' matched by universal pattern '/**'DEBUG org.springframework.security.web.util.matcher.AntPathRequestMatcher - Request '/login/authfail' matched by universal pattern '/**'DEBUG org.springframework.security.web.FilterChainProxy - /login/authfail?login_error=1 at position 1 of 9 in additional filter chain; firing Filter: 'SecurityRequestHolderFilter'DEBUG org.springframework.security.web.FilterChainProxy - /login/authfail?login_error=1 at position 1 of 9 in additional filter chain; firing Filter: 'SecurityRequestHolderFilter'DEBUG org.springframework.security.web.FilterChainProxy - /login/authfail?login_error=1 at position 2 of 9 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'DEBUG org.springframework.security.web.FilterChainProxy - /login/authfail?login_error=1 at position 2 of 9 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'DEBUG org.springframework.security.web.context.HttpSessionSecurityContextRepository - No HttpSession currently existsDEBUG org.springframework.security.web.context.HttpSessionSecurityContextRepository - No HttpSession currently existsDEBUG org.springframework.security.web.context.HttpSessionSecurityContextRepository - No SecurityContext was available from the HttpSession: null. A new one will be created.DEBUG org.springframework.security.web.context.HttpSessionSecurityContextRepository - No SecurityContext was available from the HttpSession: null. A new one will be created.DEBUG org.springframework.security.web.FilterChainProxy - /login/authfail?login_error=1 at position 3 of 9 in additional filter chain; firing Filter: 'MutableLogoutFilter'DEBUG org.springframework.security.web.FilterChainProxy - /login/authfail?login_error=1 at position 3 of 9 in additional filter chain; firing Filter: 'MutableLogoutFilter'DEBUG org.springframework.security.web.util.matcher.AntPathRequestMatcher - Checking match of request : '/login/authfail'; against '/logoff'DEBUG org.springframework.security.web.util.matcher.AntPathRequestMatcher - Checking match of request : '/login/authfail'; against '/logoff'DEBUG org.springframework.security.web.FilterChainProxy - /login/authfail?login_error=1 at position 4 of 9 in additional filter chain; firing Filter: 'GrailsUsernamePasswordAuthenticationFilter'DEBUG org.springframework.security.web.FilterChainProxy - /login/authfail?login_error=1 at position 4 of 9 in additional filter chain; firing Filter: 'GrailsUsernamePasswordAuthenticationFilter'DEBUG org.springframework.security.web.FilterChainProxy - /login/authfail?login_error=1 at position 5 of 9 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'DEBUG org.springframework.security.web.FilterChainProxy - /login/authfail?login_error=1 at position 5 of 9 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'DEBUG org.springframework.security.web.FilterChainProxy - /login/authfail?login_error=1 at position 6 of 9 in additional filter chain; firing Filter: 'GrailsRememberMeAuthenticationFilter'DEBUG org.springframework.security.web.FilterChainProxy - /login/authfail?login_error=1 at position 6 of 9 in additional filter chain; firing Filter: 'GrailsRememberMeAuthenticationFilter'DEBUG org.springframework.security.web.FilterChainProxy - /login/authfail?login_error=1 at position 7 of 9 in additional filter chain; firing Filter: 'GrailsAnonymousAuthenticationFilter'DEBUG org.springframework.security.web.FilterChainProxy - /login/authfail?login_error=1 at position 7 of 9 in additional filter chain; firing Filter: 'GrailsAnonymousAuthenticationFilter'INFO org.springframework.security.core.SpringSecurityCoreVersion - You are running with Spring Security Core 4.0.3.RELEASEINFO org.springframework.security.core.SpringSecurityCoreVersion - You are running with Spring Security Core 4.0.3.RELEASEDEBUG org.springframework.security.web.FilterChainProxy - /login/authfail?login_error=1 at position 8 of 9 in additional filter chain; firing Filter: 'UpdateRequestContextHolderExceptionTranslationFilter'DEBUG org.springframework.security.web.FilterChainProxy - /login/authfail?login_error=1 at position 8 of 9 in additional filter chain; firing Filter: 'UpdateRequestContextHolderExceptionTranslationFilter'DEBUG org.springframework.security.web.FilterChainProxy - /login/authfail?login_error=1 at position 9 of 9 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'DEBUG org.springframework.security.web.FilterChainProxy - /login/authfail?login_error=1 at position 9 of 9 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'DEBUG org.springframework.security.web.access.intercept.FilterSecurityInterceptor - Secure object: FilterInvocation: URL: /login/authfail?login_error=1; Attributes: [IS_AUTHENTICATED_ANONYMOUSLY]DEBUG org.springframework.security.web.access.intercept.FilterSecurityInterceptor - Secure object: FilterInvocation: URL: /login/authfail?login_error=1; Attributes: [IS_AUTHENTICATED_ANONYMOUSLY]DEBUG org.springframework.security.web.access.intercept.FilterSecurityInterceptor - Previously Authenticated: grails.plugin.springsecurity.authentication.GrailsAnonymousAuthenticationToken@f23b441a: Principal: org.springframework.security.core.userdetails.User@dc730200: Username: __grails.anonymous.user__; Password: [PROTECTED]; Enabled: false; AccountNonExpired: false; credentialsNonExpired: false; AccountNonLocked: false; Granted Authorities: ROLE_ANONYMOUS; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@ffffe21a: RemoteIpAddress: 192.168.100.9; SessionId: null; Granted Authorities: ROLE_ANONYMOUSDEBUG org.springframework.security.web.access.intercept.FilterSecurityInterceptor - Previously Authenticated: grails.plugin.springsecurity.authentication.GrailsAnonymousAuthenticationToken@f23b441a: Principal: org.springframework.security.core.userdetails.User@dc730200: Username: __grails.anonymous.user__; Password: [PROTECTED]; Enabled: false; AccountNonExpired: false; credentialsNonExpired: false; AccountNonLocked: false; Granted Authorities: ROLE_ANONYMOUS; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@ffffe21a: RemoteIpAddress: 192.168.100.9; SessionId: null; Granted Authorities: ROLE_ANONYMOUSDEBUG org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl - getReachableGrantedAuthorities() - From the roles [ROLE_ANONYMOUS] one can reach [ROLE_ANONYMOUS] in zero or more steps.DEBUG org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl - getReachableGrantedAuthorities() - From the roles [ROLE_ANONYMOUS] one can reach [ROLE_ANONYMOUS] in zero or more steps.DEBUG org.springframework.security.web.access.intercept.FilterSecurityInterceptor - Authorization successfulDEBUG org.springframework.security.web.access.intercept.FilterSecurityInterceptor - Authorization successfulDEBUG org.springframework.security.web.access.intercept.FilterSecurityInterceptor - RunAsManager did not change Authentication objectDEBUG org.springframework.security.web.access.intercept.FilterSecurityInterceptor - RunAsManager did not change Authentication objectDEBUG org.springframework.security.web.FilterChainProxy - /login/authfail?login_error=1 reached end of additional filter chain; proceeding with original chainDEBUG org.springframework.security.web.FilterChainProxy - /login/authfail?login_error=1 reached end of additional filter chain; proceeding with original chainDEBUG org.springframework.security.web.context.HttpSessionSecurityContextRepository - SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.DEBUG org.springframework.security.web.context.HttpSessionSecurityContextRepository - SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.DEBUG org.springframework.security.web.context.HttpSessionSecurityContextRepository$SaveToSessionResponseWrapper - Skip invoking onDEBUG org.springframework.security.web.context.HttpSessionSecurityContextRepository$SaveToSessionResponseWrapper - Skip invoking onERROR org.grails.web.errors.GrailsExceptionResolver - CannotRedirectException occurred when processing request: [GET] /login/authfail - parameters:login_error: 1Cannot issue a redirect(..) here. The response has already been committed either by another redirect or by directly writing to the response.. Stacktrace follows:grails.web.mapping.mvc.exceptions.CannotRedirectException: Cannot issue a redirect(..) here. The response has already been committed either by another redirect or by directly writing to the response.application.groovygrails.plugin.springsecurity.userLookup.userDomainClassName = 'com.vastpalaso.security.User'grails.plugin.springsecurity.userLookup.authorityJoinClassName = 'com.vastpalaso.security.UserRole'grails.plugin.springsecurity.authority.className = 'com.vastpalaso.security.Role'grails.plugin.springsecurity.requestMap.className = 'com.vastpalaso.security.RequestMap'grails.plugin.springsecurity.securityConfigType = 'Requestmap'grails.plugin.springsecurity.controllerAnnotations.staticRules = [ [pattern: '/', access: ['permitAll']], [pattern: '/error', access: ['permitAll']], [pattern: '/index', access: ['permitAll']], [pattern: '/index2.gsp', access: ['permitAll']], [pattern: '/shutdown', access: ['permitAll']], [pattern: '/assets/**', access: ['permitAll']], [pattern: '/**/js/**', access: ['permitAll']], [pattern: '/**/css/**', access: ['permitAll']], [pattern: '/**/images/**', access: ['permitAll']], [pattern: '/**/favicon.ico', access: ['permitAll']]]grails.plugin.springsecurity.filterChain.chainMap = [ [pattern: '/assets/**', filters: 'none'], [pattern: '/**/js/**', filters: 'none'], [pattern: '/**/css/**', filters: 'none'], [pattern: '/**/images/**', filters: 'none'], [pattern: '/**/favicon.ico', filters: 'none'], [pattern: '/**', filters: 'JOINED_FILTERS']]after i add this below code, my error log become like this 解决方案 The issue is here: org.springframework.security.authentication.dao.DaoAuthenticationProvider User '' not found On the provided link slide 6 it says firing organizationFilter When you look into security filters. They are actually those static rules that I mentioned earlier.so something is of a conflict there and the rule is being bypassed then it attempts to login (with no user credentials).It is all there in there logs just a matter of interpreting it correctly Right.. Comment out this first//grails.plugin.springsecurity.securityConfigType = 'Requestmap'//Then addgrails.plugin.springsecurity.controllerAnnotations.staticRules = [ [pattern: '/', access: ['permitAll']], [pattern: '/error', access: ['permitAll']], [pattern: '/index', access: ['permitAll']], [pattern: '/index2.gsp', access: ['permitAll']], [pattern: '/shutdown', access: ['permitAll']], [pattern: '/assets/**', access: ['permitAll']], [pattern: '/**/js/**', access: ['permitAll']], [pattern: '/**/css/**', access: ['permitAll']], [pattern: '/**/images/**', access: ['permitAll']], [pattern: '/**/favicon.ico', access: ['permitAll']], [pattern: '/login/ajaxSuccess', access: ['permitAll']], [pattern: '/login/ajaxSuccess/**', access: ['permitAll']], [pattern: '/**/ajaxSuccess/**', access: ['permitAll']]]I haved added 3 new rules at the very bottom, the very first one should fix the issue. But I added them just incase. Then the line above it you have changed from annotation to Requestmap but then you have controllerAnnotations.staticRules you do need to pay attention to the finer details here.If you set something to be something else then you need relevant configuration for that.Please note if you do wish to stick with Requestmap then maybe you need to configure grails.plugin.springsecurity.interceptUrlMap = [ [pattern: '/', access: ['permitAll']], [pattern: '/something/**', access: ['ROLE_ADMIN', 'ROLE_USER']], [pattern: '/**', access: ['permitAll']],]For now I would stick with securityConfigType: Annotation 这篇关于从android http post登录到grails 3 spring security的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 10-11 02:23