PreAuthorize注释中的Java 8 / Spring常量

时间:2017-01-27 10:04:47

标签: java spring spring-boot

在我的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中还有更优雅的方法吗?

3 个答案:

答案 0 :(得分:4)

感谢oli37我已按以下方式实施此逻辑:

class FavoriteClientsController < ApplicationController

  def create
    @client = Client.find(params[:client_id] || params[:id])

    if Favorite.create(favorited: @client, user: current_user)
      redirect_to @client, notice: 'Leverandøren er tilføjet til favoritter'
    else
      redirect_to @client, alert: 'Noget gik galt...*sad panda*'
    end
  end

  def destroy
    @client = Client.find(params[:client_id] || params[:id])

    Favorite.where(favorited_id: @client.id, user_id: current_user.id).first.destroy
    redirect_to @client, notice: 'Leverandøren er nu fjernet fra favoritter'
  end

end

答案 1 :(得分:2)

这里是在单个位置定义权限的简单方法,不需要任何深入的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);

    }
}

答案 2 :(得分:0)

我认为最好的方法是不要将两者混合

你可以有常量

public static final String ROLE_ADMIN = "auth_app_admin";

还有另一面

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

这个很清楚