use of org.restlet.data.ChallengeResponse in project OpenAM by OpenRock.
the class ClientCredentialsReader method extractCredentials.
/**
* Extracts the client's credentials from the OAuth2 request.
*
* @param request The OAuth2 request.
* @param endpoint The endpoint this request should be for, or null to disable audience verification.
* @return The client's credentials.
* @throws InvalidRequestException If the request contains multiple client credentials.
* @throws InvalidClientException If the request does not contain the client's id.
*/
public ClientCredentials extractCredentials(OAuth2Request request, String endpoint) throws InvalidRequestException, InvalidClientException, NotFoundException {
final Request req = request.getRequest();
boolean basicAuth = false;
if (req.getChallengeResponse() != null) {
basicAuth = true;
}
final ClientCredentials client;
Client.TokenEndpointAuthMethod method = CLIENT_SECRET_POST;
//jwt type first
if (JWT_PROFILE_CLIENT_ASSERTION_TYPE.equalsIgnoreCase(request.<String>getParameter(CLIENT_ASSERTION_TYPE))) {
client = verifyJwtBearer(request, basicAuth, endpoint);
method = PRIVATE_KEY_JWT;
} else {
String clientId = request.getParameter(OAuth2Constants.Params.CLIENT_ID);
String clientSecret = request.getParameter(OAuth2Constants.Params.CLIENT_SECRET);
if (basicAuth && clientId != null) {
logger.error("Client (" + clientId + ") using multiple authentication methods");
throw new InvalidRequestException("Client authentication failed");
}
if (req.getChallengeResponse() != null) {
final ChallengeResponse challengeResponse = req.getChallengeResponse();
clientId = challengeResponse.getIdentifier();
clientSecret = "";
if (challengeResponse.getSecret() != null && challengeResponse.getSecret().length > 0) {
clientSecret = String.valueOf(req.getChallengeResponse().getSecret());
}
method = CLIENT_SECRET_BASIC;
}
if (clientId == null || clientId.isEmpty()) {
logger.error("Client Id is not set");
throw failureFactory.getException(request, "Client authentication failed");
}
client = new ClientCredentials(clientId, clientSecret == null ? null : clientSecret.toCharArray(), false, basicAuth);
}
final OpenIdConnectClientRegistration cr = clientRegistrationStore.get(client.getClientId(), request);
final Set<String> scopes = cr.getAllowedScopes();
//if we're accessing the token endpoint, check we're authenticating using the appropriate method
if (scopes.contains(OAuth2Constants.Params.OPENID) && req.getResourceRef().getLastSegment().equals(OAuth2Constants.Params.ACCESS_TOKEN) && !cr.getTokenEndpointAuthMethod().equals(method.getType())) {
throw failureFactory.getException(request, "Invalid authentication method for accessing this endpoint.");
}
return client;
}
use of org.restlet.data.ChallengeResponse in project OpenAM by OpenRock.
the class ConnectClientRegistration method createClient.
/**
* Handles POST requests to the OpenId Connect client registration endpoint for creating OpenId Connect client
* registrations.
*
* @param entity The representation of the client registration details.
* @return The representation of the client registration details as created in the store.
* @throws OAuth2RestletException If an error occurs whilst processing the client registration.
*/
@Post
public Representation createClient(Representation entity) throws OAuth2RestletException {
final OAuth2Request request = requestFactory.create(getRequest());
final ChallengeResponse authHeader = getRequest().getChallengeResponse();
final String accessToken = authHeader != null ? authHeader.getRawValue() : null;
try {
final String deploymentUrl = getRequest().getHostRef().toString() + "/" + getRequest().getResourceRef().getSegments().get(0);
final JsonValue registration = clientRegistrationService.createRegistration(accessToken, deploymentUrl, request);
setStatus(Status.SUCCESS_CREATED);
return jacksonRepresentationFactory.create(registration.asMap());
} catch (OAuth2Exception e) {
throw new OAuth2RestletException(e.getStatusCode(), e.getError(), e.getMessage(), null);
}
}
use of org.restlet.data.ChallengeResponse in project camel by apache.
the class DefaultRestletBinding method populateRestletRequestFromExchange.
public void populateRestletRequestFromExchange(Request request, Exchange exchange) {
request.setReferrerRef("camel-restlet");
final Method method = request.getMethod();
MediaType mediaType = exchange.getIn().getHeader(Exchange.CONTENT_TYPE, MediaType.class);
if (mediaType == null) {
mediaType = MediaType.APPLICATION_WWW_FORM;
}
Form form = null;
// Use forms only for PUT, POST and x-www-form-urlencoded
if ((Method.PUT == method || Method.POST == method) && MediaType.APPLICATION_WWW_FORM.equals(mediaType, true)) {
form = new Form();
if (exchange.getIn().getBody() instanceof Map) {
//Body is key value pairs
try {
Map pairs = exchange.getIn().getBody(Map.class);
for (Object key : pairs.keySet()) {
Object value = pairs.get(key);
form.add(key.toString(), value != null ? value.toString() : null);
}
} catch (Exception e) {
throw new RuntimeCamelException("body for " + MediaType.APPLICATION_WWW_FORM + " request must be Map<String,String> or string format like name=bob&password=secRet", e);
}
} else {
// use string based for forms
String body = exchange.getIn().getBody(String.class);
if (body != null) {
List<NameValuePair> pairs = URLEncodedUtils.parse(body, Charset.forName(IOHelper.getCharsetName(exchange, true)));
for (NameValuePair p : pairs) {
form.add(p.getName(), p.getValue());
}
}
}
}
// get outgoing custom http headers from the exchange if they exists
Series<Header> restletHeaders = exchange.getIn().getHeader(HeaderConstants.ATTRIBUTE_HEADERS, Series.class);
if (restletHeaders == null) {
restletHeaders = new Series<Header>(Header.class);
request.getAttributes().put(HeaderConstants.ATTRIBUTE_HEADERS, restletHeaders);
} else {
// if the restlet headers already exists on the exchange, we need to filter them
for (String name : restletHeaders.getNames()) {
if (headerFilterStrategy.applyFilterToCamelHeaders(name, restletHeaders.getValues(name), exchange)) {
restletHeaders.removeAll(name);
}
}
request.getAttributes().put(HeaderConstants.ATTRIBUTE_HEADERS, restletHeaders);
// since the restlet headers already exists remove them from the exchange so they don't get added again below
// we will get a new set of restlet headers on the response
exchange.getIn().removeHeader(HeaderConstants.ATTRIBUTE_HEADERS);
}
// login and password are filtered by header filter strategy
String login = exchange.getIn().getHeader(RestletConstants.RESTLET_LOGIN, String.class);
String password = exchange.getIn().getHeader(RestletConstants.RESTLET_PASSWORD, String.class);
if (login != null && password != null) {
ChallengeResponse authentication = new ChallengeResponse(ChallengeScheme.HTTP_BASIC, login, password);
request.setChallengeResponse(authentication);
LOG.debug("Basic HTTP Authentication has been applied");
}
for (Map.Entry<String, Object> entry : exchange.getIn().getHeaders().entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
if (!headerFilterStrategy.applyFilterToCamelHeaders(key, value, exchange)) {
// Use forms only for PUT, POST and x-www-form-urlencoded
if (form != null) {
if (key.startsWith("org.restlet.")) {
// put the org.restlet headers in attributes
request.getAttributes().put(key, value);
} else {
// put the user stuff in the form
if (value instanceof Collection) {
for (Object v : (Collection<?>) value) {
form.add(key, v.toString());
if (!headerFilterStrategy.applyFilterToCamelHeaders(key, value, exchange)) {
restletHeaders.set(key, value.toString());
}
}
} else {
//Add headers to headers and to body
form.add(key, value.toString());
if (!headerFilterStrategy.applyFilterToCamelHeaders(key, value, exchange)) {
restletHeaders.set(key, value.toString());
}
}
}
} else {
// For non-form post put all the headers in custom headers
if (!headerFilterStrategy.applyFilterToCamelHeaders(key, value, exchange)) {
restletHeaders.set(key, value.toString());
}
}
LOG.debug("Populate Restlet request from exchange header: {} value: {}", key, value);
}
}
if (form != null) {
request.setEntity(form.getWebRepresentation());
LOG.debug("Populate Restlet {} request from exchange body as form using media type {}", method, mediaType);
} else {
// include body if PUT or POST
if (request.getMethod() == Method.PUT || request.getMethod() == Method.POST) {
Representation body = createRepresentationFromBody(exchange, mediaType);
request.setEntity(body);
LOG.debug("Populate Restlet {} request from exchange body: {} using media type {}", method, body, mediaType);
} else {
// no body
LOG.debug("Populate Restlet {} request from exchange using media type {}", method, mediaType);
request.setEntity(new EmptyRepresentation());
}
}
// accept
String accept = exchange.getIn().getHeader("Accept", String.class);
final ClientInfo clientInfo = request.getClientInfo();
final List<Preference<MediaType>> acceptedMediaTypesList = clientInfo.getAcceptedMediaTypes();
if (accept != null) {
final MediaType[] acceptedMediaTypes = exchange.getContext().getTypeConverter().tryConvertTo(MediaType[].class, exchange, accept);
for (final MediaType acceptedMediaType : acceptedMediaTypes) {
acceptedMediaTypesList.add(new Preference<MediaType>(acceptedMediaType));
}
}
final MediaType[] acceptedMediaTypes = exchange.getIn().getHeader(Exchange.ACCEPT_CONTENT_TYPE, MediaType[].class);
if (acceptedMediaTypes != null) {
for (final MediaType acceptedMediaType : acceptedMediaTypes) {
acceptedMediaTypesList.add(new Preference<MediaType>(acceptedMediaType));
}
}
}
use of org.restlet.data.ChallengeResponse in project vcell by virtualcell.
the class VCellCookieAuthenticator method login.
@Override
protected void login(Request request, Response response) {
// Login detected
Representation entity = request.getEntity();
Form form = new Form(entity);
Parameter identifier = form.getFirst(getIdentifierFormName());
Parameter secret = form.getFirst(getSecretFormName());
Parameter redirectURL = form.getFirst(getRedirectQueryName());
UserLoginInfo.DigestedPassword digestedPassword = new UserLoginInfo.DigestedPassword(secret.getValue());
try {
User user = vcellApiApplication.getUserVerifier().authenticateUser(identifier.getValue(), digestedPassword.getString().toCharArray());
if (user == null) {
response.setStatus(Status.CLIENT_ERROR_UNAUTHORIZED);
return;
}
ApiClient apiClient = vcellApiApplication.getUserVerifier().getApiClient(VCellApiApplication.BROWSER_CLIENTID);
ApiAccessToken accessToken = vcellApiApplication.getUserVerifier().generateApiAccessToken(apiClient.getKey(), user);
// Set credentials
ChallengeResponse cr = new ChallengeResponse(getScheme(), CustomAuthHelper.ACCESS_TOKEN, accessToken.getToken());
request.setChallengeResponse(cr);
getCredentialsCookie(request, response).setMaxAge(0);
getLogger().log(Level.INFO, "MyCookieAuthenticator.login(request,response) - created new accessToken '" + accessToken.getToken() + "' and assignd to ChallengeResponse, redirectURL='" + redirectURL.getValue() + "'");
response.redirectSeeOther(Reference.decode(redirectURL.getValue()));
} catch (SQLException e) {
e.printStackTrace();
getLogger().log(Level.SEVERE, "MyCookieAuthenticator.login(request,response) - exception", e);
} catch (DataAccessException e) {
e.printStackTrace();
getLogger().log(Level.SEVERE, "MyCookieAuthenticator.login(request,response) - exception", e);
}
}
use of org.restlet.data.ChallengeResponse in project vcell by virtualcell.
the class Client method main.
/**
* @param args
*/
public static void main(String[] args) {
try {
// ClientResource resource = new ClientResource("http://restlet.org");
//
// // Customize the referrer property
// resource.setReferrerRef("http://www.mysite.org");
//
// // Write the response entity on the console
// resource.get().write(System.out);
// Prepare the request
ClientResource resource = new ClientResource("http://localhost:8182/");
// Add the client authentication to the call
ChallengeScheme scheme = ChallengeScheme.HTTP_BASIC;
ChallengeResponse authentication = new ChallengeResponse(scheme, "scott", "tiger");
resource.setChallengeResponse(authentication);
// Send the HTTP GET request
resource.get();
if (resource.getStatus().isSuccess()) {
// Output the response entity on the JVM console
resource.getResponseEntity().write(System.out);
} else if (resource.getStatus().equals(Status.CLIENT_ERROR_UNAUTHORIZED)) {
// Unauthorized access
System.out.println("Access authorized by the server, check your credentials");
} else {
// Unexpected status
System.out.println("An unexpected status was returned: " + resource.getStatus());
}
} catch (Throwable e) {
e.printStackTrace(System.out);
}
}
Aggregations