簡體   English   中英

PreAuthorize 注釋中的 Java 8/Spring 常量

[英]Java 8/Spring constants in PreAuthorize annotation

在我的 Spring Boot 項目中,我定義了以下 RestController 方法:

@PreAuthorize("hasAuthority('" + Permission.APPEND_DECISION + "')")
@RequestMapping(value = "/{decisionId}/decisions", method = RequestMethod.PUT)
public DecisionResponse appendDecisionToParent(@PathVariable @NotNull @DecimalMin("0") Long decisionId, @Valid @RequestBody AppendDecisionRequest decisionRequest) {
    ....
    return new DecisionResponse(decision);
}

現在為了提供允許的權限名稱,我使用以下代碼結構:

@PreAuthorize("hasAuthority('" + Permission.APPEND_DECISION + "')")

其中Permission.APPEND_DECISION是一個常量:

public static final String APPEND_DECISION = "APPEND_DECISION";

Java/Spring 中是否有更優雅的方式來定義這種代碼?

這是在單個位置定義權限的簡單方法,不需要任何深入的 Spring Security 配置。

public class Authority {
    public class Plan{
        public static final String MANAGE = "hasAuthority('PLAN_MANAGE')";
        public static final String APPROVE = "hasAuthority('PLAN_APPROVE')";
        public static final String VIEW = "hasAuthority('PLAN_VIEW')";
    }
}

保障服務...

public interface PlanApprovalService {

    @PreAuthorize(Authority.Plan.APPROVE)
        ApprovalInfo approvePlan(Long planId);

    }
}

感謝oli37,我通過以下方式實現了這個邏輯:

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true, jsr250Enabled = true)
public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {

    private DefaultMethodSecurityExpressionHandler defaultMethodExpressionHandler = new DefaultMethodSecurityExpressionHandler();

    @Override
    protected MethodSecurityExpressionHandler createExpressionHandler() {
        return defaultMethodExpressionHandler;
    }

    public class DefaultMethodSecurityExpressionHandler extends org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler {

        @Override
        public StandardEvaluationContext createEvaluationContextInternal(final Authentication auth, final MethodInvocation mi) {
            StandardEvaluationContext standardEvaluationContext = super.createEvaluationContextInternal(auth, mi);
            ((StandardTypeLocator) standardEvaluationContext.getTypeLocator()).registerImport(Permission.class.getPackage().getName());
            return standardEvaluationContext;
        }
    }

}


    @PreAuthorize("hasAuthority(T(Permission).APPEND_DECISION)")
    @RequestMapping(value = "/{decisionId}/decisions", method = RequestMethod.PUT)
    public DecisionResponse appendDecisionToParent(@PathVariable @NotNull @DecimalMin("0") Long decisionId, @Valid @RequestBody AppendDecisionRequest decisionRequest) {
    ...
        return new DecisionResponse(decision);
    }

我的好方法是不要將兩者混合

你可以有常數

public static final String ROLE_ADMIN = "auth_app_admin";

並有另一面

@PreAuthorize("hasRole(\"" + Constants.ROLE_ADMIN + "\")")

這很清楚

暫無
暫無

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

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