[英]Programmatically assigning security role to user on login in JSF website
我已將web.xml
設置為拒絕訪問我站點中的某些頁面,並將用戶重定向到登錄頁面(如果尚未登錄)。並且我定義了一個簡單地稱為USER
的角色,它看起來像這樣:
<security-constraint>
<web-resource-collection>
<web-resource-name>mis</web-resource-name>
<url-pattern>/secure/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>USER</role-name>
</auth-constraint>
</security-constraint>
<login-config>
<auth-method>FORM</auth-method>
<realm-name>file</realm-name>
<form-login-config>
<form-login-page>/signin.xhtml</form-login-page>
<form-error-page>/error.xhtml</form-error-page>
</form-login-config>
</login-config>
<security-role>
<role-name>USER</role-name>
</security-role>
在我的signing.xhtml
頁面中,我想手動檢查用戶的憑據(我們使用反向代理注入的標頭來處理實際的安全性),然后根據特定條件將用戶分配給特定角色。
有沒有辦法以編程方式分配當前用戶和該用戶具有的角色? 還是我必須使用JBOSS / Glassfish用戶設置?
似乎最好的方法不是使用security-constraints
,而是使用filter
選項。 首先創建一個實現javax.servlet.Filter
的類,並實現doFilter
方法:
public class UserRoleFilter implements Filter {
@Override
public void init(FilterConfig cfg) throws ServletException {
}
@Override
public void doFilter(ServletRequest req, ServletResponse response, FilterChain next) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
//Manually check that the current user can access pages
//I did that by storing stuff in the session which you can access by
//request.getSession().getAttribute(someKey);
if(!userHasAccessToRestrictedPages) {
HttpServletResponse r = (HttpServletResponse) response;
r.sendRedirect(request.getContextPath() + "/signin.xhtml");
return;
}
next.doFilter(req, response);
}
@Override
public void destroy() {
}
}
然后在web.xml
文件中刪除security-constraints
, login-config
和security-role
並替換為(其中filter-class
指上述類):
<filter>
<filter-name>UserRoleFilter</filter-name>
<filter-class>security.UserRoleFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>UserRoleFilter</filter-name>
<url-pattern>/secure/*</url-pattern>
</filter-mapping>
那應該做。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.