스프링 보안 표현식 언어 주석에서 사용할 사용자 지정 메서드를 만드는 방법
주석을 통한 메서드 기반 인증을 위해 스프링 보안 표현 언어로 사용하는 커스텀 메서드를 추가한 클래스를 만들고 싶습니다.
예를 들어 'custom'과 같은 커스텀 메서드를 만들고 싶다.MethodReturningBoolean'은 다음과 같이 사용됩니다.
@PreAuthorize("customMethodReturningBoolean()")
public void myMethodToSecure() {
// whatever
}
제 질문은 이것입니다.가능하다면 커스텀 메서드를 작성하기 위해 어떤 클래스를 서브클래스로 해야 합니까?스프링 XML 컨피규레이션파일로 이 클래스를 구성하는 방법은 무엇입니까?이렇게 사용되는 커스텀 메서드의 예를 제시해 주십시오.
그 어떤 기술도 더 이상 작동하지 않을 것입니다.Spring은 사용자가 보안을 무시하지 않도록 하기 위해 많은 노력을 한 것 같습니다.Expression Root.
11/19/14 보안 주석을 사용하도록 스프링 설정:
<beans ... xmlns:sec="http://www.springframework.org/schema/security" ... >
...
<sec:global-method-security pre-post-annotations="enabled" />
다음과 같은 콩을 만듭니다.
@Component("mySecurityService")
public class MySecurityService {
public boolean hasPermission(String key) {
return true;
}
}
그런 다음 jsp에서 다음과 같은 작업을 수행합니다.
<sec:authorize access="@mySecurityService.hasPermission('special')">
<input type="button" value="Special Button" />
</sec:authorize>
또는 메서드에 주석을 추가합니다.
@PreAuthorize("@mySecurityService.hasPermission('special')")
public void doSpecialStuff() { ... }
또한 Spring Expression Language는@PreAuthorize
현재 인증 및 메서드 인수에 액세스하기 위한 주석입니다.
예를 들어 다음과 같습니다.
@Component("mySecurityService")
public class MySecurityService {
public boolean hasPermission(Authentication authentication, String foo) { ... }
}
그럼 다음 업데이트@PreAuthorize
새로운 메서드의 시그니처에 일치시킵니다.
@PreAuthorize("@mySecurityService.hasPermission(authentication, #foo)")
public void doSpecialStuff(String foo) { ... }
당신은 두 개의 클래스를 세분화해야 할 것이다.
먼저 새 메서드 식 핸들러를 설정합니다.
<global-method-security>
<expression-handler ref="myMethodSecurityExpressionHandler"/>
</global-method-security>
myMethodSecurityExpressionHandler
서브클래스가 되다DefaultMethodSecurityExpressionHandler
우선되는 것은createEvaluationContext()
서브클래스의 설정MethodSecurityExpressionRoot
에서MethodSecurityEvaluationContext
.
예를 들어 다음과 같습니다.
@Override
public EvaluationContext createEvaluationContext(Authentication auth, MethodInvocation mi) {
MethodSecurityEvaluationContext ctx = new MethodSecurityEvaluationContext(auth, mi, parameterNameDiscoverer);
MethodSecurityExpressionRoot root = new MyMethodSecurityExpressionRoot(auth);
root.setTrustResolver(trustResolver);
root.setPermissionEvaluator(permissionEvaluator);
root.setRoleHierarchy(roleHierarchy);
ctx.setRootObject(root);
return ctx;
}
ericacm은 감사합니다만, 다음의 몇 가지 이유로 동작하지 않습니다.
- DefaultMethodSecurity 속성Expression Handler는 비공개입니다(반사 가시성이 바람직하지 않습니다).
- 적어도 Eclipse에서는 Method Security Evaluation Context 개체를 해결할 수 없습니다.
차이점은 기존 createEvaluationContext 메서드를 호출하여 커스텀루트 개체를 추가하는 것입니다.마지막으로 Method Security Evaluation Context가 컴파일러에서 해결되지 않았기 때문에 Standard Evaluation Context 오브젝트 유형을 반환했습니다(둘 다 같은 인터페이스입니다).이것이 현재 생산 중인 코드입니다.
방법 보안 만들기ExpressionHandler는 커스텀루트를 사용합니다.
public class CustomMethodSecurityExpressionHandler extends DefaultMethodSecurityExpressionHandler {
// parent constructor
public CustomMethodSecurityExpressionHandler() {
super();
}
/**
* Custom override to use {@link CustomSecurityExpressionRoot}
*
* Uses a {@link MethodSecurityEvaluationContext} as the <tt>EvaluationContext</tt> implementation and
* configures it with a {@link MethodSecurityExpressionRoot} instance as the expression root object.
*/
@Override
public EvaluationContext createEvaluationContext(Authentication auth, MethodInvocation mi) {
// due to private methods, call original method, then override it's root with ours
StandardEvaluationContext ctx = (StandardEvaluationContext) super.createEvaluationContext(auth, mi);
ctx.setRootObject( new CustomSecurityExpressionRoot(auth) );
return ctx;
}
}
그러면 보안 확장으로 기본 루트가 대체됩니다.Expression Root.여기서는 hasRole을 hasEntitlement로 이름을 바꿨습니다.
public class CustomSecurityExpressionRoot extends SecurityExpressionRoot {
// parent constructor
public CustomSecurityExpressionRoot(Authentication a) {
super(a);
}
/**
* Pass through to hasRole preserving Entitlement method naming convention
* @param expression
* @return boolean
*/
public boolean hasEntitlement(String expression) {
return hasRole(expression);
}
}
마지막으로 securityContext.xml을 업데이트합니다(그리고 applicationContext.xml에서 참조되었는지 확인합니다).
<!-- setup method level security using annotations -->
<security:global-method-security
jsr250-annotations="disabled"
secured-annotations="disabled"
pre-post-annotations="enabled">
<security:expression-handler ref="expressionHandler"/>
</security:global-method-security>
<!--<bean id="expressionHandler" class="org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler">-->
<bean id="expressionHandler" class="com.yourSite.security.CustomMethodSecurityExpressionHandler" />
주의: @Secured 주석은 다른 검증 핸들러를 통해 실행되므로 이 덮어쓰기를 허용하지 않습니다.따라서 위의 xml에서는 나중에 혼란을 방지하기 위해 비활성화했습니다.
언급URL : https://stackoverflow.com/questions/6632982/how-to-create-custom-methods-for-use-in-spring-security-expression-language-anno
'programing' 카테고리의 다른 글
SIGTERM 신호를 정상적으로 처리하는 방법 (0) | 2022.09.23 |
---|---|
__getattr_와 __getattribute_의 차이점 이해 (0) | 2022.09.23 |
팬더 데이터 프레임 열 또는 열에서 목록을 얻으시겠습니까? (0) | 2022.09.23 |
무엇:이 오류-치명적 오류를 일으키고 있다.지역 grunt"를 찾을 수 없습니다. (0) | 2022.09.23 |
어레이 항목을 값별로 제거하는 중 (0) | 2022.09.23 |