modify zuul filter

This commit is contained in:
DOHA 2016-03-01 15:52:47 +02:00
parent 87e391661d
commit bc216b142f
8 changed files with 101 additions and 85 deletions

View File

@ -13,8 +13,7 @@ create table oauth_client_details (
autoapprove VARCHAR(255) autoapprove VARCHAR(255)
); );
drop table if exists oauth_client_token; create table if not exists oauth_client_token (
create table oauth_client_token (
token_id VARCHAR(255), token_id VARCHAR(255),
token LONG VARBINARY, token LONG VARBINARY,
authentication_id VARCHAR(255) PRIMARY KEY, authentication_id VARCHAR(255) PRIMARY KEY,
@ -22,8 +21,7 @@ create table oauth_client_token (
client_id VARCHAR(255) client_id VARCHAR(255)
); );
drop table if exists oauth_access_token; create table if not exists oauth_access_token (
create table oauth_access_token (
token_id VARCHAR(255), token_id VARCHAR(255),
token LONG VARBINARY, token LONG VARBINARY,
authentication_id VARCHAR(255) PRIMARY KEY, authentication_id VARCHAR(255) PRIMARY KEY,
@ -33,20 +31,17 @@ create table oauth_access_token (
refresh_token VARCHAR(255) refresh_token VARCHAR(255)
); );
drop table if exists oauth_refresh_token; create table if not exists oauth_refresh_token (
create table oauth_refresh_token (
token_id VARCHAR(255), token_id VARCHAR(255),
token LONG VARBINARY, token LONG VARBINARY,
authentication LONG VARBINARY authentication LONG VARBINARY
); );
drop table if exists oauth_code; create table if not exists oauth_code (
create table oauth_code (
code VARCHAR(255), authentication LONG VARBINARY code VARCHAR(255), authentication LONG VARBINARY
); );
drop table if exists oauth_approvals; create table if not exists oauth_approvals (
create table oauth_approvals (
userId VARCHAR(255), userId VARCHAR(255),
clientId VARCHAR(255), clientId VARCHAR(255),
scope VARCHAR(255), scope VARCHAR(255),
@ -55,8 +50,7 @@ create table oauth_approvals (
lastModifiedAt TIMESTAMP lastModifiedAt TIMESTAMP
); );
drop table if exists ClientDetails; create table if not exists ClientDetails (
create table ClientDetails (
appId VARCHAR(255) PRIMARY KEY, appId VARCHAR(255) PRIMARY KEY,
resourceIds VARCHAR(255), resourceIds VARCHAR(255),
appSecret VARCHAR(255), appSecret VARCHAR(255),

View File

@ -0,0 +1,28 @@
package org.baeldung.config;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
public class CustomHttpServletRequest extends HttpServletRequestWrapper {
private final Map<String, String[]> additionalParams;
private final HttpServletRequest request;
public CustomHttpServletRequest(final HttpServletRequest request, final Map<String, String[]> additionalParams) {
super(request);
this.request = request;
this.additionalParams = additionalParams;
}
@Override
public Map<String, String[]> getParameterMap() {
final Map<String, String[]> map = request.getParameterMap();
final Map<String, String[]> param = new HashMap<String, String[]>();
param.putAll(map);
param.putAll(additionalParams);
return param;
}
}

View File

@ -18,37 +18,35 @@ import com.netflix.zuul.context.RequestContext;
public class CustomPostZuulFilter extends ZuulFilter { public class CustomPostZuulFilter extends ZuulFilter {
private final Logger logger = LoggerFactory.getLogger(this.getClass()); private final Logger logger = LoggerFactory.getLogger(this.getClass());
private final ObjectMapper mapper = new ObjectMapper();
@Override @Override
public Object run() { public Object run() {
final RequestContext ctx = RequestContext.getCurrentContext(); final RequestContext ctx = RequestContext.getCurrentContext();
logger.info("in zuul filter " + ctx.getRequest().getRequestURI()); logger.info("in zuul filter " + ctx.getRequest().getRequestURI());
if (ctx.getRequest().getRequestURI().contains("oauth/token")) {
final ObjectMapper mapper = new ObjectMapper(); JsonNode json;
JsonNode json; try {
try { final InputStream is = ctx.getResponseDataStream();
final InputStream is = ctx.getResponseDataStream(); final String responseBody = IOUtils.toString(is, "UTF-8");
final String responseBody = IOUtils.toString(is, "UTF-8");
ctx.setResponseBody(responseBody); ctx.setResponseBody(responseBody);
if (responseBody.contains("refresh_token")) { if (responseBody.contains("refresh_token")) {
json = mapper.readTree(responseBody); json = mapper.readTree(responseBody);
final String refreshToken = json.get("refresh_token").getTextValue(); final String refreshToken = json.get("refresh_token").getTextValue();
final Cookie cookie = new Cookie("refreshToken", refreshToken); final Cookie cookie = new Cookie("refreshToken", refreshToken);
cookie.setHttpOnly(true); cookie.setHttpOnly(true);
cookie.setPath(ctx.getRequest().getContextPath() + "/refreshToken"); // cookie.setPath(ctx.getRequest().getContextPath() + "/refreshToken");
cookie.setMaxAge(2592000); // 30 days cookie.setMaxAge(2592000); // 30 days
ctx.getResponse().addCookie(cookie); ctx.getResponse().addCookie(cookie);
logger.info("refresh token = " + refreshToken); logger.info("refresh token = " + refreshToken);
}
} catch (final Exception e) {
logger.error("Error occured in zuul post filter", e);
} }
} catch (final Exception e) {
logger.error("Error occured in zuul post filter", e);
} }
return null; return null;
} }

View File

@ -1,6 +1,11 @@
package org.baeldung.config; package org.baeldung.config;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -19,17 +24,42 @@ public class CustomPreZuulFilter extends ZuulFilter {
public Object run() { public Object run() {
final RequestContext ctx = RequestContext.getCurrentContext(); final RequestContext ctx = RequestContext.getCurrentContext();
logger.info("in zuul filter " + ctx.getRequest().getRequestURI()); logger.info("in zuul filter " + ctx.getRequest().getRequestURI());
if (ctx.getRequest().getRequestURI().contains("oauth/token")) { byte[] encoded;
byte[] encoded; try {
try { encoded = Base64.encode("fooClientIdPassword:secret".getBytes("UTF-8"));
encoded = Base64.encode("fooClientIdPassword:secret".getBytes("UTF-8")); ctx.addZuulRequestHeader("Authorization", "Basic " + new String(encoded));
ctx.addZuulRequestHeader("Authorization", "Basic " + new String(encoded)); logger.info("pre filter");
logger.info("pre filter"); logger.info(ctx.getRequest().getHeader("Authorization"));
logger.info(ctx.getRequest().getHeader("Authorization"));
} catch (final UnsupportedEncodingException e) { //
logger.error("Error occured in pre filter", e); final HttpServletRequest req = ctx.getRequest();
final String refreshToken = extractRefreshToken(req);
if (refreshToken != null) {
final Map<String, String[]> param = new HashMap<String, String[]>();
param.put("refresh_token", new String[] { refreshToken });
param.put("grant_type", new String[] { "refresh_token" });
ctx.setRequest(new CustomHttpServletRequest(req, param));
} }
} catch (final UnsupportedEncodingException e) {
logger.error("Error occured in pre filter", e);
}
//
return null;
}
private String extractRefreshToken(HttpServletRequest req) {
final Cookie[] cookies = req.getCookies();
if (cookies != null) {
for (int i = 0; i < cookies.length; i++) {
if (cookies[i].getName().equalsIgnoreCase("refreshToken")) {
return cookies[i].getValue();
}
}
} }
return null; return null;
} }
@ -41,7 +71,7 @@ public class CustomPreZuulFilter extends ZuulFilter {
@Override @Override
public int filterOrder() { public int filterOrder() {
return 111110; return -2;
} }
@Override @Override

View File

@ -1,20 +0,0 @@
package org.baeldung.config;
import javax.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseStatus;
@Controller
public class HomeController {
@RequestMapping(method = RequestMethod.GET, value = "/refreshToken")
@ResponseStatus(HttpStatus.OK)
public void getRefreshToken(@CookieValue(value = "refreshToken", defaultValue = "") String cookie, HttpServletResponse response) {
response.addHeader("refreshToken", cookie);
}
}

View File

@ -0,0 +1 @@
zuul.Servlet30WrapperFilter.pre.disable=true

View File

@ -2,12 +2,6 @@ server:
port: 8081 port: 8081
zuul: zuul:
routes: routes:
foos:
path: /foos/**
url: http://localhost:8081/spring-security-oauth-resource/foos
bars:
path: /bars/**
url: http://localhost:8081/spring-security-oauth-resource/bars
oauth: oauth:
path: /oauth/** path: /oauth/**
url: http://localhost:8081/spring-security-oauth-server/oauth url: http://localhost:8081/spring-security-oauth-server/oauth

View File

@ -22,14 +22,14 @@ var app = angular.module('myApp', ["ngResource","ngRoute","ngCookies"]);
app.controller('mainCtrl', function($scope,$resource,$http,$httpParamSerializer,$cookies) { app.controller('mainCtrl', function($scope,$resource,$http,$httpParamSerializer,$cookies) {
$scope.foo = {id:0 , name:"sample foo"}; $scope.foo = {id:0 , name:"sample foo"};
$scope.foos = $resource("foos/:fooId",{fooId:'@id'}); $scope.foos = $resource("http://localhost:8081/spring-security-oauth-resource/foos/:fooId",{fooId:'@id'});
$scope.getFoo = function(){ $scope.getFoo = function(){
$scope.foo = $scope.foos.get({fooId:$scope.foo.id}); $scope.foo = $scope.foos.get({fooId:$scope.foo.id});
} }
$scope.loginData = {grant_type:"password", username: "", password: "", client_id: "fooClientIdPassword"}; $scope.loginData = {grant_type:"password", username: "", password: "", client_id: "fooClientIdPassword"};
$scope.refreshData = {grant_type:"refresh_token", refresh_token:""}; $scope.refreshData = {grant_type:"refresh_token"};
var isLoginPage = window.location.href.indexOf("login") != -1; var isLoginPage = window.location.href.indexOf("login") != -1;
if(isLoginPage){ if(isLoginPage){
@ -40,27 +40,17 @@ app.controller('mainCtrl', function($scope,$resource,$http,$httpParamSerializer,
if($cookies.get("access_token")){ if($cookies.get("access_token")){
$http.defaults.headers.common.Authorization= 'Bearer ' + $cookies.get("access_token"); $http.defaults.headers.common.Authorization= 'Bearer ' + $cookies.get("access_token");
}else{ }else{
refreshAccessToken(); obtainAccessToken($scope.refreshData);
} }
} }
$scope.login = function() { $scope.login = function() {
$scope.obtainAccessToken($scope.loginData); obtainAccessToken($scope.loginData);
} }
function refreshAccessToken(){
$http.get("refreshToken").
success(function(data, status, headers, config) {
if(headers("refreshToken") && headers("refreshToken").length>0){
$scope.refreshData.refresh_token = headers("refreshToken");
$scope.obtainAccessToken($scope.refreshData);
}else{
window.location.href = "login";
}
});
}
$scope.obtainAccessToken = function(params){
function obtainAccessToken(params){
var req = { var req = {
method: 'POST', method: 'POST',
url: "oauth/token", url: "oauth/token",
@ -78,6 +68,7 @@ app.controller('mainCtrl', function($scope,$resource,$http,$httpParamSerializer,
window.location.href = "login"; window.location.href = "login";
}); });
} }
}); });
/*]]>*/ /*]]>*/
</script> </script>