Prechádzať zdrojové kódy

接口优化,请求参数access_token , header Authorization , token

MaxKey 2 rokov pred
rodič
commit
6a534e9f67

+ 15 - 26
maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/maxkey/authz/oauth2/provider/endpoint/IntrospectEndpoint.java

@@ -28,8 +28,8 @@ import org.maxkey.authz.oauth2.provider.ClientDetailsService;
 import org.maxkey.authz.oauth2.provider.OAuth2Authentication;
 import org.maxkey.authz.oauth2.provider.token.DefaultTokenServices;
 import org.maxkey.util.AuthorizationHeaderCredential;
-import org.maxkey.util.AuthorizationHeaderUtils;
 import org.maxkey.util.JsonUtils;
+import org.maxkey.util.RequestTokenUtils;
 import org.maxkey.web.HttpResponseAdapter;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -40,8 +40,6 @@ import org.springframework.security.authentication.UsernamePasswordAuthenticatio
 import org.springframework.stereotype.Controller;
 import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.bind.annotation.RequestParam;
-
 import io.swagger.v3.oas.annotations.Operation;
 import io.swagger.v3.oas.annotations.tags.Tag;
 
@@ -63,35 +61,26 @@ public class IntrospectEndpoint {
     @Autowired
     protected HttpResponseAdapter httpResponseAdapter;
 	
-    @Operation(summary = "OAuth 2.0 令牌验证接口", description = "传递参数token or access_token",method="POST,GET")
+    @Operation(summary = "OAuth 2.0 令牌验证接口", description = "请求参数access_token , header Authorization , token ",method="POST,GET")
 	@RequestMapping(value=OAuth2Constants.ENDPOINT.ENDPOINT_BASE + "/introspect", method = {RequestMethod.POST, RequestMethod.GET}) 
-	public void introspect(
-			@RequestParam(value = "token", required = false) String token,
-			@RequestParam(value = "access_token", required = false) String access_token,
-            HttpServletRequest request, HttpServletResponse response) {	  
-    	String  authorization = request.getHeader(AuthorizationHeaderUtils.HEADER_Authorization);
-		AuthorizationHeaderCredential headerCredential = AuthorizationHeaderUtils.resolve(authorization);
-		_logger.debug("Credential {}" , headerCredential);
-		if(StringUtils.isNotBlank(token)) {
-			access_token = token;
-		}
-        if(StringUtils.isBlank(access_token)) {
-        	_logger.error("access_token is null .");
-        }
+	public void introspect(HttpServletRequest request, HttpServletResponse response) {	  
+    	String access_token =  RequestTokenUtils.resolveAccessToken(request);
         _logger.debug("access_token {}" , access_token);
 	    
 		OAuth2Authentication oAuth2Authentication =null;
 		Introspection introspection = new Introspection(access_token);
 		try{
 			 oAuth2Authentication = oauth20tokenServices.loadAuthentication(access_token);
-			 if(oAuth2Authentication != null && clientAuthenticate(headerCredential)) {   
-				 String client_id = oAuth2Authentication.getOAuth2Request().getClientId();
-				 if(headerCredential.getUsername().equals(client_id)) {
-					 String sub = client_id;
-					//if userAuthentication not null , is password or code , else client_credentials
-					 if(oAuth2Authentication.getUserAuthentication() != null) {
-						 sub = ((SignPrincipal)oAuth2Authentication.getUserAuthentication().getPrincipal()).getUsername();
-					 }
+			 if(oAuth2Authentication != null) {   
+				 String sub = "";
+				//userAuthentication not null , is password or code , 
+				 if(oAuth2Authentication.getUserAuthentication() != null) {
+					 sub = ((SignPrincipal)oAuth2Authentication.getUserAuthentication().getPrincipal()).getUsername();
+				 }else {
+					 //client_credentials
+					 sub = oAuth2Authentication.getOAuth2Request().getClientId();
+				 }
+				 if(StringUtils.isNotBlank(sub)) {
 					 introspection.setSub(sub,true);
 				 }
 			 }
@@ -105,7 +94,7 @@ public class IntrospectEndpoint {
     public boolean clientAuthenticate(AuthorizationHeaderCredential headerCredential) {
     	if(headerCredential != null){
 			UsernamePasswordAuthenticationToken authenticationToken = null;
-			if(headerCredential.getCredentialType().equals(AuthorizationHeaderCredential.Credential.BASIC)) {
+			if(headerCredential.isBasic()) {
 			    if(StringUtils.isNotBlank(headerCredential.getUsername())&&
 			    		StringUtils.isNotBlank(headerCredential.getCredential())
 			    		) {

+ 5 - 14
maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/maxkey/authz/oauth2/provider/userinfo/endpoint/UserInfoEndpoint.java

@@ -24,7 +24,6 @@ import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 
 import org.apache.commons.beanutils.BeanUtils;
-import org.apache.commons.lang3.StringUtils;
 import org.maxkey.authn.SignPrincipal;
 import org.maxkey.authz.endpoint.adapter.AbstractAuthorizeAdapter;
 import org.maxkey.authz.oauth2.common.OAuth2Constants;
@@ -38,9 +37,9 @@ import org.maxkey.entity.apps.Apps;
 import org.maxkey.entity.apps.oauth2.provider.ClientDetails;
 import org.maxkey.persistence.service.AppsService;
 import org.maxkey.persistence.service.UserInfoService;
-import org.maxkey.util.AuthorizationHeaderUtils;
 import org.maxkey.util.Instance;
 import org.maxkey.util.JsonUtils;
+import org.maxkey.util.RequestTokenUtils;
 import org.maxkey.util.StringGenerator;
 import org.maxkey.web.HttpResponseAdapter;
 import org.slf4j.Logger;
@@ -50,8 +49,6 @@ import org.springframework.beans.factory.annotation.Qualifier;
 import org.springframework.stereotype.Controller;
 import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.bind.annotation.RequestParam;
-
 import io.swagger.v3.oas.annotations.Operation;
 import io.swagger.v3.oas.annotations.tags.Tag;
 
@@ -78,17 +75,11 @@ public class UserInfoEndpoint {
     @Autowired
     protected HttpResponseAdapter httpResponseAdapter;
 	
-    @Operation(summary = "OAuth 2.0 用户信息接口", description = "传递参数access_token",method="GET")
+    @Operation(summary = "OAuth 2.0 用户信息接口", description = "请求参数access_token , header Authorization , token ",method="GET")
 	@RequestMapping(value=OAuth2Constants.ENDPOINT.ENDPOINT_USERINFO, method={RequestMethod.POST, RequestMethod.GET}) 
-	public void apiV20UserInfo(
-			@RequestParam(value = "access_token", required = false) String access_token,
-            HttpServletRequest request, 
-            HttpServletResponse response) {	        
-	        if(StringUtils.isBlank(access_token)) {
-	        	//for header authorization bearer
-	        	access_token = AuthorizationHeaderUtils.resolveBearer(request);
-	        }
-	        
+	public void apiV20UserInfo(HttpServletRequest request, HttpServletResponse response) {	        
+    		String access_token =  RequestTokenUtils.resolveAccessToken(request);
+    		_logger.debug("access_token {}" , access_token);
 			if (!StringGenerator.uuidMatches(access_token)) {
 				httpResponseAdapter.write(response,JsonUtils.gsonToString(accessTokenFormatError(access_token)),"json"); 
 			}

+ 6 - 6
maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/maxkey/authz/oauth2/provider/userinfo/endpoint/UserInfoOIDCEndpoint.java

@@ -42,8 +42,8 @@ import org.maxkey.entity.UserInfo;
 import org.maxkey.entity.apps.oauth2.provider.ClientDetails;
 import org.maxkey.persistence.service.AppsService;
 import org.maxkey.persistence.service.UserInfoService;
-import org.maxkey.util.AuthorizationHeaderUtils;
 import org.maxkey.util.JsonUtils;
+import org.maxkey.util.RequestTokenUtils;
 import org.maxkey.util.StringGenerator;
 import org.maxkey.web.HttpResponseAdapter;
 import org.maxkey.web.WebConstants;
@@ -97,19 +97,19 @@ public class UserInfoOIDCEndpoint {
     @Autowired
     protected HttpResponseAdapter httpResponseAdapter;
 		
-    @Operation(summary = "OIDC 用户信息接口", description = "传递Authorization参数access_token",method="GET")
+    @Operation(summary = "OIDC 用户信息接口", description = "请求参数access_token , header Authorization , token ",method="GET")
 	@RequestMapping(value=OAuth2Constants.ENDPOINT.ENDPOINT_OPENID_CONNECT_USERINFO, method={RequestMethod.POST, RequestMethod.GET})
 	@ResponseBody
 	public String connect10aUserInfo(HttpServletRequest request, 
 									 HttpServletResponse response) {
-    	String access_token = AuthorizationHeaderUtils.resolveBearer(request);
-		
+    	String access_token =  RequestTokenUtils.resolveAccessToken(request);
+    	_logger.debug("access_token {}" , access_token);
 		if (!StringGenerator.uuidMatches(access_token)) {
 			return JsonUtils.gsonToString(accessTokenFormatError(access_token));
 		}
 		
-		String principal="";
-		OAuth2Authentication oAuth2Authentication =null;
+		String principal = "";
+		OAuth2Authentication oAuth2Authentication = null;
 		try{
 			 oAuth2Authentication = oauth20tokenServices.loadAuthentication(access_token);
 			 

+ 14 - 11
maxkey-webs/maxkey-web-mgt/src/main/java/org/maxkey/web/interceptor/Oauth20ApiPermissionAdapter.java

@@ -26,7 +26,7 @@ import javax.servlet.http.HttpServletResponse;
 import org.maxkey.authz.oauth2.provider.OAuth2Authentication;
 import org.maxkey.authz.oauth2.provider.token.DefaultTokenServices;
 import org.maxkey.crypto.password.PasswordReciprocal;
-import org.maxkey.util.AuthorizationHeaderUtils;
+import org.maxkey.util.RequestTokenUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Autowired;
@@ -57,16 +57,19 @@ public class Oauth20ApiPermissionAdapter  implements AsyncHandlerInterceptor  {
 	 */
 	@Override
 	public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {
-		 _logger.trace("Oauth20ApiPermissionAdapter preHandle");
-		 String accessToken = AuthorizationHeaderUtils.resolveBearer(request);
-		 
-		 OAuth2Authentication authentication = oauth20TokenServices.loadAuthentication(accessToken);
-		 
-		//判断应用的accessToken信息
-		if(authentication != null ){
-		    _logger.trace("authentication "+ authentication);
-		    return true;
-		}
+		 _logger.trace("OAuth20 API Permission Adapter pre handle");
+		 String accessToken =  RequestTokenUtils.resolveAccessToken(request);
+		 _logger.trace("access_token {} " , accessToken);
+		 try {
+			 OAuth2Authentication authentication = oauth20TokenServices.loadAuthentication(accessToken);
+			//判断应用的accessToken信息
+			if(authentication != null ){
+			    _logger.trace("authentication "+ authentication);
+			    return true;
+			}
+		 }catch(Exception e) {
+			 _logger.error("load Authentication Exception ! ",e);
+		 }
 		
 		_logger.trace("No Authentication ... forward to /login");
         RequestDispatcher dispatcher = request.getRequestDispatcher("/login");

+ 5 - 6
maxkey-webs/maxkey-web-mgt/src/main/java/org/maxkey/web/interceptor/RestApiPermissionAdapter.java

@@ -61,14 +61,13 @@ public class RestApiPermissionAdapter  implements AsyncHandlerInterceptor  {
 	 */
 	@Override
 	public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {
-		 _logger.trace("RestApiPermissionAdapter preHandle");
-		String  authorization = request.getHeader(AuthorizationHeaderUtils.HEADER_Authorization);
-		AuthorizationHeaderCredential headerCredential = AuthorizationHeaderUtils.resolve(authorization);
+		_logger.trace("Rest API Permission Adapter pre handle");
+		 AuthorizationHeaderCredential headerCredential = AuthorizationHeaderUtils.resolve(request);
 		 
 		//判断应用的AppId和Secret
 		if(headerCredential != null){
 			UsernamePasswordAuthenticationToken authenticationToken = null;
-			if(headerCredential.getCredentialType().equals(AuthorizationHeaderCredential.Credential.BASIC)) {
+			if(headerCredential.isBasic()) {
 			    if(StringUtils.isNotBlank(headerCredential.getUsername())&&
 			    		StringUtils.isNotBlank(headerCredential.getCredential())
 			    		) {
@@ -79,12 +78,12 @@ public class RestApiPermissionAdapter  implements AsyncHandlerInterceptor  {
 			    	authenticationToken= (UsernamePasswordAuthenticationToken)oauth20ClientAuthenticationManager.authenticate(authRequest);
 			    }
 			}else {
-				_logger.trace("Authentication bearer " + headerCredential.getCredential());
+				_logger.trace("Authentication bearer {}" , headerCredential.getCredential());
 				OAuth2Authentication oauth2Authentication = 
 						oauth20TokenServices.loadAuthentication(headerCredential.getCredential());
 				
 				if(oauth2Authentication != null) {
-					_logger.trace("Authentication token " + oauth2Authentication.getPrincipal().toString());
+					_logger.trace("Authentication token {}" , oauth2Authentication.getPrincipal().toString());
 					authenticationToken= new UsernamePasswordAuthenticationToken(
 			    			new User(
 			    					oauth2Authentication.getPrincipal().toString(),