oauth refresh token

This commit is contained in:
DOHA 2016-02-27 20:37:56 +02:00
parent 11461268fe
commit f8b8a5d7bb
10 changed files with 216 additions and 43 deletions

View File

@ -23,6 +23,12 @@
<artifactId>spring-boot-starter-thymeleaf</artifactId> <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zuul</artifactId>
<version>1.0.4.RELEASE</version>
</dependency>
<!-- test --> <!-- test -->

View File

@ -0,0 +1,70 @@
package org.baeldung.config;
import java.io.InputStream;
import javax.servlet.http.Cookie;
import org.apache.commons.io.IOUtils;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
@Component
public class CustomPostZuulFilter extends ZuulFilter {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Override
public Object run() {
final RequestContext ctx = RequestContext.getCurrentContext();
logger.info("in zuul filter " + ctx.getRequest().getRequestURI());
if (ctx.getRequest().getRequestURI().contains("oauth/token")) {
final ObjectMapper mapper = new ObjectMapper();
JsonNode json;
try {
final InputStream is = ctx.getResponseDataStream();
final String responseBody = IOUtils.toString(is, "UTF-8");
ctx.setResponseBody(responseBody);
if (responseBody.contains("refresh_token")) {
json = mapper.readTree(responseBody);
final String refreshToken = json.get("refresh_token").getTextValue();
final Cookie cookie = new Cookie("refreshToken", refreshToken);
cookie.setHttpOnly(true);
cookie.setPath(ctx.getRequest().getContextPath() + "/refreshToken");
cookie.setMaxAge(2592000); // 30 days
ctx.getResponse().addCookie(cookie);
logger.info("refresh token = " + refreshToken);
}
} catch (final Exception e) {
logger.error("Error occured in zuul post filter", e);
}
}
return null;
}
@Override
public boolean shouldFilter() {
return true;
}
@Override
public int filterOrder() {
return 10;
}
@Override
public String filterType() {
return "post";
}
}

View File

@ -0,0 +1,52 @@
package org.baeldung.config;
import java.io.UnsupportedEncodingException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.crypto.codec.Base64;
import org.springframework.stereotype.Component;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
@Component
public class CustomPreZuulFilter extends ZuulFilter {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Override
public Object run() {
final RequestContext ctx = RequestContext.getCurrentContext();
logger.info("in zuul filter " + ctx.getRequest().getRequestURI());
if (ctx.getRequest().getRequestURI().contains("oauth/token")) {
byte[] encoded;
try {
encoded = Base64.encode("fooClientIdPassword:secret".getBytes("UTF-8"));
ctx.addZuulRequestHeader("Authorization", "Basic " + new String(encoded));
logger.info("pre filter");
logger.info(ctx.getRequest().getHeader("Authorization"));
} catch (final UnsupportedEncodingException e) {
logger.error("Error occured in pre filter", e);
}
}
return null;
}
@Override
public boolean shouldFilter() {
return true;
}
@Override
public int filterOrder() {
return 111110;
}
@Override
public String filterType() {
return "pre";
}
}

View File

@ -0,0 +1,20 @@
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

@ -3,7 +3,9 @@ package org.baeldung.config;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.web.SpringBootServletInitializer; import org.springframework.boot.context.web.SpringBootServletInitializer;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
@EnableZuulProxy
@SpringBootApplication @SpringBootApplication
public class UiApplication extends SpringBootServletInitializer { public class UiApplication extends SpringBootServletInitializer {

View File

@ -1,2 +0,0 @@
server.contextPath=/spring-security-oauth-ui-password
server.port=8081

View File

@ -0,0 +1,13 @@
server:
port: 8081
zuul:
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:
path: /oauth/**
url: http://localhost:8081/spring-security-oauth-server/oauth

View File

@ -21,52 +21,63 @@
var app = angular.module('myApp', ["ngResource","ngRoute","ngCookies"]); 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("http://localhost:8081/spring-security-oauth-resource/foos/:fooId",{fooId:'@id'}); $scope.foos = $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.data = {grant_type:"password", username: "", password: "", client_id: "fooClientIdPassword"}; $scope.loginData = {grant_type:"password", username: "", password: "", client_id: "fooClientIdPassword"};
$scope.encoded = btoa("fooClientIdPassword:secret"); $scope.refreshData = {grant_type:"refresh_token", refresh_token:""};
var isLoginPage = window.location.href.indexOf("login") != -1; var isLoginPage = window.location.href.indexOf("login") != -1;
if(isLoginPage){ if(isLoginPage){
if($cookies.get("access_token")){ if($cookies.get("access_token")){
window.location.href = "index"; window.location.href = "index";
}else{
$http.defaults.headers.common.Authorization= 'Basic ' + $scope.encoded;
} }
}else{ }else{
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{
window.location.href = "login"; refreshAccessToken();
} }
} }
$scope.login = function() { $scope.login = function() {
var req = { $scope.obtainAccessToken($scope.loginData);
method: 'POST',
url: "http://localhost:8081/spring-security-oauth-server/oauth/token",
headers: {
"Authorization": "Basic " + $scope.encoded,
"Content-type": "application/x-www-form-urlencoded; charset=utf-8"
},
data: $httpParamSerializer($scope.data)
}
$http(req).then(
function(data){
$http.defaults.headers.common.Authorization= 'Bearer ' + data.data.access_token;
$cookies.put("access_token", data.data.access_token);
window.location.href="index";
},function(){
console.log("error");
});
} }
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){
var req = {
method: 'POST',
url: "oauth/token",
headers: {"Content-type": "application/x-www-form-urlencoded; charset=utf-8"},
data: $httpParamSerializer(params)
}
$http(req).then(
function(data){
$http.defaults.headers.common.Authorization= 'Bearer ' + data.data.access_token;
var expireDate = new Date (new Date().getTime() + (1000 * data.data.expires_in));
$cookies.put("access_token", data.data.access_token, {'expires': expireDate});
window.location.href="index";
},function(){
console.log("error");
window.location.href = "login";
});
}
}); });
/*]]>*/ /*]]>*/
</script> </script>

View File

@ -15,16 +15,17 @@
<div class="col-sm-6"> <div class="col-sm-6">
<div class="col-sm-12"> <div class="col-sm-12">
<label class="col-sm-3">Username</label> <label class="col-sm-3">Username</label>
<input class="form-control" type="text" ng-model="data.username"/> <input class="form-control" type="text" ng-model="loginData.username"/>
</div> </div>
<div class="col-sm-12"> <div class="col-sm-12">
<label class="col-sm-3">Password</label> <label class="col-sm-3">Password</label>
<input class="form-control" type="password" ng-model="data.password"/> <input class="form-control" type="password" ng-model="loginData.password"/>
</div> </div>
<div class="col-sm-12"> <div class="col-sm-12">
<a class="btn btn-default" href="#" ng-click="login()">Login</a> <a class="btn btn-default" href="#" ng-click="login()">Login</a>
</div> </div>
</div> </div>

View File

@ -20,11 +20,6 @@
<arguments> <arguments>
</arguments> </arguments>
</buildCommand> </buildCommand>
<buildCommand>
<name>org.eclipse.m2e.core.maven2Builder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand> <buildCommand>
<name>org.springframework.ide.eclipse.core.springbuilder</name> <name>org.springframework.ide.eclipse.core.springbuilder</name>
<arguments> <arguments>
@ -35,6 +30,11 @@
<arguments> <arguments>
</arguments> </arguments>
</buildCommand> </buildCommand>
<buildCommand>
<name>org.eclipse.m2e.core.maven2Builder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec> </buildSpec>
<natures> <natures>
<nature>org.eclipse.jem.workbench.JavaEMFNature</nature> <nature>org.eclipse.jem.workbench.JavaEMFNature</nature>