Example For Restlet Auth
1. Create a Restlet Server
package server;
import org.restlet.Application;
import org.restlet.Component;
import org.restlet.data.Protocol;
public class TestServer extends Application {
public static void main(String[] args) throws Exception {
Component component = new Component();
component.getServers().add(Protocol.HTTP, 8182);
component.getDefaultHost().attach("/trace", Part3.class);
component.start();
}
}
2. Create a Restlet Resource
package server;
import org.restlet.Request;
import org.restlet.data.MediaType;
import org.restlet.representation.Representation;
import org.restlet.representation.StringRepresentation;
import org.restlet.resource.Get;
import org.restlet.resource.ServerResource;
public class RestletResource extends ServerResource {
@Get
public Representation doPost(Representation entity) {
Request request = getRequest();
Check check = new Check();
String result = check.authCheck(request);
if(result.equals("success")){
return new StringRepresentation("Success : ", MediaType.TEXT_PLAIN);
}
else{
return new StringRepresentation("Fail : ", MediaType.TEXT_PLAIN);
}
}
}
3. Create a Auth Check method
import org.restlet.Request;
import org.restlet.data.ChallengeResponse;
public class Check {
public String authCheck(Request request) {
String result;
ChallengeResponse challengeResponse = request.getChallengeResponse();
if (challengeResponse == null) {
throw new RuntimeException("not authenticated");
}
String userName = challengeResponse.getIdentifier();
System.out.println("Identifier :" + userName);
String password = new String(challengeResponse.getSecret());
System.out.println("Secret" + password);
/*
* Here you can check the username and password. I am considering 'Dev' and 'Dev123'
*/
if (userName.equals("dev") && password.equals("Dev123")) {
result = "success";
} else {
result = "fail";
}
return result;
}
}
4. Restlet Client
import org.restlet.data.ChallengeScheme;
import org.restlet.resource.ClientResource;
import org.restlet.resource.ResourceException;
public class TestClient {
public static void main(String[] args) throws Exception {
ClientResource resource = new ClientResource("http://localhost:8182/trace");
resource.setChallengeResponse(ChallengeScheme.HTTP_BASIC, "dev", "Dev123");
// Send the first request with unsufficient authentication.
try {
System.out.println(resource.get(String.class));
} catch (ResourceException re) {
re.printStackTrace();
}
}
}
No comments:
Post a Comment