I have a web service rest in java, in which, I have already restricted access to it, since it generates a JSON with user data, the problem is that I do not know how to do it so that I as admin can access from the browser, from what I have been able to find out, I need to create an "Authorization Header" but I do not know how.
package com.gmail.brunodiazmartin5.rs.ws;
import java.io.IOException;
import java.util.List;
import java.util.StringTokenizer;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.core.Response;
import org.glassfish.jersey.internal.util.Base64;
public class SecuredFilter implements ContainerRequestFilter {
private static final String AUTHORIZATION_HEADER_KEY = "Authorization";
private static final String AUTHORIZATION_HEADER_PREFIX = "Basic";
private static final String SECURED_URL_PREFIX = "secured";
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
if(requestContext.getUriInfo().getPath().contains(SECURED_URL_PREFIX)) {
List<String> authHeader = requestContext.getHeaders().get(AUTHORIZATION_HEADER_KEY);
if (authHeader != null && authHeader.size() > 0){
String authToken = authHeader.get(0);
authToken = authToken.replaceFirst(AUTHORIZATION_HEADER_PREFIX, "");
String decodeString = Base64.decodeAsString(authToken);
StringTokenizer tokenizer = new StringTokenizer(decodeString, ":");
String username = tokenizer.nextToken();
String password = tokenizer.nextToken();
if ("admin".equals(username) && "admin".equals(password)) {
return;
}
Response unauthorizedStatus = Response
.status(Response.Status.UNAUTHORIZED)
.encoding("No puedes acceder a recurso solicitado")
.build();
requestContext.abortWith(unauthorizedStatus);
}
}
}
}
Example class I have to check
package com.gmail.brunodiazmartin5.rs.ws;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
@Path("secured")
public class SecuredService {
@GET
@Path("message")
@Produces(MediaType.TEXT_PLAIN)
public String securedMethod(){
return "Esta API necesita login";
}
}
I can not access this last class, since it sends me a message that I must be logged in, which is what I want, but I do not know how to login.