簡體   English   中英

Java Restful Web Services(jax rs)身份驗證模式

[英]Java Restful Web Services (jax rs) authentication pattern

我已經開始使用JAX-RS為我的Web應用程序創建一個簡單的restful接口。 目前,它只被一個內部客戶端使用(只讀),該客戶端可以訪問所有應用程序數據,我使用http基本身份驗證進行訪問。 我想開始使用它作為我的應用程序的視圖層的一部分,並且只有當用戶通過Web應用程序登錄時才允許某些操作。 我正在努力尋找一種模式,允許我以優雅的方式使用兩種形式的身份驗證,而無需重復大量代碼。 這大致是我提出的:

首先是一個用於加載應用程序會話的util類,它存儲在數據庫中。

public class RestUtil {
    public static AppSession getAuthenticatedSession(HttpServletRequest request) {
        AppSession session;
        String remoteUser = request.getRemoteUser();
        if (remoteUser != null) {
            session = SessionRepository.loadSessionByRemoteUser(remoteUser);
        } else {
            session = SessionRepository.loadSessionById(request.getSession().getId());
        }
        return session;
    }
}

這是我們的資源,只有一個方法只能由經過身份驗證的用戶訪問,或者我們的http基本身份驗證客戶端:

@Path("/protected/resource")
public class ProtectedResource {
    @GET
    @Produces(MediaType.TEXT_JSON)
    @Path("{userId}")
    public String getProtectedResourceJson(@Context HttpServletRequest request, @PathParam("userId") Integer userId) {
        // Return Charity List XML
        AppSession session = RestUtil.getAuthenticatedSession(request);

        if (session.canAccessUser(userId))  //get Json...
    }
}

對於這個問題,這是AppSession的最基本視圖:

public class AppSession {
    User authenticatedUser;
    String remoteUser;

    public boolean canAccessUser(Integer userId) {
        if (remoteUser != null) {
            //this client has access to all users
            return true;
        } else if (authenticatedUser.getId().equals(userId)) {
            //this is local client, calling the service from a view
            //only has access to authenticatedUser
            return true;
        } else {
            return false;
        }
    }
}

此外,對於不需要任何身份驗證的服務,如何防止未經授權的第三方指向網址,並在閑暇時抓取數據?

當你值得研究使用面向方面的編程來從業務邏輯中分離安全方面時,你就會發現這一點。 如果您已經使用Spring來組裝應用程序的部分(我建議用於復雜的服務器),那么只需添加Spring AOP來注入安全邏輯。 否則,直接使用AspectJ。 處理多種登錄模式的實際邏輯可能必須是自定義的,但至少可以保持隔離狀態。

如果使用Spring,請考慮使用Spring Security; 它構建於Spring AOP之上,為您提供更多解決方案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM