简体   繁体   中英

Secure RESTful web services in Java

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?

You will first need to add a Login filter to intercept the request as described here . In this filter, you can set the security context using this -

RequestContext.setSecurityContext(securityContext);

Remember to intercept the "admin" username from the request and set in the above securityContext .

The user name can be passed using the HTTP Basic Authentication .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM