Glassfish 3.1.1: Retrieve HTTP-Authentication in RESTful Webservice

大憨熊 提交于 2019-12-10 19:39:58

问题


I´m using HTTP-Authentication based on my customer-table. After the user is authenticated a restful webservice is called. But how can I access in the webservice the HTTP-Authentication (the Header Data of the HttpRequest)? My code looks like this:

@GET
@Path("{id}") 
@Produces({"application/xml"})
public ObjectList read(@PathParam("id") Integer id) {
... //how to get here the HTTP-Username and Password?
}

回答1:


In order to get the Principal and its role, inject @Context SecurityContext in the class body or in the method input parameters.

import javax.ws.rs.core;
//
public ObjectList read(
    @PathParam("id") Integer id,
    @Context SecurityContext sc) {
    String principalUserName = sc.getUserPrincipal().getName();
    if (sc.isUserInRole("MyRole")) {
        return new MyRoleResource();
    } else {
        return new MyDefaultRoleResource();
    }
}



回答2:


Add more parameters to your method like this:

import javax.ws.rs.HeaderParam;

// ...

public ObjectList read(
    @PathParam("id") Integer id,
    @HeaderParam("user-agent") String userAgent,
    @HeaderParam("X-auth-token") String authToken) ...


来源:https://stackoverflow.com/questions/9005124/glassfish-3-1-1-retrieve-http-authentication-in-restful-webservice

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