[英]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.