org.restlet.data.ChallengeScheme Java Examples

The following examples show how to use org.restlet.data.ChallengeScheme. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RemoteCarService.java    From microservices-comparison with Apache License 2.0 6 votes vote down vote up
@Override
public List<Car> list() {
    Client client = new Client(new Context(), Protocol.HTTPS);
    Series<Parameter> parameters = client.getContext().getParameters();
    parameters.add("truststorePath", System.getProperty("javax.net.ssl.trustStore"));

    ClientResource clientResource = new ClientResource("https://localhost:8043/api/cars/cars");
    clientResource.setNext(client);
    ChallengeResponse challenge = new ChallengeResponse(ChallengeScheme.HTTP_OAUTH_BEARER);
    challenge.setRawValue(Request.getCurrent().getAttributes().getOrDefault("token", "").toString());
    clientResource.setChallengeResponse(challenge);
    CarServiceInterface carServiceInterface = clientResource.wrap(CarServiceInterface.class);
    Car[] allCars = carServiceInterface.getAllCars();
    try {
        client.stop();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return asList(allCars);
}
 
Example #2
Source File: RootResource.java    From attic-polygene-java with Apache License 2.0 6 votes vote down vote up
@SubResource
public void administration()
{
    ChallengeResponse challenge = Request.getCurrent().getChallengeResponse();
    if( challenge == null )
    {
        Response.getCurrent()
            .setChallengeRequests( Collections.singletonList( new ChallengeRequest( ChallengeScheme.HTTP_BASIC, "Forum" ) ) );
        throw new ResourceException( Status.CLIENT_ERROR_UNAUTHORIZED );
    }

    User user = select( Users.class, Users.USERS_ID ).userNamed( challenge.getIdentifier() );
    if( user == null || !user.isCorrectPassword( new String( challenge.getSecret() ) ) )
    {
        throw new ResourceException( Status.CLIENT_ERROR_UNAUTHORIZED );
    }

    current().select( user );

    subResource( AdministrationResource.class );
}
 
Example #3
Source File: Main.java    From attic-polygene-java with Apache License 2.0 6 votes vote down vote up
public static void main( String[] args )
    throws Exception
{
    Energy4Java polygene = new Energy4Java(  );

    Server server = new Server( Protocol.HTTP, 8888 );

    Application app = polygene.newApplication( new ForumAssembler(), new MetadataService() );

    app.activate();

    ContextRestlet restlet = app.findModule( "REST", "Restlet" ).newObject( ContextRestlet.class, new org.restlet.Context() );

    ChallengeAuthenticator guard = new ChallengeAuthenticator(null, ChallengeScheme.HTTP_BASIC, "testRealm");
    MapVerifier mapVerifier = new MapVerifier();
    mapVerifier.getLocalSecrets().put("rickard", "secret".toCharArray());
    guard.setVerifier(mapVerifier);

    guard.setNext(restlet);

    server.setNext( restlet );
    server.start();
}
 
Example #4
Source File: AbstractRestApplication.java    From FoxBPM with Apache License 2.0 6 votes vote down vote up
public void initializeAuthentication() {
	if(verifier == null){
		verifier = new DefaultSecretVerifier();
	}
	authenticator = new ChallengeAuthenticator(null, false, ChallengeScheme.HTTP_BASIC, "Foxbpm Realm") {
		protected boolean authenticate(Request request, Response response) {
			if (restAuthenticator != null && !restAuthenticator.requestRequiresAuthentication(request)) {
				return true;
			}
			if (request.getChallengeResponse() == null) {
				response.setStatus(Status.CLIENT_ERROR_UNAUTHORIZED);
				return false;
			} else {
				boolean authenticated = super.authenticate(request, response);
				if (authenticated && restAuthenticator != null) {
					authenticated = restAuthenticator.isRequestAuthorized(request);
				}
				return authenticated;
			}
		}
	};
	authenticator.setVerifier(verifier);
}
 
Example #5
Source File: TestGetAllUsers.java    From FoxBPM with Apache License 2.0 6 votes vote down vote up
/**
 * @param args
 */
public static void main(String[] args) {
	ClientResource client = new ClientResource("http://localhost:8889/foxbpm-webapps-base/service/identity/allUsers");
	client.setChallengeResponse(ChallengeScheme.HTTP_BASIC, "111", "111");
	Representation result = client.get();
	try {
		BufferedReader br = new BufferedReader(result.getReader());
		String line = null;
		while ((line = br.readLine()) != null) {
			System.out.println(line);
		}
	} catch (Exception e) {
		e.printStackTrace();
	}
	
}
 
Example #6
Source File: NeighbourhoodManagerConnector.java    From vicinity-gateway-api with GNU General Public License v3.0 5 votes vote down vote up
private ClientResource createRequest(String endpointUrl) {
	ClientResource clientResource = new ClientResource(endpointUrl);
	// Add auth token if security enabled
	if(securityEnabled) {
		String token = secureComms.getToken();
		ChallengeResponse cr = new ChallengeResponse(ChallengeScheme.HTTP_OAUTH_BEARER);
		cr.setRawValue(token);
		clientResource.setChallengeResponse(cr);
	}
	return clientResource;
}
 
Example #7
Source File: Api.java    From vicinity-gateway-api with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Translates the authentication method string from configuration file into RESTLET readable authentication
 * scheme. If the string is not recognised as valid scheme, or if the configuration string says "none", null
 * is returned. 
 * 
 * @return RESTLET challenge scheme.
 */
private void configureChallengeScheme(){
	
	String challengeScheme = config.getString(CONF_PARAM_AUTHMETHOD, CONF_DEF_AUTHMETHOD);
	
	useAuthentication = true;
	
	switch (challengeScheme){
	case "basic":
		logger.config("HTTP Basic challenge authentication scheme configured.");
		this.challengeScheme = ChallengeScheme.HTTP_BASIC;
		break;
		
	case "digest":
		logger.config("HTTP Digest challenge authentication scheme configured.");
		this.challengeScheme = ChallengeScheme.HTTP_DIGEST;
		break;
		
	case "bearer":
		logger.config("HTTP Bearer challenge authentication scheme configured.");
		this.challengeScheme = ChallengeScheme.HTTP_OAUTH_BEARER;
		break;
		
	case "none":
		logger.config("No authentication for API is configured.");
		// this will disable the check for authentication method, otherwise exception is to be expected - that is
		// how the program treats invalid authentication method 
		useAuthentication = false;
		this.challengeScheme = null;
		break;
		
		default:
			logger.warning("Invalid API authentication scheme, reverting to basic.");
			this.challengeScheme = ChallengeScheme.HTTP_BASIC;
	}
}
 
Example #8
Source File: AuthTokenVerifier.java    From microservices-comparison with Apache License 2.0 5 votes vote down vote up
@Override
public int verify(Request request, Response response) {
    final String token;

    try {
        ChallengeResponse cr = request.getChallengeResponse();
        if (cr == null) {
            return RESULT_MISSING;
        } else if (ChallengeScheme.HTTP_OAUTH_BEARER.equals(cr.getScheme())) {
            final String bearer = cr.getRawValue();
            if (bearer == null || bearer.isEmpty()) {
                return RESULT_MISSING;
            }
            token = bearer;
        } else {
            return RESULT_UNSUPPORTED;
        }
    } catch (Exception ex) {
        return RESULT_INVALID;
    }

    Try<User> user = accessTokenVerificationCommandFactory.createVerificationCommand(token).executeCommand();
    return user.map(u -> {
        org.restlet.security.User restletUser = createRestletUser(u);
        request.getClientInfo().setUser(restletUser);
        request.getAttributes().put("token", token);
        return RESULT_VALID;
    }).orElse(RESULT_INVALID);
}
 
Example #9
Source File: RestComponent.java    From microservices-comparison with Apache License 2.0 5 votes vote down vote up
private Restlet secure(Application app, Verifier verifier, String realm) {
    ChallengeAuthenticator guard = new ChallengeAuthenticator(getContext().createChildContext(),
            ChallengeScheme.HTTP_OAUTH_BEARER, realm);
    guard.setVerifier(verifier);
    guard.setNext(app);
    return guard;
}
 
Example #10
Source File: ContextResourceClient.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
private HandlerCommand invokeQuery( Reference ref, Object queryRequest, ResponseHandler resourceHandler, ResponseHandler processingErrorHandler )
{
    Request request = new Request( Method.GET, ref );

    if( queryRequest != null )
    {
        contextResourceFactory.writeRequest( request, queryRequest );
    }

    contextResourceFactory.updateQueryRequest( request );

    User user = request.getClientInfo().getUser();
    if ( user != null)
        request.setChallengeResponse( new ChallengeResponse( ChallengeScheme.HTTP_BASIC, user.getName(), user.getSecret() ) );

    Response response = new Response( request );

    contextResourceFactory.getClient().handle( request, response );

    if( response.getStatus().isSuccess() )
    {
        contextResourceFactory.updateCache( response );

        return resourceHandler.handleResponse( response, this );
    } else if (response.getStatus().isRedirection())
    {
        Reference redirectedTo = response.getLocationRef();
        return invokeQuery( redirectedTo, queryRequest, resourceHandler, processingErrorHandler );
    } else
    {
        if (response.getStatus().equals(Status.CLIENT_ERROR_UNPROCESSABLE_ENTITY) && processingErrorHandler != null)
        {
            return processingErrorHandler.handleResponse( response, this );
        } else
        {
            // TODO This needs to be expanded to allow custom handling of all the various cases
            return errorHandler.handleResponse( response, this );
        }
    }
}
 
Example #11
Source File: PolygeneRestApplication.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
@Override
public Restlet createInboundRoot()
{
    Context context = getContext();
    Engine.getInstance().getRegisteredConverters().add( new PolygeneConverter( objectFactory ) );

    if( polygeneApplication.mode() == Application.Mode.development )
    {
        setDebugging( true );
    }
    router = new Router( context );

    addRoutes( router );
    router.attach( basePath, newPolygeneRestlet( EntryPointResource.class, EntryPoint.class ) );

    Verifier verifier = createVerifier();
    Enroler enroler = createEnroler();
    if( verifier == null && enroler == null )
    {
        return createInterceptors(new Filter()
            {
            } );
    }
    else
    {
        ChallengeAuthenticator guard = new ChallengeAuthenticator( context, ChallengeScheme.HTTP_BASIC, getName() + " Realm" );

        if( verifier != null )
        {
            guard.setVerifier( verifier );
        }

        if( enroler != null )
        {
            guard.setEnroler( enroler );
        }
        return createInterceptors( guard );
    }
}
 
Example #12
Source File: TestBizDataObjectResouce.java    From FoxBPM with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
	ClientResource client = new ClientResource("http://localhost:8889/foxbpm-webapps-base/service/bizDataObjects/dataBaseMode/foxbpmDataSource");
	client.setChallengeResponse(ChallengeScheme.HTTP_BASIC, "111", "111");
	Representation result = client.get();
	try {
		BufferedReader br = new BufferedReader(result.getReader());
		String line = null;
		while ((line = br.readLine()) != null) {
			System.out.println(line);
		}
	} catch (Exception e) {
		e.printStackTrace();
	}
	
}
 
Example #13
Source File: TestDeploy.java    From FoxBPM with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
	ClientResource client = new ClientResource("http://127.0.0.1:8082/model/deployments");
	client.setChallengeResponse(ChallengeScheme.HTTP_BASIC,"111", "111");
	
	InputStream input = TestDeploy.class.getClassLoader().getResourceAsStream("FirstFoxbpm.zip");
	Representation deployInput = new InputRepresentation(input);
	Representation result = client.post(deployInput);
	try {
		result.write(System.out);
	} catch (IOException e) {
		e.printStackTrace();
	}
}
 
Example #14
Source File: RestRequestByRestlet.java    From activiti-in-action-codes with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException {
    ClientResource resource = new ClientResource(REST_URI);

    // 设置Base Auth认证
    resource.setChallengeResponse(ChallengeScheme.HTTP_BASIC, "kermit", "kermit");

    Representation representation = resource.get();
    ObjectMapper mapper = new ObjectMapper();
    JsonNode jsonNode = mapper.readTree(representation.getStream());
    Iterator<String> fieldNames = jsonNode.fieldNames();
    while (fieldNames.hasNext()) {
        String fieldName = fieldNames.next();
        System.out.println(fieldName + " : " + jsonNode.get(fieldName));
    }
}
 
Example #15
Source File: Activator.java    From scava with Eclipse Public License 2.0 4 votes vote down vote up
public void start(BundleContext context) throws Exception {
	
	System.err.println("Starting Admin bundle");
	
	context.addServiceListener(new ServiceListener() {
		
		@Override
		public void serviceChanged(ServiceEvent event) {
			System.err.println(event);
			if (event.getType() == ServiceEvent.REGISTERED){
				Application application = new AdminApplication();

				component = new Component();
				component.getServers().add(Protocol.HTTP, 8183);
				component.getClients().add(Protocol.FILE);

				boolean useAuth = Boolean.valueOf(Configuration.getInstance().getProperty("adminapi.use_authentication", "false"));
				
				if (useAuth) {
					String username = Configuration.getInstance().getProperty("adminapi.username", null);
					String password = Configuration.getInstance().getProperty("adminapi.password", null);
					
					ChallengeAuthenticator guard = new ChallengeAuthenticator(null, ChallengeScheme.HTTP_BASIC, "myRealm");
					MapVerifier verifier = new MapVerifier();
					verifier.getLocalSecrets().put(username, password.toCharArray());
					guard.setVerifier(verifier);
					guard.setNext(application);
					
					component.getDefaultHost().attachDefault(guard);
				} else {
					component.getDefaultHost().attachDefault(application);
				}
				
				try {
					component.start();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}, "(objectclass=" + ApiStartServiceToken.class.getName() +")");
}