JAX-RS and custom authorization

前端 未结 2 716
伪装坚强ぢ
伪装坚强ぢ 2021-02-04 18:41

I\'m trying to secure the JAX-RS endpoint and am currently trying to figure out how the authentication and authorization work. Most examples are quite simple as they only piggyb

2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-04 19:11

    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
        }
    }
    

提交回复
热议问题