Merge remote-tracking branch 'upstream/master'

This commit is contained in:
Bill Burke 2013-07-25 07:44:07 -04:00
commit 5f10102c39
27 changed files with 22696 additions and 1 deletions

9
.gitignore vendored
View file

@ -3,6 +3,12 @@
.idea
*.iml
# Eclipse #
###########
.project
.settings
.classpath
# Compiled source #
###################
*.com
@ -29,4 +35,7 @@
######################
*.log
# Maven #
#########
target

21
pom.xml
View file

@ -57,6 +57,7 @@
<module>services</module>
<module>integration</module>
<module>examples</module>
<module>social</module>
</modules>
<dependencyManagement>
@ -177,6 +178,26 @@
<artifactId>hibernate-jpa-2.0-api</artifactId>
<version>1.0.1.Final</version>
</dependency>
<dependency>
<groupId>com.google.api-client</groupId>
<artifactId>google-api-client</artifactId>
<version>1.14.1-beta</version>
</dependency>
<dependency>
<groupId>com.google.http-client</groupId>
<artifactId>google-http-client-jackson</artifactId>
<version>1.14.1-beta</version>
</dependency>
<dependency>
<groupId>com.google.apis</groupId>
<artifactId>google-api-services-oauth2</artifactId>
<version>v2-rev35-1.14.1-beta</version>
</dependency>
<dependency>
<groupId>org.twitter4j</groupId>
<artifactId>twitter4j-core</artifactId>
<version>3.0.3</version>
</dependency>
</dependencies>
</dependencyManagement>

42
sdk-html/pom.xml Executable file
View file

@ -0,0 +1,42 @@
<?xml version="1.0"?>
<project>
<parent>
<artifactId>keycloak-parent</artifactId>
<groupId>org.keycloak</groupId>
<version>1.0-alpha-1</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>keycloak-sdk-html</artifactId>
<name>Keycloak HTML SDK</name>
<description />
<dependencies>
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-social</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>jaxrs-api</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

View file

@ -0,0 +1,9 @@
package org.keycloak.sdk.resources;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
@ApplicationPath("sdk/api")
public class SdkApplication extends Application {
}

View file

@ -0,0 +1,131 @@
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.keycloak.sdk.resources;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import javax.xml.bind.annotation.XmlRootElement;
import org.keycloak.social.util.UriBuilder;
/**
* @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a>
*/
@Path("")
public class SdkResource {
@XmlRootElement
public static class LoginConfig {
private String callbackUrl;
private String id;
private String name;
private String[] providers;
public String getCallbackUrl() {
return callbackUrl;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public String[] getProviders() {
return providers;
}
public void setCallbackUrl(String callbackUrl) {
this.callbackUrl = callbackUrl;
}
public void setId(String id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setProviders(String[] providers) {
this.providers = providers;
}
}
@Context
private HttpHeaders headers;
@Context
private UriInfo uriInfo;
/**
* TODO Retrieve configuration for application from IDM
*/
@GET
@Path("{application}/login/config")
@Produces(MediaType.APPLICATION_JSON)
public LoginConfig getLoginConfig(@PathParam("application") String application) {
LoginConfig loginConfig = new LoginConfig();
loginConfig.setId(application);
loginConfig.setName(application);
loginConfig.setCallbackUrl("http://localhost:8080");
loginConfig.setProviders(new String[] { "google", "twitter" });
return loginConfig;
}
@GET
@Path("{application}/login")
public Response login(@PathParam("application") String application, @QueryParam("error") String error) {
UriBuilder ub = new UriBuilder(headers, uriInfo, "sdk/login.html").setQueryParam("application", application);
if (error != null) {
ub.setQueryParam("error", error);
}
return Response.seeOther(ub.build()).build();
}
@GET
@Path("{application}/register")
public Response register(@PathParam("application") String application, @QueryParam("error") String error) {
UriBuilder ub = new UriBuilder(headers, uriInfo, "sdk/register.html").setQueryParam("application", application);
if (error != null) {
ub.setQueryParam("error", error);
}
return Response.seeOther(ub.build()).build();
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,17 @@
body {
margin: 50px;
}
div#keycloak-login-container,div#keycloak-register-container {
}
div#keycloak-login-standard,div#keycloak-register-standard {
width: 50%;
float: left;
}
div#keycloak-login-social,div#keycloak-register-social {
width: 50%;
float: left;
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.7 KiB

View file

@ -0,0 +1,457 @@
/**
* @license AngularJS v1.0.7
* (c) 2010-2012 Google, Inc. http://angularjs.org
* License: MIT
*/
(function(window, angular, undefined) {
'use strict';
/**
* @ngdoc overview
* @name ngResource
* @description
*/
/**
* @ngdoc object
* @name ngResource.$resource
* @requires $http
*
* @description
* A factory which creates a resource object that lets you interact with
* [RESTful](http://en.wikipedia.org/wiki/Representational_State_Transfer) server-side data sources.
*
* The returned resource object has action methods which provide high-level behaviors without
* the need to interact with the low level {@link ng.$http $http} service.
*
* # Installation
* To use $resource make sure you have included the `angular-resource.js` that comes in Angular
* package. You can also find this file on Google CDN, bower as well as at
* {@link http://code.angularjs.org/ code.angularjs.org}.
*
* Finally load the module in your application:
*
* angular.module('app', ['ngResource']);
*
* and you are ready to get started!
*
* @param {string} url A parameterized URL template with parameters prefixed by `:` as in
* `/user/:username`. If you are using a URL with a port number (e.g.
* `http://example.com:8080/api`), you'll need to escape the colon character before the port
* number, like this: `$resource('http://example.com\\:8080/api')`.
*
* @param {Object=} paramDefaults Default values for `url` parameters. These can be overridden in
* `actions` methods.
*
* Each key value in the parameter object is first bound to url template if present and then any
* excess keys are appended to the url search query after the `?`.
*
* Given a template `/path/:verb` and parameter `{verb:'greet', salutation:'Hello'}` results in
* URL `/path/greet?salutation=Hello`.
*
* If the parameter value is prefixed with `@` then the value of that parameter is extracted from
* the data object (useful for non-GET operations).
*
* @param {Object.<Object>=} actions Hash with declaration of custom action that should extend the
* default set of resource actions. The declaration should be created in the following format:
*
* {action1: {method:?, params:?, isArray:?},
* action2: {method:?, params:?, isArray:?},
* ...}
*
* Where:
*
* - `action` {string} The name of action. This name becomes the name of the method on your
* resource object.
* - `method` {string} HTTP request method. Valid methods are: `GET`, `POST`, `PUT`, `DELETE`,
* and `JSONP`
* - `params` {object=} Optional set of pre-bound parameters for this action.
* - isArray {boolean=} If true then the returned object for this action is an array, see
* `returns` section.
*
* @returns {Object} A resource "class" object with methods for the default set of resource actions
* optionally extended with custom `actions`. The default set contains these actions:
*
* { 'get': {method:'GET'},
* 'save': {method:'POST'},
* 'query': {method:'GET', isArray:true},
* 'remove': {method:'DELETE'},
* 'delete': {method:'DELETE'} };
*
* Calling these methods invoke an {@link ng.$http} with the specified http method,
* destination and parameters. When the data is returned from the server then the object is an
* instance of the resource class. The actions `save`, `remove` and `delete` are available on it
* as methods with the `$` prefix. This allows you to easily perform CRUD operations (create,
* read, update, delete) on server-side data like this:
* <pre>
var User = $resource('/user/:userId', {userId:'@id'});
var user = User.get({userId:123}, function() {
user.abc = true;
user.$save();
});
</pre>
*
* It is important to realize that invoking a $resource object method immediately returns an
* empty reference (object or array depending on `isArray`). Once the data is returned from the
* server the existing reference is populated with the actual data. This is a useful trick since
* usually the resource is assigned to a model which is then rendered by the view. Having an empty
* object results in no rendering, once the data arrives from the server then the object is
* populated with the data and the view automatically re-renders itself showing the new data. This
* means that in most case one never has to write a callback function for the action methods.
*
* The action methods on the class object or instance object can be invoked with the following
* parameters:
*
* - HTTP GET "class" actions: `Resource.action([parameters], [success], [error])`
* - non-GET "class" actions: `Resource.action([parameters], postData, [success], [error])`
* - non-GET instance actions: `instance.$action([parameters], [success], [error])`
*
*
* @example
*
* # Credit card resource
*
* <pre>
// Define CreditCard class
var CreditCard = $resource('/user/:userId/card/:cardId',
{userId:123, cardId:'@id'}, {
charge: {method:'POST', params:{charge:true}}
});
// We can retrieve a collection from the server
var cards = CreditCard.query(function() {
// GET: /user/123/card
// server returns: [ {id:456, number:'1234', name:'Smith'} ];
var card = cards[0];
// each item is an instance of CreditCard
expect(card instanceof CreditCard).toEqual(true);
card.name = "J. Smith";
// non GET methods are mapped onto the instances
card.$save();
// POST: /user/123/card/456 {id:456, number:'1234', name:'J. Smith'}
// server returns: {id:456, number:'1234', name: 'J. Smith'};
// our custom method is mapped as well.
card.$charge({amount:9.99});
// POST: /user/123/card/456?amount=9.99&charge=true {id:456, number:'1234', name:'J. Smith'}
});
// we can create an instance as well
var newCard = new CreditCard({number:'0123'});
newCard.name = "Mike Smith";
newCard.$save();
// POST: /user/123/card {number:'0123', name:'Mike Smith'}
// server returns: {id:789, number:'01234', name: 'Mike Smith'};
expect(newCard.id).toEqual(789);
* </pre>
*
* The object returned from this function execution is a resource "class" which has "static" method
* for each action in the definition.
*
* Calling these methods invoke `$http` on the `url` template with the given `method` and `params`.
* When the data is returned from the server then the object is an instance of the resource type and
* all of the non-GET methods are available with `$` prefix. This allows you to easily support CRUD
* operations (create, read, update, delete) on server-side data.
<pre>
var User = $resource('/user/:userId', {userId:'@id'});
var user = User.get({userId:123}, function() {
user.abc = true;
user.$save();
});
</pre>
*
* It's worth noting that the success callback for `get`, `query` and other method gets passed
* in the response that came from the server as well as $http header getter function, so one
* could rewrite the above example and get access to http headers as:
*
<pre>
var User = $resource('/user/:userId', {userId:'@id'});
User.get({userId:123}, function(u, getResponseHeaders){
u.abc = true;
u.$save(function(u, putResponseHeaders) {
//u => saved user object
//putResponseHeaders => $http header getter
});
});
</pre>
* # Buzz client
Let's look at what a buzz client created with the `$resource` service looks like:
<doc:example>
<doc:source jsfiddle="false">
<script>
function BuzzController($resource) {
this.userId = 'googlebuzz';
this.Activity = $resource(
'https://www.googleapis.com/buzz/v1/activities/:userId/:visibility/:activityId/:comments',
{alt:'json', callback:'JSON_CALLBACK'},
{get:{method:'JSONP', params:{visibility:'@self'}}, replies: {method:'JSONP', params:{visibility:'@self', comments:'@comments'}}}
);
}
BuzzController.prototype = {
fetch: function() {
this.activities = this.Activity.get({userId:this.userId});
},
expandReplies: function(activity) {
activity.replies = this.Activity.replies({userId:this.userId, activityId:activity.id});
}
};
BuzzController.$inject = ['$resource'];
</script>
<div ng-controller="BuzzController">
<input ng-model="userId"/>
<button ng-click="fetch()">fetch</button>
<hr/>
<div ng-repeat="item in activities.data.items">
<h1 style="font-size: 15px;">
<img src="{{item.actor.thumbnailUrl}}" style="max-height:30px;max-width:30px;"/>
<a href="{{item.actor.profileUrl}}">{{item.actor.name}}</a>
<a href ng-click="expandReplies(item)" style="float: right;">Expand replies: {{item.links.replies[0].count}}</a>
</h1>
{{item.object.content | html}}
<div ng-repeat="reply in item.replies.data.items" style="margin-left: 20px;">
<img src="{{reply.actor.thumbnailUrl}}" style="max-height:30px;max-width:30px;"/>
<a href="{{reply.actor.profileUrl}}">{{reply.actor.name}}</a>: {{reply.content | html}}
</div>
</div>
</div>
</doc:source>
<doc:scenario>
</doc:scenario>
</doc:example>
*/
angular.module('ngResource', ['ng']).
factory('$resource', ['$http', '$parse', function($http, $parse) {
var DEFAULT_ACTIONS = {
'get': {method:'GET'},
'save': {method:'POST'},
'query': {method:'GET', isArray:true},
'remove': {method:'DELETE'},
'delete': {method:'DELETE'}
};
var noop = angular.noop,
forEach = angular.forEach,
extend = angular.extend,
copy = angular.copy,
isFunction = angular.isFunction,
getter = function(obj, path) {
return $parse(path)(obj);
};
/**
* We need our custom method because encodeURIComponent is too aggressive and doesn't follow
* http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path
* segments:
* segment = *pchar
* pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
* pct-encoded = "%" HEXDIG HEXDIG
* unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
* sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
* / "*" / "+" / "," / ";" / "="
*/
function encodeUriSegment(val) {
return encodeUriQuery(val, true).
replace(/%26/gi, '&').
replace(/%3D/gi, '=').
replace(/%2B/gi, '+');
}
/**
* This method is intended for encoding *key* or *value* parts of query component. We need a custom
* method becuase encodeURIComponent is too agressive and encodes stuff that doesn't have to be
* encoded per http://tools.ietf.org/html/rfc3986:
* query = *( pchar / "/" / "?" )
* pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
* unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
* pct-encoded = "%" HEXDIG HEXDIG
* sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
* / "*" / "+" / "," / ";" / "="
*/
function encodeUriQuery(val, pctEncodeSpaces) {
return encodeURIComponent(val).
replace(/%40/gi, '@').
replace(/%3A/gi, ':').
replace(/%24/g, '$').
replace(/%2C/gi, ',').
replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
}
function Route(template, defaults) {
this.template = template = template + '#';
this.defaults = defaults || {};
var urlParams = this.urlParams = {};
forEach(template.split(/\W/), function(param){
if (param && (new RegExp("(^|[^\\\\]):" + param + "\\W").test(template))) {
urlParams[param] = true;
}
});
this.template = template.replace(/\\:/g, ':');
}
Route.prototype = {
url: function(params) {
var self = this,
url = this.template,
val,
encodedVal;
params = params || {};
forEach(this.urlParams, function(_, urlParam){
val = params.hasOwnProperty(urlParam) ? params[urlParam] : self.defaults[urlParam];
if (angular.isDefined(val) && val !== null) {
encodedVal = encodeUriSegment(val);
url = url.replace(new RegExp(":" + urlParam + "(\\W)", "g"), encodedVal + "$1");
} else {
url = url.replace(new RegExp("(\/?):" + urlParam + "(\\W)", "g"), function(match,
leadingSlashes, tail) {
if (tail.charAt(0) == '/') {
return tail;
} else {
return leadingSlashes + tail;
}
});
}
});
url = url.replace(/\/?#$/, '');
var query = [];
forEach(params, function(value, key){
if (!self.urlParams[key]) {
query.push(encodeUriQuery(key) + '=' + encodeUriQuery(value));
}
});
query.sort();
url = url.replace(/\/*$/, '');
return url + (query.length ? '?' + query.join('&') : '');
}
};
function ResourceFactory(url, paramDefaults, actions) {
var route = new Route(url);
actions = extend({}, DEFAULT_ACTIONS, actions);
function extractParams(data, actionParams){
var ids = {};
actionParams = extend({}, paramDefaults, actionParams);
forEach(actionParams, function(value, key){
ids[key] = value.charAt && value.charAt(0) == '@' ? getter(data, value.substr(1)) : value;
});
return ids;
}
function Resource(value){
copy(value || {}, this);
}
forEach(actions, function(action, name) {
action.method = angular.uppercase(action.method);
var hasBody = action.method == 'POST' || action.method == 'PUT' || action.method == 'PATCH';
Resource[name] = function(a1, a2, a3, a4) {
var params = {};
var data;
var success = noop;
var error = null;
switch(arguments.length) {
case 4:
error = a4;
success = a3;
//fallthrough
case 3:
case 2:
if (isFunction(a2)) {
if (isFunction(a1)) {
success = a1;
error = a2;
break;
}
success = a2;
error = a3;
//fallthrough
} else {
params = a1;
data = a2;
success = a3;
break;
}
case 1:
if (isFunction(a1)) success = a1;
else if (hasBody) data = a1;
else params = a1;
break;
case 0: break;
default:
throw "Expected between 0-4 arguments [params, data, success, error], got " +
arguments.length + " arguments.";
}
var value = this instanceof Resource ? this : (action.isArray ? [] : new Resource(data));
$http({
method: action.method,
url: route.url(extend({}, extractParams(data, action.params || {}), params)),
data: data
}).then(function(response) {
var data = response.data;
if (data) {
if (action.isArray) {
value.length = 0;
forEach(data, function(item) {
value.push(new Resource(item));
});
} else {
copy(data, value);
}
}
(success||noop)(value, response.headers);
}, error);
return value;
};
Resource.prototype['$' + name] = function(a1, a2, a3) {
var params = extractParams(this),
success = noop,
error;
switch(arguments.length) {
case 3: params = a1; success = a2; error = a3; break;
case 2:
case 1:
if (isFunction(a1)) {
success = a1;
error = a2;
} else {
params = a1;
success = a2 || noop;
}
case 0: break;
default:
throw "Expected between 1-3 arguments [params, success, error], got " +
arguments.length + " arguments.";
}
var data = hasBody ? this : undefined;
Resource[name].call(this, params, data, success, error);
};
});
Resource.bind = function(additionalParamDefaults){
return ResourceFactory(url, extend({}, paramDefaults, additionalParamDefaults), actions);
};
return Resource;
}
return ResourceFactory;
}]);
})(window, window.angular);

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,25 @@
var keycloakModule = angular.module('keycloak', [ 'ngResource' ]);
keycloakModule.factory('messages', function() {
var messages = {};
messages['user_registered'] = "User registered";
messages['invalid_provider'] = "Social provider not found";
messages['provider_error'] = "Failed to login with social provider";
return messages
});
keycloakModule.factory('queryParams', function($location) {
var queryParams = {};
var locationParameters = window.location.search.substring(1).split("&");
for ( var i = 0; i < locationParameters.length; i++) {
var param = locationParameters[i].split("=");
queryParams[decodeURIComponent(param[0])] = decodeURIComponent(param[1]);
}
return queryParams;
});
keycloakModule.controller('GlobalCtrl', function($scope, $resource, queryParams, messages) {
$scope.config = $resource("/keycloak-server/sdk/api/" + queryParams.application + "/login/config").get();
$scope.info = queryParams.info && (messages[queryParams.info] || queryParams.info);
$scope.error = queryParams.error && (messages[queryParams.error] || queryParams.error);
});

View file

@ -0,0 +1,46 @@
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<link href="css/bootstrap.css" rel="stylesheet">
<link href="css/default.css" rel="stylesheet">
<script src="js/angular.js"></script>
<script src="js/angular-resource.js"></script>
<script src="js/app.js"></script>
</head>
<body class=keycloak-login-page data-ng-app=keycloak>
<div id=keycloak-login-container data-ng-controller=GlobalCtrl>
<div id=keycloak-login-standard>
<h1>Login to {{config.name}}</h1>
<div class="alert alert-info" data-ng-show="info">{{info}}</div>
<div class="alert alert-error" data-ng-show="error">{{error}}</div>
<form action="#">
<label for=username>Username</label>
<input id=username type=text data-ng-model=username required />
<label for=password>Password</label>
<input id=password type=text data-ng-model=password required />
<div>
<button class="btn btn-primary" id=keycloak-login-submit type=submit>Login</button>
<a class="btn" href="register.html?application={{config.id}}">Register</a>
<a class="btn" href="{{config.callbackUrl}}">Cancel</a>
</div>
</form>
</div>
<div id=keycloak-login-social>
<h3>Login with</h3>
<div data-ng-repeat="p in config.providers">
<a href="/keycloak-server/social/api/{{config.id}}/auth/{{p}}"><img data-ng-src="icons/{{p}}.png" /></a>
</div>
</div>
</div>
</body>
</html>

View file

@ -0,0 +1,57 @@
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<link href="css/bootstrap.css" rel="stylesheet">
<link href="css/default.css" rel="stylesheet">
<script src="js/angular.js"></script>
<script src="js/angular-resource.js"></script>
<script src="js/app.js"></script>
</head>
<body class=keycloak-login-page data-ng-app=keycloak>
<div id=keycloak-login-container data-ng-controller=GlobalCtrl>
<div id=keycloak-login-standard>
<h1>Register with {{config.name}}</h1>
<div class="alert alert-info" data-ng-show="info">{{info}}</div>
<div class="alert alert-error" data-ng-show="error">{{error}}</div>
<form action="#">
<label for=firstname>Firstname</label>
<input id=firstname type=text data-ng-model=firstname />
<label for=lastname>Lastname</label>
<input id=lastname type=text data-ng-model=lastname />
<label for=email>Email</label>
<input id=email type=email data-ng-model=email />
<label for=username>Username</label>
<input id=username type=text data-ng-model=username />
<label for=password>Password</label>
<input id=password type=text data-ng-model=password required />
<label for=password-confirm>Password confirmation</label>
<input id=password-confirm type=text data-ng-model=passwordConfirm required pattern="{{password}}" title="Passwords don't match" />
<div>
<button class="btn btn-primary" id=keycloak-login-submit type=submit>Register</button>
<a class="btn" href="{{config.callbackUrl}}">Cancel</a>
</div>
</form>
</div>
<div id=keycloak-login-social>
<h3>Login with</h3>
<div data-ng-repeat="p in config.providers">
<a href="/social/{{config.id}}/provider/{{p}}"><img data-ng-src="icons/{{p}}.png" /></a>
</div>
</div>
</div>
</body>
</html>

48
server/pom.xml Executable file
View file

@ -0,0 +1,48 @@
<?xml version="1.0"?>
<project>
<parent>
<artifactId>keycloak-parent</artifactId>
<groupId>org.keycloak</groupId>
<version>1.0-alpha-1</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>keycloak-server</artifactId>
<name>Keycloak Server</name>
<packaging>war</packaging>
<description />
<dependencies>
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-sdk-html</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-social</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>jaxrs-api</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

70
social/pom.xml Executable file
View file

@ -0,0 +1,70 @@
<?xml version="1.0"?>
<project>
<parent>
<artifactId>keycloak-parent</artifactId>
<groupId>org.keycloak</groupId>
<version>1.0-alpha-1</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>keycloak-social</artifactId>
<name>Keycloak Social</name>
<description/>
<dependencies>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jaxrs</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>jaxrs-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.picketlink</groupId>
<artifactId>picketlink-idm-api</artifactId>
</dependency>
<dependency>
<groupId>org.jboss.spec.javax.ejb</groupId>
<artifactId>jboss-ejb-api_3.2_spec</artifactId>
<version>1.0.0.Alpha2</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.google.api-client</groupId>
<artifactId>google-api-client</artifactId>
</dependency>
<dependency>
<groupId>com.google.http-client</groupId>
<artifactId>google-http-client-jackson</artifactId>
</dependency>
<dependency>
<groupId>com.google.apis</groupId>
<artifactId>google-api-services-oauth2</artifactId>
</dependency>
<dependency>
<groupId>org.twitter4j</groupId>
<artifactId>twitter4j-core</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

View file

@ -0,0 +1,50 @@
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.keycloak.social;
import java.net.URI;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import org.picketlink.idm.model.User;
/**
* @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a>
*/
@XmlRootElement
public interface IdentityProvider {
String getId();
@XmlTransient
URI getAuthUrl(IdentityProviderCallback callback) throws IdentityProviderException;
String getName();
@XmlTransient
boolean isCallbackHandler(IdentityProviderCallback callback);
@XmlTransient
User processCallback(IdentityProviderCallback callback) throws IdentityProviderException;
}

View file

@ -0,0 +1,113 @@
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.keycloak.social;
import java.net.URI;
import java.util.List;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.UriInfo;
import org.keycloak.social.util.UriBuilder;
/**
* @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a>
*/
public class IdentityProviderCallback {
private String application;
private HttpHeaders headers;
private String providerKey;
private String providerSecret;
private IdentityProviderState providerState;
private UriInfo uriInfo;
public boolean containsQueryParam(String key) {
return uriInfo.getQueryParameters().containsKey(key);
}
public boolean containsState(String key) {
return providerState.contains(key);
}
public UriBuilder createUri(String path) {
return new UriBuilder(headers, uriInfo, path);
}
public URI getProviderCallbackUrl() {
return createUri("social/" + application + "/callback").build();
}
public String getProviderKey() {
return providerKey;
}
public String getProviderSecret() {
return providerSecret;
}
public String getQueryParam(String key) {
List<String> values = uriInfo.getQueryParameters().get(key);
if (!values.isEmpty()) {
return values.get(0);
}
return null;
}
public <T> T getState(String key) {
return providerState.remove(key);
}
public void putState(String key, Object value) {
providerState.put(key, value);
}
public void setApplication(String application) {
this.application = application;
}
public void setHeaders(HttpHeaders headers) {
this.headers = headers;
}
public void setProviderKey(String providerKey) {
this.providerKey = providerKey;
}
public void setProviderSecret(String providerSecret) {
this.providerSecret = providerSecret;
}
public void setProviderState(IdentityProviderState providerState) {
this.providerState = providerState;
}
public void setUriInfo(UriInfo uriInfo) {
this.uriInfo = uriInfo;
}
}

View file

@ -0,0 +1,6 @@
package org.keycloak.social;
public class IdentityProviderErrors {
public static final String INVALID_PROVIDER = "invalid_provider";
public static final String PROVIDER_ERROR = "provider_error";
}

View file

@ -0,0 +1,11 @@
package org.keycloak.social;
public class IdentityProviderException extends Exception {
private static final long serialVersionUID = 1L;
public IdentityProviderException(Throwable cause) {
super(cause);
}
}

View file

@ -0,0 +1,48 @@
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.keycloak.social;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
* @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a>
*/
public class IdentityProviderState {
private final Map<String, Object> state = Collections.synchronizedMap(new HashMap<String, Object>());
public boolean contains(String key) {
return state.containsKey(key);
}
public void put(String key, Object value) {
state.put(key, value);
}
@SuppressWarnings("unchecked")
public <T> T remove(String key) {
return (T) state.remove(key);
}
}

View file

@ -0,0 +1,114 @@
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.keycloak.social.google;
import java.net.URI;
import java.util.UUID;
import org.keycloak.social.IdentityProvider;
import org.keycloak.social.IdentityProviderCallback;
import org.keycloak.social.IdentityProviderException;
import org.picketlink.idm.model.SimpleUser;
import org.picketlink.idm.model.User;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeTokenRequest;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.api.services.oauth2.Oauth2;
import com.google.api.services.oauth2.model.Tokeninfo;
import com.google.api.services.oauth2.model.Userinfo;
/**
* @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a>
*/
public class GoogleProvider implements IdentityProvider {
private static final JacksonFactory JSON_FACTORY = new JacksonFactory();
private static final NetHttpTransport TRANSPORT = new NetHttpTransport();
@Override
public String getId() {
return "google";
}
@Override
public URI getAuthUrl(IdentityProviderCallback callback) {
String state = UUID.randomUUID().toString();
callback.putState(state, null);
return callback
.createUri("https://accounts.google.com/o/oauth2/auth")
.setQueryParam("client_id", callback.getProviderKey())
.setQueryParam("response_type", "code")
.setQueryParam("scope",
"https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email")
.setQueryParam("redirect_uri", callback.getProviderCallbackUrl().toString()).setQueryParam("state", state)
.build();
}
@Override
public String getName() {
return "Google";
}
@Override
public boolean isCallbackHandler(IdentityProviderCallback callback) {
return callback.containsQueryParam("state") && callback.containsState(callback.getQueryParam("state"));
}
@Override
public User processCallback(IdentityProviderCallback callback) throws IdentityProviderException {
String code = callback.getQueryParam("code");
try {
GoogleTokenResponse tokenResponse = new GoogleAuthorizationCodeTokenRequest(TRANSPORT, JSON_FACTORY,
callback.getProviderKey(), callback.getProviderSecret(), code, callback.getProviderCallbackUrl().toString())
.execute();
GoogleCredential credential = new GoogleCredential.Builder().setJsonFactory(JSON_FACTORY).setTransport(TRANSPORT)
.setClientSecrets(callback.getProviderKey(), callback.getProviderSecret()).build()
.setFromTokenResponse(tokenResponse);
Oauth2 oauth2 = new Oauth2.Builder(TRANSPORT, JSON_FACTORY, credential).build();
Tokeninfo tokenInfo = oauth2.tokeninfo().setAccessToken(credential.getAccessToken()).execute();
if (tokenInfo.containsKey("error")) {
throw new RuntimeException("error");
}
Userinfo userInfo = oauth2.userinfo().get().execute();
User user = new SimpleUser(userInfo.getEmail());
user.setFirstName(userInfo.getGivenName());
user.setLastName(userInfo.getFamilyName());
user.setEmail(userInfo.getEmail());
return user;
} catch (Exception e) {
throw new IdentityProviderException(e);
}
}
}

View file

@ -0,0 +1,9 @@
package org.keycloak.social.resources;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
@ApplicationPath("social/api")
public class SocialApplication extends Application {
}

View file

@ -0,0 +1,221 @@
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.keycloak.social.resources;
import java.io.Serializable;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.imageio.spi.ServiceRegistry;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import org.jboss.resteasy.logging.Logger;
import org.keycloak.social.IdentityProvider;
import org.keycloak.social.IdentityProviderCallback;
import org.keycloak.social.IdentityProviderErrors;
import org.keycloak.social.IdentityProviderException;
import org.keycloak.social.IdentityProviderState;
import org.keycloak.social.util.UriBuilder;
import org.picketlink.idm.model.Attribute;
import org.picketlink.idm.model.User;
/**
* @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a>
*/
@Path("")
public class SocialResource {
private static final Logger log = Logger.getLogger(SocialResource.class);
// TODO This is just temporary - need to either save state variables somewhere they can be flushed after a timeout, or
// alternatively they could be saved in http session, but that is probably not a good idea
private static final Map<String, IdentityProviderState> states = new HashMap<String, IdentityProviderState>();
private static synchronized IdentityProviderState getProviderState(IdentityProvider provider) {
IdentityProviderState s = states.get(provider.getId());
if (s == null) {
s = new IdentityProviderState();
states.put(provider.getId(), s);
}
return s;
}
@Context
private HttpHeaders headers;
@Context
private UriInfo uriInfo;
@GET
@Path("{application}/callback")
public Response callback(@PathParam("application") String application) throws URISyntaxException {
String realm = null; // TODO Get realm for application
IdentityProviderCallback callback = new IdentityProviderCallback();
callback.setApplication(application);
callback.setHeaders(headers);
callback.setUriInfo(uriInfo);
Iterator<IdentityProvider> itr = ServiceRegistry.lookupProviders(IdentityProvider.class);
for (IdentityProvider provider = itr.next(); itr.hasNext();) {
callback.setProviderState(getProviderState(provider));
if (provider.isCallbackHandler(callback)) {
User user = null;
try {
user = provider.processCallback(callback);
} catch (IdentityProviderException e) {
log.warn("Failed to process callback", e);
redirectToLogin(application, IdentityProviderErrors.PROVIDER_ERROR);
}
String providerUsername = user.getLoginName();
String providerUsernameKey = provider.getId() + ".username";
user.setAttribute(new Attribute<String>(providerUsernameKey, user.getLoginName()));
User existingUser = getUser(realm, user.getLoginName());
if (existingUser != null) {
user = mergeUser(user, existingUser);
updateUser(realm, user);
} else {
if (user.getEmail() != null && getUser(realm, user.getEmail()) == null) {
user.setLoginName(user.getEmail());
} else if (getUser(realm, user.getLoginName()) != null) {
for (int i = 0;; i++) {
if (getUser(realm, providerUsername + i) == null) {
user.setLoginName(providerUsername + i);
break;
}
}
}
createUser(realm, user);
}
// TODO Get bearer token etc and redirect to application callback url
URI uri = null;
return Response.seeOther(uri).build();
}
}
return redirectToLogin(application, "login_failed");
}
private void createUser(String realm, User user) {
// TODO Save user in IDM
}
@GET
@Path("providers")
@Produces(MediaType.APPLICATION_JSON)
public List<IdentityProvider> getProviders() {
List<IdentityProvider> providers = new LinkedList<IdentityProvider>();
Iterator<IdentityProvider> itr = ServiceRegistry.lookupProviders(IdentityProvider.class);
while (itr.hasNext()) {
providers.add(itr.next());
}
return providers;
}
private User getUser(String realm, String username) {
// TODO Get user from IDM
return null;
}
private User mergeUser(User source, User destination) {
if (source.getEmail() != null) {
destination.setEmail(source.getEmail());
}
if (source.getFirstName() != null) {
destination.setFirstName(source.getFirstName());
}
if (source.getLastName() != null) {
destination.setLastName(source.getLastName());
}
for (Attribute<? extends Serializable> attribute : source.getAttributes()) {
destination.setAttribute(attribute);
}
return destination;
}
private Response redirectToLogin(String application, String error) {
URI uri = new UriBuilder(headers, uriInfo, "sdk/api/" + application + "/login").setQueryParam("error", error).build();
return Response.seeOther(uri).build();
}
@GET
@Path("{application}/auth/{provider}")
public Response redirectToProviderAuth(@PathParam("application") String application,
@PathParam("provider") String providerId) {
Iterator<IdentityProvider> itr = ServiceRegistry.lookupProviders(IdentityProvider.class);
IdentityProvider provider;
for (provider = itr.next(); itr.hasNext() && !provider.getId().equals(providerId);) {
}
if (provider == null) {
log.warn("Failed to redirect to provider auth: " + providerId + " not found");
return redirectToLogin(application, IdentityProviderErrors.INVALID_PROVIDER);
}
IdentityProviderCallback callback = new IdentityProviderCallback();
callback.setApplication(application);
callback.setHeaders(headers);
callback.setUriInfo(uriInfo);
callback.setProviderKey(null); // TODO Get provider key
callback.setProviderSecret(null); // TODO Get provider secret
callback.setProviderState(getProviderState(provider));
try {
return Response.seeOther(provider.getAuthUrl(callback)).build();
} catch (Throwable t) {
log.warn("Failed to redirect to provider auth", t);
return redirectToLogin(application, IdentityProviderErrors.PROVIDER_ERROR);
}
}
private void updateUser(String realm, User user) {
// TODO Update user in IDM
}
}

View file

@ -0,0 +1,90 @@
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.keycloak.social.twitter;
import java.net.URI;
import org.keycloak.social.IdentityProvider;
import org.keycloak.social.IdentityProviderCallback;
import org.keycloak.social.IdentityProviderException;
import org.picketlink.idm.model.SimpleUser;
import org.picketlink.idm.model.User;
import twitter4j.Twitter;
import twitter4j.TwitterFactory;
import twitter4j.auth.RequestToken;
/**
* @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a>
*/
public class TwitterProvider implements IdentityProvider {
@Override
public String getId() {
return "twitter";
}
@Override
public URI getAuthUrl(IdentityProviderCallback callback) throws IdentityProviderException {
try {
Twitter twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(callback.getProviderKey(), callback.getProviderSecret());
RequestToken requestToken = twitter.getOAuthRequestToken();
callback.putState(requestToken.getToken(), requestToken);
return callback.createUri(requestToken.getAuthenticationURL()).build();
} catch (Exception e) {
throw new IdentityProviderException(e);
}
}
@Override
public String getName() {
return "Twitter";
}
@Override
public boolean isCallbackHandler(IdentityProviderCallback callback) {
return callback.containsQueryParam("oauth_token") && callback.containsState(callback.getQueryParam("oauth_token"));
}
@Override
public User processCallback(IdentityProviderCallback callback) throws IdentityProviderException {
try {
Twitter twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(callback.getProviderKey(), callback.getProviderSecret());
String verifier = callback.getQueryParam("oauth_verifier");
RequestToken requestToken = callback.getState(callback.getQueryParam("oauth_token"));
twitter.getOAuthAccessToken(requestToken, verifier);
twitter4j.User twitterUser = twitter.verifyCredentials();
User user = new SimpleUser(String.valueOf(twitterUser.getScreenName()));
user.setFirstName(twitterUser.getName());
return user;
} catch (Exception e) {
throw new IdentityProviderException(e);
}
}
}

View file

@ -0,0 +1,85 @@
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.keycloak.social.util;
import java.net.URI;
import java.net.URISyntaxException;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.UriInfo;
/**
* @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a>
*/
public class UriBuilder {
private final javax.ws.rs.core.UriBuilder b;
private String fragment;
public UriBuilder(HttpHeaders headers, UriInfo uriInfo, String path) {
if (path.contains("#")) {
String t = path;
path = t.substring(0, t.indexOf('#'));
fragment = t.substring(t.indexOf('#'));
}
if (path.contains("://")) {
b = javax.ws.rs.core.UriBuilder.fromUri(path);
} else {
URI absolutePath = uriInfo.getAbsolutePath();
if (headers.getRequestHeaders().containsKey("x-forwarded-proto")) {
String scheme = headers.getRequestHeaders().get("x-forwarded-proto").get(0);
try {
absolutePath = new URI(absolutePath.toString().replaceFirst(".*://", scheme + "://"));
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
if (path.startsWith("/")) {
b = javax.ws.rs.core.UriBuilder.fromUri(absolutePath.resolve(path));
} else {
URI uri = absolutePath;
String p = uri.getPath();
p = p.substring(0, p.indexOf('/', 1) + 1);
uri = uri.resolve(p + path);
b = javax.ws.rs.core.UriBuilder.fromUri(uri);
}
}
}
public URI build() {
URI uri = b.build();
if (fragment != null) {
uri = uri.resolve(fragment);
}
return uri;
}
public UriBuilder setQueryParam(String name, String value) {
b.replaceQueryParam(name, value);
return this;
}
}

View file

@ -0,0 +1,2 @@
org.keycloak.social.google.GoogleProvider
org.keycloak.social.twitter.TwitterProvider