簡體   English   中英

使用Spring Security記錄請求

[英]Log requests with Spring Security

如何通過Spring Security將請求記錄到Spring REST服務? (在一些例子中為我指出)

正確設置並運行Spring Security后,您可以通過獲取SecurityContext並從其中獲取UserDetails來訪問當前登錄用戶的憑據(或至少是用戶名):

final Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

String username = null;

if (principal instanceof UserDetails) {
    username = ((UserDetails) principal).getUsername();
} else {
    username = principal.toString();
}

log.debug("User: " + username + " has accessed the service");

我們在其中一個應用程序中做到了這一點。 這是一個Spring MVC程序,但這沒什么大不了的。

但是,我不會真正將用戶名登錄到某個文件中。 您可能會嘗試建立某種協議數據庫,並記錄更多信息(“ X在YY時以Z方式訪問MYSERVICE”或其他方式)

web.xml

<filter>
    <filter-name>securityFilter</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    <init-param>
        <param-name>targetFilterLifecycle</param-name>
        <param-value>true</param-value>
    </init-param>
</filter>

<filter-mapping>
    <filter-name>securityFilter</filter-name>
    <url-pattern>/*</url-pattern>
    <url-pattern>//</url-pattern>
</filter-mapping>

spring-config.xml

...

<bean class="com.examlple.MyLogFilter" id="logFilter"/>

...

<bean class="org.springframework.security.web.FilterChainProxy" id="securityFilter">
    <sec:filter-chain-map path-type="ant">
          <sec:filter-chain filters="logFilter,otherfilter1,otherfilter2" pattern="/myRESTservicePath/**"/>

....

MyLogFilter是一個簡單的Servlet過濾器實現

暫無
暫無

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

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