明点软件 avatar 明点软件 committed 5ae3f91

增加alibaba开放平台支持

Comments (0)

Files changed (36)

 target-eclipse/classes/BootStrap$_closure1.class
 target-eclipse/*
 *.iml
+.idea/*
+out/*
 syntax: regexp
 ^Grails-spring-security-taobao-grailsPlugins\.iml$
 syntax: regexp

Grails-spring-security-taobao-grailsPlugins.iml

-<?xml version="1.0" encoding="UTF-8"?>
-<module type="JAVA_MODULE" version="4">
-  <component name="FacetManager">
-    <facet type="hibernate" name="Hibernate">
-      <configuration>
-        <datasource-map />
-      </configuration>
-    </facet>
-  </component>
-  <component name="NewModuleRootManager" inherit-compiler-output="true">
-    <exclude-output />
-    <content url="file://$USER_HOME$/.grails/2.1.0/projects/spring-security-taobao/plugins/hibernate-2.1.0">
-      <sourceFolder url="file://$USER_HOME$/.grails/2.1.0/projects/spring-security-taobao/plugins/hibernate-2.1.0/grails-app/i18n" isTestSource="false" />
-    </content>
-    <content url="file://$USER_HOME$/.grails/2.1.0/projects/spring-security-taobao/plugins/release-2.0.4">
-      <sourceFolder url="file://$USER_HOME$/.grails/2.1.0/projects/spring-security-taobao/plugins/release-2.0.4/src/java" isTestSource="false" />
-      <sourceFolder url="file://$USER_HOME$/.grails/2.1.0/projects/spring-security-taobao/plugins/release-2.0.4/src/groovy" isTestSource="false" />
-    </content>
-    <content url="file://$USER_HOME$/.grails/2.1.0/projects/spring-security-taobao/plugins/rest-client-builder-1.0.2">
-      <sourceFolder url="file://$USER_HOME$/.grails/2.1.0/projects/spring-security-taobao/plugins/rest-client-builder-1.0.2/src/groovy" isTestSource="false" />
-    </content>
-    <content url="file://$USER_HOME$/.grails/2.1.0/projects/spring-security-taobao/plugins/spring-security-core-1.2.7.3">
-      <sourceFolder url="file://$USER_HOME$/.grails/2.1.0/projects/spring-security-taobao/plugins/spring-security-core-1.2.7.3/src/java" isTestSource="false" />
-      <sourceFolder url="file://$USER_HOME$/.grails/2.1.0/projects/spring-security-taobao/plugins/spring-security-core-1.2.7.3/src/groovy" isTestSource="false" />
-      <sourceFolder url="file://$USER_HOME$/.grails/2.1.0/projects/spring-security-taobao/plugins/spring-security-core-1.2.7.3/grails-app/i18n" isTestSource="false" />
-      <sourceFolder url="file://$USER_HOME$/.grails/2.1.0/projects/spring-security-taobao/plugins/spring-security-core-1.2.7.3/grails-app/services" isTestSource="false" />
-      <sourceFolder url="file://$USER_HOME$/.grails/2.1.0/projects/spring-security-taobao/plugins/spring-security-core-1.2.7.3/grails-app/taglib" isTestSource="false" />
-    </content>
-    <content url="file://$USER_HOME$/.grails/2.1.0/projects/spring-security-taobao/plugins/tomcat-2.1.0" />
-    <content url="file://$USER_HOME$/.grails/2.1.0/projects/spring-security-taobao/plugins/webxml-1.4.1">
-      <sourceFolder url="file://$USER_HOME$/.grails/2.1.0/projects/spring-security-taobao/plugins/webxml-1.4.1/src/groovy" isTestSource="false" />
-    </content>
-    <orderEntry type="inheritedJdk" />
-    <orderEntry type="sourceFolder" forTests="false" />
-    <orderEntry type="library" scope="PROVIDED" name="grails-2.1.0" level="application" />
-    <orderEntry type="module-library" exported="">
-      <library name="Grails User Library (Grails-spring-security-taobao-grailsPlugins)">
-        <CLASSES>
-          <root url="jar://$USER_HOME$/.grails/ivy-cache/org.springframework.security/spring-security-web/jars/spring-security-web-3.0.7.RELEASE.jar!/" />
-          <root url="jar://$USER_HOME$/.grails/ivy-cache/org.springframework.security/spring-security-core/jars/spring-security-core-3.0.7.RELEASE.jar!/" />
-          <root url="jar://$USER_HOME$/.grails/ivy-cache/nekohtml/nekohtml/jars/nekohtml-1.9.6.2.jar!/" />
-          <root url="jar://$USER_HOME$/.grails/ivy-cache/nekohtml/xercesMinimal/jars/xercesMinimal-1.9.6.2.jar!/" />
-          <root url="jar://$USER_HOME$/.grails/ivy-cache/org.apache.maven.wagon/wagon-http-shared/jars/wagon-http-shared-1.0-beta-6.jar!/" />
-          <root url="jar://$USER_HOME$/.grails/ivy-cache/org.apache.maven.wagon/wagon-http-lightweight/jars/wagon-http-lightweight-1.0-beta-6.jar!/" />
-          <root url="jar://$USER_HOME$/.grails/ivy-cache/org.apache.maven.wagon/wagon-file/jars/wagon-file-1.0-beta-6.jar!/" />
-          <root url="jar://$USER_HOME$/.grails/ivy-cache/org.apache.maven/maven-error-diagnostics/jars/maven-error-diagnostics-2.2.1.jar!/" />
-          <root url="jar://$USER_HOME$/.grails/ivy-cache/org.apache.maven/maven-plugin-registry/jars/maven-plugin-registry-2.2.1.jar!/" />
-          <root url="jar://$USER_HOME$/.grails/ivy-cache/org.apache.maven/maven-profile/jars/maven-profile-2.2.1.jar!/" />
-          <root url="jar://$USER_HOME$/.grails/ivy-cache/org.apache.maven/maven-settings/jars/maven-settings-2.2.1.jar!/" />
-          <root url="jar://$USER_HOME$/.grails/ivy-cache/org.apache.maven/maven-project/jars/maven-project-2.2.1.jar!/" />
-          <root url="jar://$USER_HOME$/.grails/ivy-cache/org.apache.maven/maven-model/jars/maven-model-2.2.1.jar!/" />
-          <root url="jar://$USER_HOME$/.grails/ivy-cache/backport-util-concurrent/backport-util-concurrent/jars/backport-util-concurrent-3.1.jar!/" />
-          <root url="jar://$USER_HOME$/.grails/ivy-cache/org.apache.maven.wagon/wagon-provider-api/jars/wagon-provider-api-1.0-beta-6.jar!/" />
-          <root url="jar://$USER_HOME$/.grails/ivy-cache/org.apache.maven/maven-repository-metadata/jars/maven-repository-metadata-2.2.1.jar!/" />
-          <root url="jar://$USER_HOME$/.grails/ivy-cache/org.apache.maven/maven-artifact-manager/jars/maven-artifact-manager-2.2.1.jar!/" />
-          <root url="jar://$USER_HOME$/.grails/ivy-cache/org.apache.maven/maven-artifact/jars/maven-artifact-2.2.1.jar!/" />
-          <root url="jar://$USER_HOME$/.grails/ivy-cache/org.codehaus.plexus/plexus-interpolation/jars/plexus-interpolation-1.11.jar!/" />
-          <root url="jar://$USER_HOME$/.grails/ivy-cache/org.codehaus.plexus/plexus-utils/jars/plexus-utils-1.5.15.jar!/" />
-          <root url="jar://$USER_HOME$/.grails/ivy-cache/org.codehaus.plexus/plexus-container-default/jars/plexus-container-default-1.0-alpha-9-stable-1.jar!/" />
-          <root url="jar://$USER_HOME$/.grails/ivy-cache/classworlds/classworlds/jars/classworlds-1.1-alpha-2.jar!/" />
-          <root url="jar://$USER_HOME$/.grails/ivy-cache/ant/ant/jars/ant-1.6.5.jar!/" />
-          <root url="jar://$USER_HOME$/.grails/ivy-cache/org.apache.maven/maven-ant-tasks/jars/maven-ant-tasks-2.1.0.jar!/" />
-          <root url="jar://$USER_HOME$/.grails/ivy-cache/xml-resolver/xml-resolver/jars/xml-resolver-1.2.jar!/" />
-          <root url="jar://$USER_HOME$/.grails/ivy-cache/xerces/xercesImpl/jars/xercesImpl-2.8.1.jar!/" />
-          <root url="jar://$USER_HOME$/.grails/ivy-cache/net.sourceforge.nekohtml/nekohtml/jars/nekohtml-1.9.9.jar!/" />
-          <root url="jar://$USER_HOME$/.grails/ivy-cache/asm/asm-analysis/jars/asm-analysis-3.2.jar!/" />
-          <root url="jar://$USER_HOME$/.grails/ivy-cache/asm/asm-util/jars/asm-util-3.2.jar!/" />
-          <root url="jar://$USER_HOME$/.grails/ivy-cache/asm/asm-tree/jars/asm-tree-3.2.jar!/" />
-          <root url="jar://$USER_HOME$/.grails/ivy-cache/asm/asm-commons/jars/asm-commons-3.2.jar!/" />
-          <root url="jar://$USER_HOME$/.grails/ivy-cache/asm/asm/jars/asm-3.2.jar!/" />
-          <root url="jar://$USER_HOME$/.grails/ivy-cache/org.codehaus.groovy/groovy/jars/groovy-1.7-rc-2.jar!/" />
-          <root url="jar://$USER_HOME$/.grails/ivy-cache/net.sf.ezmorph/ezmorph/jars/ezmorph-1.0.6.jar!/" />
-          <root url="jar://$USER_HOME$/.grails/ivy-cache/net.sf.json-lib/json-lib/jars/json-lib-2.3-jdk15.jar!/" />
-          <root url="jar://$USER_HOME$/.grails/ivy-cache/commons-logging/commons-logging/jars/commons-logging-1.1.1.jar!/" />
-          <root url="jar://$USER_HOME$/.grails/ivy-cache/org.apache.httpcomponents/httpcore/jars/httpcore-4.0.1.jar!/" />
-          <root url="jar://$USER_HOME$/.grails/ivy-cache/org.apache.httpcomponents/httpclient/jars/httpclient-4.0.jar!/" />
-          <root url="jar://$USER_HOME$/.grails/ivy-cache/org.codehaus.groovy.modules.http-builder/http-builder/jars/http-builder-0.5.0.jar!/" />
-        </CLASSES>
-        <JAVADOC />
-        <SOURCES />
-      </library>
-    </orderEntry>
-  </component>
-</module>
-

Grails-spring-security-taobao.iml

   <component name="FacetManager">
     <facet type="Spring" name="Spring">
       <configuration>
-        <fileset id="fileset1" name="Xml Application Context" removed="false">
+        <fileset id="Grails" name="Grails" removed="false">
           <file>file://$MODULE_DIR$/web-app/WEB-INF/applicationContext.xml</file>
         </fileset>
       </configuration>
     </facet>
     <facet type="hibernate" name="Hibernate">
       <configuration>
-        <datasource-map>
-          <unit-entry name="Gorm" />
-          <unit-entry name="sessionFactory" />
-        </datasource-map>
+        <datasource-map />
       </configuration>
     </facet>
   </component>
       <sourceFolder url="file://$MODULE_DIR$/src/java" isTestSource="false" />
       <sourceFolder url="file://$MODULE_DIR$/grails-app/utils" isTestSource="false" />
       <sourceFolder url="file://$MODULE_DIR$/src/groovy" isTestSource="false" />
+      <sourceFolder url="file://$MODULE_DIR$/grails-app/i18n" isTestSource="false" />
       <sourceFolder url="file://$MODULE_DIR$/grails-app/controllers" isTestSource="false" />
       <sourceFolder url="file://$MODULE_DIR$/grails-app/domain" isTestSource="false" />
       <sourceFolder url="file://$MODULE_DIR$/grails-app/services" isTestSource="false" />
       <sourceFolder url="file://$MODULE_DIR$/grails-app/taglib" isTestSource="false" />
       <sourceFolder url="file://$MODULE_DIR$/test/unit" isTestSource="true" />
       <sourceFolder url="file://$MODULE_DIR$/test/integration" isTestSource="true" />
-      <sourceFolder url="file://$MODULE_DIR$/grails-app/i18n" isTestSource="false" />
       <excludeFolder url="file://$MODULE_DIR$/target/classes" />
     </content>
     <orderEntry type="inheritedJdk" />
     <orderEntry type="sourceFolder" forTests="false" />
+    <orderEntry type="library" name="grails-2.1.1 (2)" level="application" />
     <orderEntry type="module-library" exported="">
-      <library name="Grails User Library (Grails-spring-security-taobao)">
+      <library name="Grails User Library (grails-spring-security-taobao)">
         <CLASSES>
           <root url="file://$MODULE_DIR$/lib" />
-          <root url="jar://$USER_HOME$/.grails/ivy-cache/org.springframework.security/spring-security-web/jars/spring-security-web-3.0.7.RELEASE.jar!/" />
-          <root url="jar://$USER_HOME$/.grails/ivy-cache/org.springframework.security/spring-security-core/jars/spring-security-core-3.0.7.RELEASE.jar!/" />
           <root url="jar://$USER_HOME$/.grails/ivy-cache/nekohtml/nekohtml/jars/nekohtml-1.9.6.2.jar!/" />
           <root url="jar://$USER_HOME$/.grails/ivy-cache/nekohtml/xercesMinimal/jars/xercesMinimal-1.9.6.2.jar!/" />
           <root url="jar://$USER_HOME$/.grails/ivy-cache/org.apache.maven.wagon/wagon-http-shared/jars/wagon-http-shared-1.0-beta-6.jar!/" />
           <root url="jar://$USER_HOME$/.grails/ivy-cache/classworlds/classworlds/jars/classworlds-1.1-alpha-2.jar!/" />
           <root url="jar://$USER_HOME$/.grails/ivy-cache/ant/ant/jars/ant-1.6.5.jar!/" />
           <root url="jar://$USER_HOME$/.grails/ivy-cache/org.apache.maven/maven-ant-tasks/jars/maven-ant-tasks-2.1.0.jar!/" />
+          <root url="jar://$USER_HOME$/.grails/ivy-cache/org.springframework.security/spring-security-web/jars/spring-security-web-3.0.7.RELEASE.jar!/" />
+          <root url="jar://$USER_HOME$/.grails/ivy-cache/org.springframework.security/spring-security-core/jars/spring-security-core-3.0.7.RELEASE.jar!/" />
           <root url="jar://$USER_HOME$/.grails/ivy-cache/xml-resolver/xml-resolver/jars/xml-resolver-1.2.jar!/" />
           <root url="jar://$USER_HOME$/.grails/ivy-cache/xerces/xercesImpl/jars/xercesImpl-2.8.1.jar!/" />
           <root url="jar://$USER_HOME$/.grails/ivy-cache/net.sourceforge.nekohtml/nekohtml/jars/nekohtml-1.9.9.jar!/" />
           <root url="jar://$USER_HOME$/.grails/ivy-cache/org.apache.httpcomponents/httpcore/jars/httpcore-4.0.1.jar!/" />
           <root url="jar://$USER_HOME$/.grails/ivy-cache/org.apache.httpcomponents/httpclient/jars/httpclient-4.0.jar!/" />
           <root url="jar://$USER_HOME$/.grails/ivy-cache/org.codehaus.groovy.modules.http-builder/http-builder/jars/http-builder-0.5.0.jar!/" />
+          <root url="jar://$USER_HOME$/.grails/ivy-cache/com.google.code.gson/gson/jars/gson-2.2.2.jar!/" />
         </CLASSES>
         <JAVADOC />
         <SOURCES>
-          <root url="jar://$USER_HOME$/.grails/ivy-cache/org.springframework.security/spring-security-web/sources/spring-security-web-3.0.7.RELEASE-sources.jar!/" />
-          <root url="jar://$USER_HOME$/.grails/ivy-cache/org.springframework.security/spring-security-core/sources/spring-security-core-3.0.7.RELEASE-sources.jar!/" />
+          <root url="jar://$MODULE_DIR$/spring-security-core-3.0.7.RELEASE-sources.jar!/" />
         </SOURCES>
         <jarDirectory url="file://$MODULE_DIR$/lib" recursive="false" />
       </library>
     </orderEntry>
-    <orderEntry type="library" name="grails-2.1.0" level="application" />
-    <orderEntry type="module" module-name="Grails-spring-security-taobao-grailsPlugins" />
+    <orderEntry type="module" module-name="grails-spring-security-taobao-grailsPlugins" />
   </component>
 </module>
 

SpringSecurityTaobaoGrailsPlugin.groovy

-/* Copyright 2006-2011 the original author or authors.
-*
-* Licensed under the Apache License, Version 2.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*      http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
+import com.mingidea.security.alibaba.AlibabaAuthenticationFilter
+import com.mingidea.security.alibaba.AlibabaAuthenticationFilter
+import com.mingidea.security.alibaba.AlibabaAuthenticationProvider
+import com.mingidea.security.taobao.top.TaobaoTopAuthenticationFilter
+import com.mingidea.security.taobao.top.TaobaoTopAuthenticationProvider
 import org.codehaus.groovy.grails.plugins.springsecurity.SecurityFilterPosition
 import org.codehaus.groovy.grails.plugins.springsecurity.SpringSecurityUtils
 import org.springframework.security.core.session.SessionRegistryImpl
 */
 class SpringSecurityTaobaoGrailsPlugin {
     // the plugin version
-    def version = "1.0.12"
+    def version = "1.1"
     // the version or versions of Grails the plugin is designed for
     def grailsVersion = "2.1 > *"
     // the other plugins this plugin depends on
         // have to get again after overlaying DefaultTaobaoSecurityConfig
         conf = SpringSecurityUtils.securityConfig
 
-        if (!conf.taobao.active) {
-            return
+        // 淘宝
+        if (conf.taobao.active) {
+            println 'Configuring Spring Security Taobao ...'
+
+            // 注册淘宝拦截器
+            SpringSecurityUtils.registerProvider 'taobaoAuthenticationProvider'
+            SpringSecurityUtils.registerFilter 'taobaoAuthenticationFilter', conf.taobao.filter.position
+
+            taobaoAuthenticationProvider(TaobaoTopAuthenticationProvider) {
+                appSecretMap = conf.taobao.appSecretMap
+                authenticationDao = ref('taobaoAuthenticationDao')
+            }
+
+            taobaoAuthenticationFilter(TaobaoTopAuthenticationFilter, conf.taobao.filter.processUrl){
+                authenticationManager = ref('authenticationManager')
+                sessionAuthenticationStrategy = ref('sessionAuthenticationStrategy')
+
+                //ref to grails spring security core plugin
+                authenticationSuccessHandler = ref('authenticationSuccessHandler')
+                authenticationFailureHandler = ref('authenticationFailureHandler')
+                rememberMeServices = ref('rememberMeServices')
+                allowSessionCreation = conf.apf.allowSessionCreation
+            }
         }
 
-        println 'Configuring Spring Security Taobao ...'
+        if (conf.alibaba.active) {
+            println 'Configuring Spring Security Alibaba ...'
 
-        SpringSecurityUtils.registerProvider 'taobaoAuthenticationProvider'
-        SpringSecurityUtils.registerFilter 'taobaoAuthenticationFilter', SecurityFilterPosition.OPENID_FILTER
-		SpringSecurityUtils.registerFilter 'concurrentSessionFilter', SecurityFilterPosition.CONCURRENT_SESSION_FILTER
+            // 注册阿里巴巴拦截器
+            SpringSecurityUtils.registerProvider 'alibabaAuthenticationProvider'
+            SpringSecurityUtils.registerFilter 'alibabaAuthenticationFilter', conf.alibaba.filter.position
 
-        taobaoAuthenticationProvider(TaobaoAuthenticationProvider) {
-			
-            appSecretMap = conf.taobao.appSecretMap
-            taobaoAuthenticationDao = ref('taobaoAuthenticationDao')
+            alibabaAuthenticationProvider(AlibabaAuthenticationProvider) {
+                appSecretMap = conf.alibaba.appSecretMap
+                authenticationDao = ref('alibabaAuthenticationDao')
+            }
+
+            alibabaAuthenticationFilter(AlibabaAuthenticationFilter, conf.alibaba.filter.processUrl){
+                authenticationManager = ref('authenticationManager')
+                sessionAuthenticationStrategy = ref('sessionAuthenticationStrategy')
+
+                //ref to grails spring security core plugin
+                authenticationSuccessHandler = ref('authenticationSuccessHandler')
+                authenticationFailureHandler = ref('authenticationFailureHandler')
+                rememberMeServices = ref('rememberMeServices')
+                allowSessionCreation = conf.apf.allowSessionCreation
+            }
         }
 
-        taobaoAuthenticationFilter(TaobaoAuthenticationProcessingFilter){
-            authenticationManager = ref('authenticationManager')
-            sessionAuthenticationStrategy = ref('sessionAuthenticationStrategy')
-            
-            //ref to grails spring security core plugin
-            authenticationSuccessHandler = ref('authenticationSuccessHandler')
-            authenticationFailureHandler = ref('authenticationFailureHandler')
-            rememberMeServices = ref('rememberMeServices')
-            allowSessionCreation = conf.apf.allowSessionCreation
-        }
-		
-		sessionAuthenticationStrategy(ConcurrentSessionControlStrategy, ref('sessionRegistry')) {
-			maximumSessions = conf.maxConcurrentSessions //default is -1 for unlimited sessions
-		}
-		
+        SpringSecurityUtils.registerFilter 'concurrentSessionFilter', SecurityFilterPosition.CONCURRENT_SESSION_FILTER
+
 		concurrentSessionFilter(ConcurrentSessionFilter) {
 			sessionRegistry = ref('sessionRegistry')
 			expiredUrl = conf.expiredUrl
 		}
 		
 		sessionRegistry(SessionRegistryImpl)
+
+        sessionAuthenticationStrategy(ConcurrentSessionControlStrategy, ref('sessionRegistry')) {
+            maximumSessions = conf.maxConcurrentSessions //default is -1 for unlimited sessions
+        }
     }
 
     def doWithApplicationContext = { applicationContext ->

application.properties

 #Grails Metadata file
-#Thu Oct 25 23:49:27 CST 2012
+#Wed Dec 19 14:12:42 CST 2012
 app.grails.version=2.1.1
 app.name=spring-security-taobao
 plugins.hibernate=2.1.1

grails-app/conf/BuildConfig.groovy

 		grailsCentral()
 
 		mavenCentral()
+
+        mavenRepo "http://snapshots.repository.codehaus.org"
+        mavenRepo "http://repository.codehaus.org"
+        mavenRepo "http://download.java.net/maven/2/"
+        mavenRepo "http://repository.jboss.com/maven2/"
     }
     dependencies {
         // specify dependencies here under either 'build', 'compile', 'runtime', 'test' or 'provided' scopes eg.
         // runtime 'mysql:mysql-connector-java:5.1.13'
+        compile 'com.google.code.gson:gson:2.2.2'
     }
 }

grails-app/conf/Config.groovy

     //
     
     root {
-        info 'stdout'
+        debug 'stdout'
     }
     appenders {
         console name:'stdout', layout:pattern(conversionPattern: '%c{2} %m%n')
            'org.springframework',
            'org.hibernate',
            'net.sf.ehcache.hibernate',
-		   'org.springframework.security',
 		   'com.mingidea.security',
 		   'grails.plugins.springsecurity',
 		   'org.codehaus.groovy.grails.plugins.springsecurity'
 
     warn   'org.mortbay.log'
 
-    debug 'com.mingidea'
+    debug 'com.mingidea',
+          'org.springframework.security'
 }
 
 grails.plugins.springsecurity.expiredUrl = '/expired'
 //test_app_1的appkey 和 appscert
 grails.plugins.springsecurity.taobao.appSecretMap = ['12264981' : '4aaaabc0a7057c3fd36b8de889d4aa65']
 
+grails.plugins.springsecurity.alibaba.appSecretMap = ['1003921' : 'K=PQvl]lhhq']
+
 grails.plugins.springsecurity.securityConfigType = "InterceptUrlMap"
 grails.plugins.springsecurity.interceptUrlMap = [
     '/secure/**':    ['ROLE_USER'],

grails-app/conf/DefaultTaobaoSecurityConfig.groovy

         //appKey -> appSecret
         appSecretMap = [:]
         active = true
+        filter {
+            processUrl = '/j_spring_taobao_security_check'
+            position = 900 // 和OPEN_ID位置一样
+        }
+    }
+
+    alibaba {
+        appSecretMap = [:]
+        active = true
+        filter {
+            processUrl = '/j_spring_alibaba_security_check'
+            position = 901
+        }
     }
 }

grails-app/conf/spring/resources.groovy

+import test.TestAlibabaAuthenticationDao
 import test.TestTaobaoAuthenticationDao
 
 beans = {
     taobaoAuthenticationDao(TestTaobaoAuthenticationDao) {
 
     }
+
+    alibabaAuthenticationDao(TestAlibabaAuthenticationDao) {
+
+    }
 }

grails-app/controllers/test/TestController.groovy

 package test
 
+import com.mingidea.security.util.HttpUtils
+import groovyx.net.http.HTTPBuilder
+import org.springframework.security.authentication.BadCredentialsException
+
 
 class TestController {
     def springSecurityService
     def concurrentSessionFilter
     def index = {
-        println request.requestURI
-//        def user = springSecurityService.currentUser
-//        render 'user id: '
-        render 'i'
+        String code = params.code
+        String url = 'https://gw.open.china.alibaba.com/openapi/http/1/system.oauth2/getToken/1003921'
+
+        String json = HttpUtils.post(url, 'grant_type=authorization_code&need_refresh_token=true&client_id=1003921&client_secret=z3-a:jDFBT]&redirect_uri=http://dev.mingidea.com:8080/spring-security-taobao/test&code=' + code)
+
+        render json
     }
-    
+
+
+    private String encodeUrl(String url) {
+        try {
+            return URLEncoder.encode(url, "UTF-8");
+        } catch (UnsupportedEncodingException e) {
+            throw new RuntimeException(e);
+        }
+    }
+
     def expire = {
         def userId = 1
 
     }
-    
+
     def p = {
         println concurrentSessionFilter
     }
-<plugin name='spring-security-taobao' version='1.0.12' grailsVersion='2.1 &gt; *'>
+<plugin name='spring-security-taobao' version='1.1-BATE-2' grailsVersion='2.1 &gt; *'>
   <author>Simon Leung</author>
   <authorEmail>simon.r.leung@gmail.com</authorEmail>
   <title>Spring Security Taobao Plugin</title>
     <repository name='grailsCentral' url='http://grails.org/plugins' />
     <repository name='http://repo.grails.org/grails/core' url='http://repo.grails.org/grails/core/' />
     <repository name='mavenCentral' url='http://repo1.maven.org/maven2/' />
+    <repository name='http://snapshots.repository.codehaus.org' url='http://snapshots.repository.codehaus.org/' />
+    <repository name='http://repository.codehaus.org' url='http://repository.codehaus.org/' />
+    <repository name='http://download.java.net/maven/2/' url='http://download.java.net/maven/2/' />
+    <repository name='http://repository.jboss.com/maven2/' url='http://repository.jboss.com/maven2/' />
   </repositories>
-  <dependencies />
+  <dependencies>
+    <compile>
+      <dependency group='com.google.code.gson' name='gson' version='2.2.2' />
+    </compile>
+  </dependencies>
   <plugins />
   <runtimePluginRequirements>
     <plugin name='springSecurityCore' version='1.2.7.3 &gt; *' />

src/groovy/test/TestAlibabaAuthenticationDao.groovy

+package test
+
+import com.mingidea.security.AuthenticationDao
+import com.mingidea.security.alibaba.AlibabaUser
+import org.springframework.security.core.userdetails.UserDetails
+
+/**
+ * @author Liang Yong Rui
+ */
+class TestAlibabaAuthenticationDao implements AuthenticationDao<AlibabaUser> {
+    @Override
+    AlibabaUser find(String userId, String appKey) {
+        println 'hello'
+        return null
+    }
+
+    @Override
+    void update(AlibabaUser user) {
+
+    }
+
+    @Override
+    void create(AlibabaUser user) {
+        print 'create alibaba user: ' + user.id
+    }
+
+    @Override
+    UserDetails getPrincipal(AlibabaUser user) {
+        return new org.springframework.security.core.userdetails.User("xx", "", true, true, true, true, []);
+    }
+}

src/groovy/test/TestTaobaoAuthenticationDao.groovy

 package test
 
+import com.mingidea.security.AuthenticationDao
 import org.springframework.security.core.userdetails.UserDetails
+import com.mingidea.security.taobao.TaobaoUser
 
-import com.mingidea.security.taobao.TaobaoAuthenticationDao
-import com.mingidea.security.taobao.TaobaoUser
-import org.apache.commons.codec.digest.DigestUtils
-import org.apache.commons.codec.binary.Base64
 
-class TestTaobaoAuthenticationDao implements TaobaoAuthenticationDao {
+class TestTaobaoAuthenticationDao implements AuthenticationDao<TaobaoUser> {
 
 
 
 	}
 
 	public void create(TaobaoUser taobaoUser) {
-		print 'create taobao user: ' + taobaoUser.nickname
+		print 'create taobao user: ' + taobaoUser.id
 
 	}
 

src/java/com/mingidea/security/AbstractAuthenticationProvider.java

+package com.mingidea.security;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.security.authentication.AuthenticationProvider;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.core.AuthenticationException;
+import org.springframework.security.core.userdetails.UserDetails;
+
+/**
+ *
+ * @author Liang Yong Rui
+ * @param <T> user type
+ */
+public abstract  class AbstractAuthenticationProvider<T extends User> implements AuthenticationProvider {
+    private final static Logger log = LoggerFactory.getLogger(AbstractAuthenticationProvider.class);
+
+    private AuthenticationDao<T> authenticationDao;
+
+    @Override
+    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
+        if (!supports(authentication.getClass())) {
+            return null;
+        }
+        Object credentials = authentication.getCredentials();
+        T user = validateCredentials(credentials);
+
+        String userId = user.getId();
+        T persistedUser = authenticationDao.find(userId, user.getAppKey());
+
+        if(persistedUser == null) {
+            log.info("create user: {}", user);
+            authenticationDao.create(user);
+        }
+        else if(!user.equals(persistedUser)) {
+            log.debug("update user: {}", user);
+            authenticationDao.update(user);
+        }
+
+        UserDetails userDetails = authenticationDao.getPrincipal(user);
+        if (userDetails == null) {
+            throw new PrincipalNotFoundException("can not found principal for user :" + userId);
+        }
+
+        return new AuthenticationToken(userDetails);
+    }
+
+    /**
+     * 校验credentials,如果正确则返回相应的User对象,如果不正确则抛出相应的AuthenticationException
+     * @param credentials
+     * @return the auth user
+     * @see AuthenticationException
+     */
+    protected abstract T validateCredentials(Object credentials);
+
+    public void setAuthenticationDao(AuthenticationDao<T> authenticationDao) {
+        this.authenticationDao = authenticationDao;
+    }
+
+    public AuthenticationDao<T> getAuthenticationDao() {
+        return authenticationDao;
+    }
+}

src/java/com/mingidea/security/AuthenticationDao.java

+package com.mingidea.security;
+
+import org.springframework.security.core.userdetails.UserDetails;
+
+/**
+ * @author Liang Yong Rui
+ */
+public interface AuthenticationDao<U extends User> {
+    /**
+     *
+     * @param userId 用户唯一ID
+     * @return 如果不存在返回null
+     */
+    public U find(String userId, String appKey);
+
+    public void update(U user);
+
+    public void create(U user);
+
+    public UserDetails getPrincipal(U user);
+}

src/java/com/mingidea/security/AuthenticationToken.java

+package com.mingidea.security;
+
+import org.springframework.security.authentication.AbstractAuthenticationToken;
+import org.springframework.security.core.GrantedAuthority;
+import org.springframework.security.core.userdetails.UserDetails;
+
+import java.util.Collections;
+import java.util.List;
+
+/**
+ * @author Liang Yong Rui
+ * @param <T> credentials的类型
+ */
+public class AuthenticationToken<T> extends AbstractAuthenticationToken {
+    private static final List<GrantedAuthority> EMPTY_AUTHORITIES = Collections.emptyList();
+
+    private T credentials;
+    private UserDetails principal;
+
+    public AuthenticationToken(T credentials) {
+        super(EMPTY_AUTHORITIES);
+        this.credentials = credentials;
+        this.setAuthenticated(false);
+    }
+
+    public AuthenticationToken(UserDetails principal) {
+        super(principal.getAuthorities());
+        this.principal = principal;
+        this.setAuthenticated(true);
+    }
+
+    @Override
+    public T getCredentials() {
+        return credentials;
+    }
+
+    @Override
+    public UserDetails getPrincipal() {
+        return principal;
+    }
+}

src/java/com/mingidea/security/PrincipalNotFoundException.java

+package com.mingidea.security;
+
+import org.springframework.security.core.AuthenticationException;
+
+public class PrincipalNotFoundException extends AuthenticationException {
+	private static final long serialVersionUID = 1L;
+
+	public PrincipalNotFoundException(String message) {
+		super(message);
+	}
+}

src/java/com/mingidea/security/User.java

+package com.mingidea.security;
+
+import org.apache.commons.lang.builder.EqualsBuilder;
+import org.apache.commons.lang.builder.HashCodeBuilder;
+import org.apache.commons.lang.builder.ToStringBuilder;
+import org.apache.commons.lang.builder.ToStringStyle;
+
+import java.io.Serializable;
+
+/**
+ * @author Liang Yong Rui
+ */
+public class User {
+    private String id;
+    private String appKey;
+
+    public User(String id, String appKey) {
+        this.id = id;
+        this.appKey = appKey;
+    }
+
+    public String getId() {
+        return id;
+    }
+
+    public void setId(String id) {
+        this.id = id;
+    }
+
+    public String getAppKey() {
+        return appKey;
+    }
+
+    public void setAppKey(String appKey) {
+        this.appKey = appKey;
+    }
+
+    @Override
+    public boolean equals(Object obj) {
+        return EqualsBuilder.reflectionEquals(this, obj);
+    }
+
+    @Override
+    public int hashCode() {
+        return HashCodeBuilder.reflectionHashCode(this);
+    }
+
+    @Override
+    public String toString() {
+        return ToStringBuilder.reflectionToString(this, ToStringStyle.SIMPLE_STYLE);
+    }
+}

src/java/com/mingidea/security/alibaba/AlibabaAuthenticationFilter.java

+package com.mingidea.security.alibaba;
+
+import com.mingidea.security.AuthenticationToken;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.core.AuthenticationException;
+import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
+
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+
+/**
+ * 阿里巴巴开放平台OAuth2.0授权Filter
+ * 参考文档: http://open.china.alibaba.com/doc/api/cn/sys_auth.htm?ns=cn.alibaba.open
+ * @author Liang Yong Rui
+ */
+public class AlibabaAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
+    protected AlibabaAuthenticationFilter(String filterProcessUrl) {
+        super(filterProcessUrl);
+    }
+
+    @Override
+    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
+        String appKey = request.getParameter("appKey");
+        String code = request.getParameter("code");
+        AlibabaCredentials credentials = new AlibabaCredentials(appKey, code);
+        AlibabaAuthenticationToken token = new AlibabaAuthenticationToken(credentials);
+
+        // delegate to the authentication provider
+        Authentication authentication = this.getAuthenticationManager().authenticate(token);
+
+        return authentication;
+    }
+}

src/java/com/mingidea/security/alibaba/AlibabaAuthenticationProvider.java

+package com.mingidea.security.alibaba;
+
+import com.google.gson.FieldNamingPolicy;
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.mingidea.security.AbstractAuthenticationProvider;
+import com.mingidea.security.util.HttpUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.InitializingBean;
+import org.springframework.security.authentication.BadCredentialsException;
+import org.springframework.util.Assert;
+
+import java.io.IOException;
+import java.util.Map;
+
+/**
+ * @author Liang Yong Rui
+ */
+public class AlibabaAuthenticationProvider extends AbstractAuthenticationProvider<AlibabaUser> implements InitializingBean {
+    private static Logger log = LoggerFactory.getLogger(AlibabaAuthenticationProvider.class);
+    private static Gson gson = new GsonBuilder()
+                                    .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
+                                    .create();
+
+
+    /**
+     * appKey to appSecret mapping
+     */
+    private Map<String, String> appSecretMap;
+
+    @Override
+    protected AlibabaUser validateCredentials(Object credentials) {
+        AlibabaCredentials alibabaCredentials = (AlibabaCredentials)credentials;
+        String appKey = alibabaCredentials.getAppKey();
+        String code = alibabaCredentials.getCode();
+        OAuthToken oAuthToken = getOAuthToken(appKey, code);
+
+        AlibabaUser user = new AlibabaUser(oAuthToken.resourceOwner, appKey);
+        user.setAccessToken(oAuthToken.getAccessToken());
+        user.setRefreshToken(oAuthToken.getRefreshToken());
+        user.setExpiresIn(oAuthToken.getExpiresIn());
+
+        return user;
+    }
+
+    private OAuthToken getOAuthToken(String appKey, String code) {
+        String url = "https://gw.open.china.alibaba.com/openapi/http/1/system.oauth2/getToken/" + appKey;
+        String parameters = buildOAuthTokenParameters(appKey, code);
+        String json = null;
+        try {
+            json = HttpUtils.post(url, parameters);
+        } catch (IOException e) {
+            log.error("fail to get oauth token", e);
+            throw new BadCredentialsException("fail to get oauth token", e);
+        }
+        return gson.fromJson(json, OAuthToken.class);
+    }
+
+    private String buildOAuthTokenParameters(String appKey, String code) {
+        String appSecret = appSecretMap.get(appKey);
+        if (appSecret == null) {
+            throw new BadCredentialsException("can't not find appSecret for appKey: " + appKey);
+        }
+
+        return new StringBuilder()
+                .append("grant_type=authorization_code&need_refresh_token=true&client_id=")
+                .append(appKey)
+                .append("&client_secret=")
+                .append(HttpUtils.encodeUrl(appSecret))
+                .append("&redirect_uri=")
+                //TODO 动态配置
+                .append(HttpUtils.encodeUrl("http://dev.mingidea.com:8080/spring-security-taobao/j_spring_alibaba_security_check?appKey=1003921"))
+                .append("&code=")
+                .append(code)
+                .toString();
+    }
+
+    public void setAppSecretMap(Map<String, String> appSecretMap) {
+        this.appSecretMap = appSecretMap;
+    }
+
+    @Override
+    public boolean supports(Class<? extends Object> authenticationClass) {
+        return AlibabaAuthenticationToken.class.isAssignableFrom(authenticationClass);
+    }
+
+    @Override
+    public void afterPropertiesSet() throws Exception {
+        Assert.notNull(appSecretMap, "The appSecretMap property can't be null");
+    }
+
+    private class OAuthToken {
+        private String resourceOwner;
+        private Long expiresIn;
+        private String accessToken;
+        private String refreshToken;
+
+        public String getResourceOwner() {
+            return resourceOwner;
+        }
+
+        public void setResourceOwner(String resourceOwner) {
+            this.resourceOwner = resourceOwner;
+        }
+
+        public Long getExpiresIn() {
+            return expiresIn;
+        }
+
+        public void setExpiresIn(Long expiresIn) {
+            this.expiresIn = expiresIn;
+        }
+
+        public String getAccessToken() {
+            return accessToken;
+        }
+
+        public void setAccessToken(String accessToken) {
+            this.accessToken = accessToken;
+        }
+
+        public String getRefreshToken() {
+            return refreshToken;
+        }
+
+        public void setRefreshToken(String refreshToken) {
+            this.refreshToken = refreshToken;
+        }
+    }
+}

src/java/com/mingidea/security/alibaba/AlibabaAuthenticationToken.java

+package com.mingidea.security.alibaba;
+
+import com.mingidea.security.AuthenticationToken;
+import org.springframework.security.core.userdetails.UserDetails;
+
+import java.util.Collection;
+
+/**
+ * @author Liang Yong Rui
+ */
+public class AlibabaAuthenticationToken extends AuthenticationToken<AlibabaCredentials> {
+
+    public AlibabaAuthenticationToken(AlibabaCredentials credentials) {
+        super(credentials);
+    }
+
+    public AlibabaAuthenticationToken(UserDetails principal) {
+        super(principal);
+    }
+}

src/java/com/mingidea/security/alibaba/AlibabaCredentials.java

+package com.mingidea.security.alibaba;
+
+import java.io.Serializable;
+
+/**
+ * 阿里巴巴OAuth登陆证书
+ * @author Liang Yong Rui
+ */
+public class AlibabaCredentials implements Serializable {
+    private static final long serialVersionUID = 1L;
+    private String appKey;
+    private String code;
+
+    public AlibabaCredentials(String appKey, String code) {
+        this.appKey = appKey;
+        this.code = code;
+    }
+
+    public String getAppKey() {
+        return appKey;
+    }
+
+    public String getCode() {
+        return code;
+    }
+}

src/java/com/mingidea/security/alibaba/AlibabaUser.java

+package com.mingidea.security.alibaba;
+
+import com.mingidea.security.User;
+
+/**
+ * @author Liang Yong Rui
+ */
+public class AlibabaUser extends User {
+    private String accessToken;
+    private String refreshToken;
+    private Long expiresIn;
+
+    public AlibabaUser(String id, String appKey) {
+        super(id, appKey);
+    }
+
+    public String getAccessToken() {
+        return accessToken;
+    }
+
+    public void setAccessToken(String accessToken) {
+        this.accessToken = accessToken;
+    }
+
+    public String getRefreshToken() {
+        return refreshToken;
+    }
+
+    public void setRefreshToken(String refreshToken) {
+        this.refreshToken = refreshToken;
+    }
+
+    public Long getExpiresIn() {
+        return expiresIn;
+    }
+
+    public void setExpiresIn(Long expiresIn) {
+        this.expiresIn = expiresIn;
+    }
+}

src/java/com/mingidea/security/taobao/PrincipalNotFoundException.java

-package com.mingidea.security.taobao;
-
-import org.springframework.security.core.AuthenticationException;
-
-public class PrincipalNotFoundException extends AuthenticationException {
-	private static final long serialVersionUID = 1L;
-
-	public PrincipalNotFoundException(String msg) {
-		super(msg);
-	}
-}

src/java/com/mingidea/security/taobao/TaobaoAuthenticationDao.java

-package com.mingidea.security.taobao;
-
-import org.springframework.security.core.userdetails.UserDetails;
-
-public interface TaobaoAuthenticationDao {
-	/**
-	 * 
-	 * @param nick 淘宝用户昵称
-	 * @return 如果不存在返回null
-	 */
-	public TaobaoUser find(String nick, String appKey);
-
-	public void update(TaobaoUser taobaoUser);
-
-	public void create(TaobaoUser taobaoUser);
-
-	public UserDetails getPrincipal(TaobaoUser taobaoUser);
-}

src/java/com/mingidea/security/taobao/TaobaoAuthenticationProcessingFilter.java

-package com.mingidea.security.taobao;
-
-import java.io.IOException;
-
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.security.core.Authentication;
-import org.springframework.security.core.AuthenticationException;
-import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
-
-public class TaobaoAuthenticationProcessingFilter extends AbstractAuthenticationProcessingFilter {
-    private static Logger log = LoggerFactory.getLogger(TaobaoAuthenticationProcessingFilter.class);
-
-    public TaobaoAuthenticationProcessingFilter() {
-        super("/j_spring_taobao_security_check");
-    }
-
-    @Override
-    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
-        throws AuthenticationException, IOException, ServletException {
-
-        TaobaoCredentials credentials = TaobaoCredentials.build(request);
-        TaobaoAuthenticationToken token = new TaobaoAuthenticationToken(credentials);
-        // delegate to the authentication provider
-        Authentication authentication = this.getAuthenticationManager().authenticate(token);
-
-        return authentication;
-    }
-}

src/java/com/mingidea/security/taobao/TaobaoAuthenticationProvider.java

-package com.mingidea.security.taobao;
-
-import java.util.Map;
-
-import org.apache.commons.codec.binary.Base64;
-import org.apache.commons.codec.digest.DigestUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.BeansException;
-import org.springframework.beans.factory.InitializingBean;
-import org.springframework.context.ApplicationContext;
-import org.springframework.context.ApplicationContextAware;
-import org.springframework.security.authentication.AuthenticationProvider;
-import org.springframework.security.authentication.BadCredentialsException;
-import org.springframework.security.authentication.CredentialsExpiredException;
-import org.springframework.security.core.Authentication;
-import org.springframework.security.core.AuthenticationException;
-import org.springframework.security.core.userdetails.UserDetails;
-import org.springframework.util.Assert;
-
-public class TaobaoAuthenticationProvider implements AuthenticationProvider, InitializingBean, ApplicationContextAware {
-    private final static Logger log = LoggerFactory.getLogger(TaobaoAuthenticationProvider.class);
-
-    private ApplicationContext applicationContext;
-
-    private TaobaoAuthenticationDao taobaoAuthenticationDao;
-
-    /**
-     * appKey to appSecret mapping
-     */
-    private Map<String, String> appSecretMap;
-
-    @Override
-    public void afterPropertiesSet() throws Exception {
-        Assert.notNull(taobaoAuthenticationDao, "The taobaoAuthenticationDao property can't be null");
-        Assert.notNull(appSecretMap, "The appSecretMap property can't be null");
-    }
-
-    @Override
-    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
-        if (!supports(authentication.getClass())) {
-            return null;
-        }
-
-        TaobaoAuthenticationToken token = (TaobaoAuthenticationToken) authentication;
-        TaobaoCredentials credentials = (TaobaoCredentials) token.getCredentials();
-        validateCredentials(credentials);
-
-        // 淘宝用户昵称
-        String mainNickname = credentials.getVisitorNick(); // 主账号
-        String subNickname = credentials.getSubTaobaoUserNick(); // 子账号
-        String nickname = (subNickname != null) ? subNickname : mainNickname;
-        String appKey = credentials.getAppKey();
-
-        TaobaoUser taobaoUser = taobaoAuthenticationDao.find(nickname, appKey);
-        if (taobaoUser == null) {
-            log.debug("create taobao user {}", nickname);
-            taobaoUser = new TaobaoUser(nickname, appKey);
-            copyProperties(credentials, taobaoUser);
-            taobaoAuthenticationDao.create(taobaoUser);
-            applicationContext.publishEvent(new TaobaoUserCreatedEvent(this, taobaoUser));
-        } else {
-            log.debug("update taobao user {} with session {}", nickname, credentials.getSession());
-            copyProperties(credentials, taobaoUser);
-            taobaoAuthenticationDao.update(taobaoUser);
-            applicationContext.publishEvent(new TaobaoUserUpdatedEvent(this, taobaoUser));
-        }
-
-        UserDetails userDetails = taobaoAuthenticationDao.getPrincipal(taobaoUser);
-
-        if (userDetails == null) {
-            throw new PrincipalNotFoundException("can not found principal for taobao user [" + nickname + "]");
-        } else {
-            //remove credentials
-            return new TaobaoAuthenticationToken(userDetails, null, userDetails.getAuthorities());
-        }
-    }
-
-    /**
-     * copy properties from credentials to taobao user
-     */
-    private void copyProperties(TaobaoCredentials credentials, TaobaoUser taobaoUser) {
-        taobaoUser.setSession(credentials.getSession());
-        taobaoUser.setTimestamp(credentials.getTimestamp());
-        taobaoUser.setExpiresIn(credentials.getExpiresIn());
-        taobaoUser.setR1ExpiresIn(credentials.getR1ExpiresIn());
-        taobaoUser.setR2ExpiresIn(credentials.getR2ExpiresIn());
-        taobaoUser.setW1ExpiresIn(credentials.getW1ExpiresIn());
-        taobaoUser.setW2ExpiresIn(credentials.getW2ExpiresIn());
-        taobaoUser.setRefreshToken(credentials.getRefreshToken());
-        taobaoUser.setReExpiresIn(credentials.getReExpiresIn());
-    }
-
-    /**
-     * @throws BadCredentialsException credentials is invalid
-     */
-    private void validateCredentials(TaobaoCredentials credentials) throws BadCredentialsException {
-        String appkey = credentials.getAppKey();
-        String parameters = credentials.getParameters();
-        String session = credentials.getSession();
-        String sign = credentials.getSign();
-        validateSign(appkey, parameters, session, sign);
-
-        validateTime(credentials.getTimestamp());
-    }
-
-    /**
-     * 签名规则为base64(md5(top_appkey+top_parameters+top_session+app_secret))
-     *
-     * @throws CredentialsExpiredException
-     */
-    private void validateSign(String appkey, String parameters, String session, String sign)
-            throws BadCredentialsException {
-        String appSecret = this.appSecretMap.get(appkey);
-        if (appSecret == null) {
-            log.error("The corresponding App Secret can't be found. appKey: {}", appkey);
-            throw new BadCredentialsException("The corresponding App Secret can't be found");
-        }
-        byte[] md5 = DigestUtils.md5(appkey + parameters + session + appSecret);
-        // apache commons codec的版本要在1.5及以上,否则计算出来的签名会多一个回车导致异常
-        String calculatedSign = Base64.encodeBase64String(md5);
-        if (!calculatedSign.equals(sign)) {
-            throw new BadCredentialsException("The sign is invalid expected sign is: " + sign + ", but calculated is : " + calculatedSign);
-        }
-    }
-
-    /**
-     * 请求时间不能和当前时间超过30分钟
-     *
-     * @param timestamp
-     * @throws BadCredentialsException
-     */
-    private void validateTime(long timestamp) throws BadCredentialsException {
-        long now = System.currentTimeMillis();
-        if ((now - timestamp) > 1800000) { // 30分钟
-            throw new CredentialsExpiredException(
-                    "The difference between the request time and the server's time is too large");
-        }
-    }
-
-    public void setTaobaoAuthenticationDao(TaobaoAuthenticationDao taobaoAuthenticationDao) {
-        this.taobaoAuthenticationDao = taobaoAuthenticationDao;
-    }
-
-    public void setAppSecretMap(Map<String, String> appSecretMap) {
-        this.appSecretMap = appSecretMap;
-    }
-
-    @Override
-    public boolean supports(Class<?> authentication) {
-        return TaobaoAuthenticationToken.class.isAssignableFrom(authentication);
-    }
-
-    @Override
-    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
-        this.applicationContext = applicationContext;
-    }
-}

src/java/com/mingidea/security/taobao/TaobaoAuthenticationToken.java

-package com.mingidea.security.taobao;
-
-import java.util.Collection;
-
-import org.springframework.security.authentication.AbstractAuthenticationToken;
-import org.springframework.security.core.GrantedAuthority;
-
-@SuppressWarnings("serial")
-public class TaobaoAuthenticationToken extends AbstractAuthenticationToken {
-    private TaobaoCredentials credentials;
-    private Object principal;
-    
-    public TaobaoAuthenticationToken(TaobaoCredentials credentials) {
-        super(null);
-        this.credentials = credentials;
-        this.principal = credentials.getVisitorNick();
-        this.setAuthenticated(false);
-    }
-    
-    public TaobaoAuthenticationToken(Object principal, TaobaoCredentials credentials, Collection<? extends GrantedAuthority> authorities) {
-        super(authorities);    
-        this.principal = principal;
-        this.credentials = credentials;
-        this.setAuthenticated(true);
-    }
-
-    @Override
-    public Object getCredentials() {
-        return credentials;
-    }
-
-    @Override
-    public Object getPrincipal() {
-        return principal;
-    }
-}

src/java/com/mingidea/security/taobao/TaobaoUser.java

 package com.mingidea.security.taobao;
 
-public class TaobaoUser {
-    /**
-     * 昵称(如果该用户是子账号则为子账号,否则则与主账号相同)
-     */
-    private String nickname;
-    private String appKey;
+import com.mingidea.security.User;
+
+public class TaobaoUser extends User {
     private String session;
 
     private long timestamp;
 
     private String refreshToken;
 
-    public TaobaoUser(String nickname, String appKey) {
-        this.nickname = nickname;
-        this.appKey = appKey;
-    }
-
-    public void setNickname(String nickname) {
-        this.nickname = nickname;
-    }
-
-    public String getNickname() {
-        return nickname;
-    }
-
-    public String getAppKey() {
-        return appKey;
-    }
-
-    public void setAppKey(String appKey) {
-        this.appKey = appKey;
+    public TaobaoUser(String userId, String appKey) {
+        super(userId, appKey);
     }
 
     public String getSession() {

src/java/com/mingidea/security/taobao/TaobaoUserCreatedEvent.java

-package com.mingidea.security.taobao;
-
-import org.springframework.context.ApplicationEvent;
-
-public class TaobaoUserCreatedEvent extends ApplicationEvent {
-	private static final long serialVersionUID = 1L;
-	
-	private TaobaoUser taobaoUser;
-	
-	public TaobaoUserCreatedEvent(Object source, TaobaoUser taobaoUser) {
-		super(source);
-		this.taobaoUser = taobaoUser;
-	}
-
-	public TaobaoUser getTaobaoUser() {
-		return taobaoUser;
-	}
-}

src/java/com/mingidea/security/taobao/TaobaoUserUpdatedEvent.java

-package com.mingidea.security.taobao;
-
-import org.springframework.context.ApplicationEvent;
-
-public class TaobaoUserUpdatedEvent extends ApplicationEvent {
-	private static final long serialVersionUID = 1L;
-	private TaobaoUser taobaoUser;
-
-	public TaobaoUserUpdatedEvent(Object source, TaobaoUser taobaoUser) {
-		super(source);
-		this.taobaoUser = taobaoUser;
-	}
-
-	public TaobaoUser getTaobaoUser() {
-		return taobaoUser;
-	}
-}

src/java/com/mingidea/security/taobao/oauth/TaobaoOAuthAuthenticationFilter.java

+package com.mingidea.security.taobao.oauth;
+
+/**
+ * @author Liang Yong Rui
+ */
+public class TaobaoOAuthAuthenticationFilter {
+}

src/java/com/mingidea/security/taobao/top/TaobaoTopAuthenticationFilter.java

+package com.mingidea.security.taobao.top;
+
+import java.io.IOException;
+
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import com.mingidea.security.taobao.TaobaoCredentials;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.core.AuthenticationException;
+import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
+
+/**
+ * 淘宝开放平台基于TOP协议的登录授权Filter
+ * 参考文档:http://open.taobao.com/doc/detail.htm?id=105
+ */
+public class TaobaoTopAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
+    private static Logger log = LoggerFactory.getLogger(TaobaoTopAuthenticationFilter.class);
+
+    public TaobaoTopAuthenticationFilter(String filterProcessUrl) {
+        super(filterProcessUrl);
+    }
+
+    @Override
+    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
+        throws AuthenticationException, IOException, ServletException {
+
+        TaobaoCredentials credentials = TaobaoCredentials.build(request);
+        TaobaoTopAuthenticationToken token = new TaobaoTopAuthenticationToken(credentials);
+        // delegate to the authentication provider
+        Authentication authentication = this.getAuthenticationManager().authenticate(token);
+
+        return authentication;
+    }
+}

src/java/com/mingidea/security/taobao/top/TaobaoTopAuthenticationProvider.java

+package com.mingidea.security.taobao.top;
+
+import java.util.Map;
+
+import com.mingidea.security.AbstractAuthenticationProvider;
+import com.mingidea.security.taobao.*;
+import com.mingidea.security.taobao.TaobaoCredentials;
+import org.apache.commons.codec.binary.Base64;
+import org.apache.commons.codec.digest.DigestUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.InitializingBean;
+import org.springframework.security.authentication.BadCredentialsException;
+import org.springframework.security.authentication.CredentialsExpiredException;
+import org.springframework.util.Assert;
+
+/**
+ * @author Liang Yong Rui
+ */
+public class TaobaoTopAuthenticationProvider extends AbstractAuthenticationProvider<TaobaoUser> implements InitializingBean {
+    private final static Logger log = LoggerFactory.getLogger(TaobaoTopAuthenticationProvider.class);
+
+    /**
+     * appKey to appSecret mapping
+     */
+    private Map<String, String> appSecretMap;
+
+    @Override
+    protected TaobaoUser validateCredentials(Object credentials) {
+        TaobaoCredentials taobaoCredentials = (TaobaoCredentials)credentials;
+
+        String appKey = taobaoCredentials.getAppKey();
+        String parameters = taobaoCredentials.getParameters();
+        String session = taobaoCredentials.getSession();
+        String sign = taobaoCredentials.getSign();
+
+        validateSign(appKey, parameters, session, sign);
+        validateTime(taobaoCredentials.getTimestamp());
+
+        // 淘宝用户昵称
+        String mainNickname = taobaoCredentials.getVisitorNick(); // 主账号
+        String subNickname = taobaoCredentials.getSubTaobaoUserNick(); // 子账号
+        String userId = (subNickname != null) ? subNickname : mainNickname;
+
+        TaobaoUser taobaoUser = new TaobaoUser(userId, appKey);
+        copyProperties(taobaoCredentials, taobaoUser);
+
+        return taobaoUser;
+    }
+
+    /**
+     * 签名规则为base64(md5(top_appkey+top_parameters+top_session+app_secret))
+     *
+     * @throws CredentialsExpiredException
+     */
+    private void validateSign(String appkey, String parameters, String session, String sign)
+            throws BadCredentialsException {
+        String appSecret = this.appSecretMap.get(appkey);
+        if (appSecret == null) {
+            log.error("The corresponding App Secret can't be found. appKey: {}", appkey);
+            throw new BadCredentialsException("The corresponding App Secret can't be found");
+        }
+        byte[] md5 = DigestUtils.md5(appkey + parameters + session + appSecret);
+        // apache commons codec的版本要在1.5及以上,否则计算出来的签名会多一个回车导致异常
+        String calculatedSign = Base64.encodeBase64String(md5);
+        if (!calculatedSign.equals(sign)) {
+            throw new BadCredentialsException("The sign is invalid expected sign is: " + sign + ", but calculated is : " + calculatedSign);
+        }
+    }
+
+    /**
+     * 请求时间不能和当前时间超过30分钟
+     *
+     * @param timestamp
+     * @throws BadCredentialsException
+     */
+    private void validateTime(long timestamp) throws BadCredentialsException {
+        long now = System.currentTimeMillis();
+        if ((now - timestamp) > 1800000) { // 30分钟
+            throw new CredentialsExpiredException(
+                    "The difference between the request time and the server's time is too large");
+        }
+    }
+
+    @Override
+    public void afterPropertiesSet() throws Exception {
+        Assert.notNull(getAuthenticationDao(), "The authenticationDao property can't be null");
+        Assert.notNull(appSecretMap, "The appSecretMap property can't be null");
+    }
+
+    /**
+     * copy properties from credentials to taobao user
+     */
+    private void copyProperties(TaobaoCredentials credentials, TaobaoUser taobaoUser) {
+        taobaoUser.setSession(credentials.getSession());
+        taobaoUser.setTimestamp(credentials.getTimestamp());
+        taobaoUser.setExpiresIn(credentials.getExpiresIn());
+        taobaoUser.setR1ExpiresIn(credentials.getR1ExpiresIn());
+        taobaoUser.setR2ExpiresIn(credentials.getR2ExpiresIn());
+        taobaoUser.setW1ExpiresIn(credentials.getW1ExpiresIn());
+        taobaoUser.setW2ExpiresIn(credentials.getW2ExpiresIn());
+        taobaoUser.setRefreshToken(credentials.getRefreshToken());
+        taobaoUser.setReExpiresIn(credentials.getReExpiresIn());
+    }
+
+
+
+    public void setAppSecretMap(Map<String, String> appSecretMap) {
+        this.appSecretMap = appSecretMap;
+    }
+
+    @Override
+    public boolean supports(Class<?> authentication) {
+        return TaobaoTopAuthenticationToken.class.isAssignableFrom(authentication);
+    }
+}

src/java/com/mingidea/security/taobao/top/TaobaoTopAuthenticationToken.java

+package com.mingidea.security.taobao.top;
+
+import com.mingidea.security.AuthenticationToken;
+import com.mingidea.security.taobao.TaobaoCredentials;
+import org.springframework.security.core.userdetails.UserDetails;
+
+public class TaobaoTopAuthenticationToken extends AuthenticationToken<TaobaoCredentials> {
+    public TaobaoTopAuthenticationToken(TaobaoCredentials credentials) {
+        super(credentials);
+    }
+
+    public TaobaoTopAuthenticationToken(UserDetails principal) {
+        super(principal);
+    }
+}

src/java/com/mingidea/security/util/HttpUtils.java

+package com.mingidea.security.util;
+
+import org.apache.commons.io.IOUtils;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.UnsupportedEncodingException;
+import java.net.HttpURLConnection;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.net.URLEncoder;
+
+/**
+ * @author Liang Yong Rui
+ */
+public class HttpUtils {
+    public static String post(String urlString, String parameters) throws IOException {
+        URL url = new URL(urlString);
+        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
+        urlConnection.setRequestMethod("POST");
+        urlConnection.setDoOutput(true);
+        urlConnection.setDoInput(true);
+        urlConnection.setUseCaches(false);
+        urlConnection.connect();
+
+        OutputStream output = null;
+        InputStream input = null;
+        try {
+            output = urlConnection.getOutputStream();
+            output.write(parameters.getBytes());
+            input = urlConnection.getInputStream();
+            return IOUtils.toString(input, "UTF-8");
+        } finally {
+            IOUtils.closeQuietly(output);
+            IOUtils.closeQuietly(input);
+        }
+    }
+
+    public static String encodeUrl(String url) {
+        try {
+            return URLEncoder.encode(url, "UTF-8");
+        } catch (UnsupportedEncodingException e) {
+            throw new RuntimeException(e);
+        }
+    }
+}
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.