Skip to content

Commit f8b8a5d

Browse files
committed
oauth refresh token
1 parent 1146126 commit f8b8a5d

10 files changed

Lines changed: 214 additions & 41 deletions

File tree

‎spring-security-oauth/spring-security-oauth-ui-password/pom.xml‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,11 +17,17 @@
1717
<groupId>org.springframework.boot</groupId>
1818
<artifactId>spring-boot-starter-web</artifactId>
1919
</dependency>
20-
20+
2121
<dependency>
2222
<groupId>org.springframework.boot</groupId>
2323
<artifactId>spring-boot-starter-thymeleaf</artifactId>
2424
</dependency>
25+
26+
<dependency>
27+
<groupId>org.springframework.cloud</groupId>
28+
<artifactId>spring-cloud-starter-zuul</artifactId>
29+
<version>1.0.4.RELEASE</version>
30+
</dependency>
2531

2632

2733
<!-- test -->
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
package org.baeldung.config;
2+
3+
import java.io.InputStream;
4+
5+
import javax.servlet.http.Cookie;
6+
7+
import org.apache.commons.io.IOUtils;
8+
import org.codehaus.jackson.JsonNode;
9+
import org.codehaus.jackson.map.ObjectMapper;
10+
import org.slf4j.Logger;
11+
import org.slf4j.LoggerFactory;
12+
import org.springframework.stereotype.Component;
13+
14+
import com.netflix.zuul.ZuulFilter;
15+
import com.netflix.zuul.context.RequestContext;
16+
17+
@Component
18+
public class CustomPostZuulFilter extends ZuulFilter {
19+
20+
private final Logger logger = LoggerFactory.getLogger(this.getClass());
21+
22+
@Override
23+
public Object run() {
24+
final RequestContext ctx = RequestContext.getCurrentContext();
25+
logger.info("in zuul filter " + ctx.getRequest().getRequestURI());
26+
if (ctx.getRequest().getRequestURI().contains("oauth/token")) {
27+
28+
final ObjectMapper mapper = new ObjectMapper();
29+
JsonNode json;
30+
try {
31+
final InputStream is = ctx.getResponseDataStream();
32+
final String responseBody = IOUtils.toString(is, "UTF-8");
33+
34+
ctx.setResponseBody(responseBody);
35+
36+
if (responseBody.contains("refresh_token")) {
37+
json = mapper.readTree(responseBody);
38+
final String refreshToken = json.get("refresh_token").getTextValue();
39+
final Cookie cookie = new Cookie("refreshToken", refreshToken);
40+
cookie.setHttpOnly(true);
41+
cookie.setPath(ctx.getRequest().getContextPath() + "/refreshToken");
42+
cookie.setMaxAge(2592000); // 30 days
43+
ctx.getResponse().addCookie(cookie);
44+
45+
logger.info("refresh token = " + refreshToken);
46+
}
47+
} catch (final Exception e) {
48+
logger.error("Error occured in zuul post filter", e);
49+
}
50+
51+
}
52+
return null;
53+
}
54+
55+
@Override
56+
public boolean shouldFilter() {
57+
return true;
58+
}
59+
60+
@Override
61+
public int filterOrder() {
62+
return 10;
63+
}
64+
65+
@Override
66+
public String filterType() {
67+
return "post";
68+
}
69+
70+
}
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
package org.baeldung.config;
2+
3+
import java.io.UnsupportedEncodingException;
4+
5+
import org.slf4j.Logger;
6+
import org.slf4j.LoggerFactory;
7+
import org.springframework.security.crypto.codec.Base64;
8+
import org.springframework.stereotype.Component;
9+
10+
import com.netflix.zuul.ZuulFilter;
11+
import com.netflix.zuul.context.RequestContext;
12+
13+
@Component
14+
public class CustomPreZuulFilter extends ZuulFilter {
15+
16+
private final Logger logger = LoggerFactory.getLogger(this.getClass());
17+
18+
@Override
19+
public Object run() {
20+
final RequestContext ctx = RequestContext.getCurrentContext();
21+
logger.info("in zuul filter " + ctx.getRequest().getRequestURI());
22+
if (ctx.getRequest().getRequestURI().contains("oauth/token")) {
23+
byte[] encoded;
24+
try {
25+
encoded = Base64.encode("fooClientIdPassword:secret".getBytes("UTF-8"));
26+
ctx.addZuulRequestHeader("Authorization", "Basic " + new String(encoded));
27+
logger.info("pre filter");
28+
logger.info(ctx.getRequest().getHeader("Authorization"));
29+
} catch (final UnsupportedEncodingException e) {
30+
logger.error("Error occured in pre filter", e);
31+
}
32+
33+
}
34+
return null;
35+
}
36+
37+
@Override
38+
public boolean shouldFilter() {
39+
return true;
40+
}
41+
42+
@Override
43+
public int filterOrder() {
44+
return 111110;
45+
}
46+
47+
@Override
48+
public String filterType() {
49+
return "pre";
50+
}
51+
52+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package org.baeldung.config;
2+
3+
import javax.servlet.http.HttpServletResponse;
4+
5+
import org.springframework.http.HttpStatus;
6+
import org.springframework.stereotype.Controller;
7+
import org.springframework.web.bind.annotation.CookieValue;
8+
import org.springframework.web.bind.annotation.RequestMapping;
9+
import org.springframework.web.bind.annotation.RequestMethod;
10+
import org.springframework.web.bind.annotation.ResponseStatus;
11+
12+
@Controller
13+
public class HomeController {
14+
15+
@RequestMapping(method = RequestMethod.GET, value = "/refreshToken")
16+
@ResponseStatus(HttpStatus.OK)
17+
public void getRefreshToken(@CookieValue(value = "refreshToken", defaultValue = "") String cookie, HttpServletResponse response) {
18+
response.addHeader("refreshToken", cookie);
19+
}
20+
}

‎spring-security-oauth/spring-security-oauth-ui-password/src/main/java/org/baeldung/config/UiApplication.java‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,9 @@
33
import org.springframework.boot.SpringApplication;
44
import org.springframework.boot.autoconfigure.SpringBootApplication;
55
import org.springframework.boot.context.web.SpringBootServletInitializer;
6+
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
67

8+
@EnableZuulProxy
79
@SpringBootApplication
810
public class UiApplication extends SpringBootServletInitializer {
911

‎spring-security-oauth/spring-security-oauth-ui-password/src/main/resources/application.properties‎

Lines changed: 0 additions & 2 deletions
This file was deleted.
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
server:
2+
port: 8081
3+
zuul:
4+
routes:
5+
foos:
6+
path: /foos/**
7+
url: http://localhost:8081/spring-security-oauth-resource/foos
8+
bars:
9+
path: /bars/**
10+
url: http://localhost:8081/spring-security-oauth-resource/bars
11+
oauth:
12+
path: /oauth/**
13+
url: http://localhost:8081/spring-security-oauth-server/oauth

‎spring-security-oauth/spring-security-oauth-ui-password/src/main/resources/templates/header.html‎

Lines changed: 44 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -21,52 +21,63 @@
2121
var app = angular.module('myApp', ["ngResource","ngRoute","ngCookies"]);
2222

2323
app.controller('mainCtrl', function($scope,$resource,$http,$httpParamSerializer,$cookies) {
24-
$scope.foo = {id:0 , name:"sample foo"};
25-
$scope.foos = $resource("http://localhost:8081/spring-security-oauth-resource/foos/:fooId",{fooId:'@id'});
24+
$scope.foo = {id:0 , name:"sample foo"};
25+
$scope.foos = $resource("foos/:fooId",{fooId:'@id'});
2626

27-
$scope.getFoo = function(){
28-
$scope.foo = $scope.foos.get({fooId:$scope.foo.id});
29-
}
30-
31-
$scope.data = {grant_type:"password", username: "", password: "", client_id: "fooClientIdPassword"};
32-
$scope.encoded = btoa("fooClientIdPassword:secret");
27+
$scope.getFoo = function(){
28+
$scope.foo = $scope.foos.get({fooId:$scope.foo.id});
29+
}
3330

31+
$scope.loginData = {grant_type:"password", username: "", password: "", client_id: "fooClientIdPassword"};
32+
$scope.refreshData = {grant_type:"refresh_token", refresh_token:""};
33+
3434
var isLoginPage = window.location.href.indexOf("login") != -1;
3535
if(isLoginPage){
36-
if($cookies.get("access_token")){
36+
if($cookies.get("access_token")){
3737
window.location.href = "index";
38-
}else{
39-
$http.defaults.headers.common.Authorization= 'Basic ' + $scope.encoded;
4038
}
4139
}else{
42-
if($cookies.get("access_token")){
43-
$http.defaults.headers.common.Authorization= 'Bearer ' + $cookies.get("access_token");
44-
}else{
45-
window.location.href = "login";
46-
}
47-
40+
if($cookies.get("access_token")){
41+
$http.defaults.headers.common.Authorization= 'Bearer ' + $cookies.get("access_token");
42+
}else{
43+
refreshAccessToken();
44+
}
4845
}
4946

5047
$scope.login = function() {
51-
var req = {
48+
$scope.obtainAccessToken($scope.loginData);
49+
}
50+
51+
function refreshAccessToken(){
52+
$http.get("refreshToken").
53+
success(function(data, status, headers, config) {
54+
if(headers("refreshToken") && headers("refreshToken").length>0){
55+
$scope.refreshData.refresh_token = headers("refreshToken");
56+
$scope.obtainAccessToken($scope.refreshData);
57+
}else{
58+
window.location.href = "login";
59+
}
60+
});
61+
}
62+
63+
$scope.obtainAccessToken = function(params){
64+
var req = {
5265
method: 'POST',
53-
url: "http://localhost:8081/spring-security-oauth-server/oauth/token",
54-
headers: {
55-
"Authorization": "Basic " + $scope.encoded,
56-
"Content-type": "application/x-www-form-urlencoded; charset=utf-8"
57-
},
58-
data: $httpParamSerializer($scope.data)
66+
url: "oauth/token",
67+
headers: {"Content-type": "application/x-www-form-urlencoded; charset=utf-8"},
68+
data: $httpParamSerializer(params)
5969
}
6070
$http(req).then(
61-
function(data){
62-
$http.defaults.headers.common.Authorization= 'Bearer ' + data.data.access_token;
63-
$cookies.put("access_token", data.data.access_token);
64-
window.location.href="index";
65-
},function(){
66-
console.log("error");
67-
});
68-
}
69-
71+
function(data){
72+
$http.defaults.headers.common.Authorization= 'Bearer ' + data.data.access_token;
73+
var expireDate = new Date (new Date().getTime() + (1000 * data.data.expires_in));
74+
$cookies.put("access_token", data.data.access_token, {'expires': expireDate});
75+
window.location.href="index";
76+
},function(){
77+
console.log("error");
78+
window.location.href = "login";
79+
});
80+
}
7081
});
7182
/*]]>*/
7283
</script>

‎spring-security-oauth/spring-security-oauth-ui-password/src/main/resources/templates/login.html‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,16 +15,17 @@ <h1 class="col-sm-12">Login</h1>
1515
<div class="col-sm-6">
1616
<div class="col-sm-12">
1717
<label class="col-sm-3">Username</label>
18-
<input class="form-control" type="text" ng-model="data.username"/>
18+
<input class="form-control" type="text" ng-model="loginData.username"/>
1919
</div>
2020

2121
<div class="col-sm-12">
2222
<label class="col-sm-3">Password</label>
23-
<input class="form-control" type="password" ng-model="data.password"/>
23+
<input class="form-control" type="password" ng-model="loginData.password"/>
2424
</div>
2525

2626
<div class="col-sm-12">
2727
<a class="btn btn-default" href="#" ng-click="login()">Login</a>
28+
2829
</div>
2930

3031
</div>

‎spring-zuul/spring-zuul-ui/.project‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,17 +21,17 @@
2121
</arguments>
2222
</buildCommand>
2323
<buildCommand>
24-
<name>org.eclipse.m2e.core.maven2Builder</name>
24+
<name>org.springframework.ide.eclipse.core.springbuilder</name>
2525
<arguments>
2626
</arguments>
2727
</buildCommand>
2828
<buildCommand>
29-
<name>org.springframework.ide.eclipse.core.springbuilder</name>
29+
<name>org.eclipse.wst.validation.validationbuilder</name>
3030
<arguments>
3131
</arguments>
3232
</buildCommand>
3333
<buildCommand>
34-
<name>org.eclipse.wst.validation.validationbuilder</name>
34+
<name>org.eclipse.m2e.core.maven2Builder</name>
3535
<arguments>
3636
</arguments>
3737
</buildCommand>

0 commit comments

Comments
 (0)