0

I want to secure RESTful web services. Here is my code:

UserService.java

@Path("/UserService")
public class UserService
{
    @GET
    @Produces("text/plain;charset=UTF-8")
    @Path("/hello")
    public String sayHello(@Context SecurityContext sc) {
        if (sc.isUserInRole("admin"))  
            return "Hello World!";
        throw new SecurityException("User is unauthorized.");
    }
}

web.xml

<display-name>RestfulWebService</display-name>
<servlet>
    <servlet-name>Jersey RESTful Application</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
    <init-param>
        <param-name>jersey.config.server.provider.packages</param-name>
        <param-value>com.tutorialspoint</param-value>
    </init-param>
</servlet>
<servlet-mapping>
    <servlet-name>Jersey RESTful Application</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping>

When I try this link

http://localhost:8080/RestfulWebService/UserService/hello

It always gives me an unauthorized exception. So how can I make the code return hello world and make it authorized?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
la2 la2
  • 21
  • 1
  • 5
  • Look at http://www.developerscrappad.com/1814/java/java-ee/rest-jax-rs/java-ee-7-jax-rs-2-0-simple-rest-api-authentication-authorization-with-custom-http-header/ and http://stackoverflow.com/questions/23670885/containerrequestfilter-containerresponsefilter-dosent-get-called – djna Jul 13 '16 at 08:35
  • Can you give more information about the users retrieval and how you authenticate a request? If you didn't configure anything else, I guess the response will always be 401 as you will always throw the SecurityException (by the way, you should not throw java.lang.SecurityException yourself, but maybe it's a custom type)... – cdelmas Jul 13 '16 at 08:37
  • were you able to resolve this @la2 la2 ? – Sampada Aug 02 '16 at 10:43

0 Answers0