JAX-RS and custom authorization

一个人想着一个人 提交于 2019-12-03 00:35:41

It all depends upon the JAX-RS implementation you're using. I'm using Jersey on embedded Jetty.

SecurityHandler sh = new SecurityHandler();

// the UserRealm is the collection of users, and a mechanism to determine if
// provided credentials are valid
sh.setUserRealm(new MyUserRealm());

// the Authenticator is a strategy for extracting authentication credentials
// from the request. BasicAuthenticator uses HTTP Basic Auth
sh.setAuthenticator(new BasicAuthenticator());

See How to Configure Security with Embedded Jetty

Once you have the Principal in the HttpServletRequest, you can inject these into the context of the JAX-RS request.

public abstract class AbstractResource {
    private Principal principal;
    @Context
    public void setSecurityContext(SecurityContext context) {
        principal = context.getUserPrincipal();
    }
    protected Principal getPrincipal() {
        return principal;
    }
}

@Path("/some/path")
public class MyResource extends AbstractResource {
    @GET
    public Object get() {
        Principal user = this.getPrincipal();
        // etc
    }
}

Disclaimer: Don't role your own security framework unless you really, really, really, need one.

Look at what the OAuth filter in Jersey does. It reads the Authorization header which holds credentials in a different format than those normally understood (HTTP Basic). It'll turn those credentials into roles which you can then use to implement security (@RolesAllowed) if you add in the Roles Allowed Filter which does the actually enforcement. Try looking at how those filters work.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!