【发布时间】:2019-02-20 20:28:07
【问题描述】:
如何创建自己的网络安全表达式,以便我可以在 JSP 文件中使用它,例如:
<sec:authorize access="isOwner()"> some content here </sec:authorize>
【问题讨论】:
标签: java spring-mvc spring-security
如何创建自己的网络安全表达式,以便我可以在 JSP 文件中使用它,例如:
<sec:authorize access="isOwner()"> some content here </sec:authorize>
【问题讨论】:
标签: java spring-mvc spring-security
这是您需要的。 按照以下步骤创建自定义 SpEL 表达式:
1) 创建 WebSecurityExpressionRoot 类的自定义子类。在这个子类中创建一个您将在表达式中使用的新方法。例如:
public class CustomWebSecurityExpressionRoot extends WebSecurityExpressionRoot {
public CustomWebSecurityExpressionRoot(Authentication a, FilterInvocation fi) {
super(a, fi);
}
public boolean yourCustomMethod() {
boolean calculatedValue = ...;
return calculatedValue;
}
}
2) 创建 DefaultWebSecurityExpressionHandler 类的自定义子类并覆盖方法 createSecurityExpressionRoot(Authentication authentication, FilterInvocation fi) (不是 createEvaluationContext(...)) 以返回您的 CustomWebSecurityExpressionRoot 实例。例如:
@Component(value="customExpressionHandler")
public class CustomWebSecurityExpressionHandler extends DefaultWebSecurityExpressionHandler {
@Override
protected SecurityExpressionRoot createSecurityExpressionRoot(
Authentication authentication, FilterInvocation fi) {
WebSecurityExpressionRoot expressionRoot = new CustomWebSecurityExpressionRoot(authentication, fi);
return expressionRoot;
}}
3) 在 spring-security.xml 中定义对表达式处理程序 bean 的引用
<security:http access-denied-page="/error403.jsp" use-expressions="true" auto-config="false">
...
<security:expression-handler ref="customExpressionHandler"/>
</security:http>
在此之后,您可以使用自己的自定义表达式代替标准表达式:
<security:authorize access="yourCustomMethod()">
【讨论】:
http.authorizeRequests().expressionHandler(expressionHandler), 所以现在它可以完美运行了。非常感谢您的帮助!
我建议你使用Shiro 框架。
官方链接:http://shiro.apache.org/
用extends实现AuthorizingRealm,然后在doGetAuthorizationInfo(...)中添加安全控制的表达式。
在JSP中,先添加Shiro JSP标签库,官方链接:http://shiro.apache.org/web.html#Web-taglibrary
使用<shiro:hasPermission name="...">...</shiro:hasPermission>可以控制你需要的东西。 name 属性是将与您在 AuthorizingRealm 中设置的内容进行比较的表达式。
这里是权限表达指南:http://shiro.apache.org/permissions.html
这里有一些用法:
<%@ taglib prefix="shiro" uri=http://shiro.apache.org/tags %>
<html>
<body>
<shiro:hasPermission name="users:manage">
<a href="manageUsers.jsp">
Click here to manage users
</a>
</shiro:hasPermission>
<shiro:lacksPermission name="users:manage">
No user management for you!
</shiro:lacksPermission>
</body>
</html>
【讨论】: