【问题标题】:Spring MVC controller inheritance with spring securitySpring MVC 控制器继承与 Spring Security
【发布时间】:2013-07-17 06:56:15
【问题描述】:

我正在尝试使用 spring mvc 3.2.3 和 spring security 3.1.3 创建一个通用控制器。 我想要实现的是这样的:

public abstract class DataController<E extends PersistentEntity> {
protected abstract E getEntity(String id);

@RequestMapping(value="/view/{id}", method=RequestMethod.GET)
public String view(@PathVariable("id") String id, ModelMap map) {
      E ent = getEntity(id);
      map.put("entity", entity);
      return "showEntity";
    }
}

我的扩展类将在类名中有一个特定的控制器映射,以便我可以使用控制器名访问 url:

@Controller
@RequestMapping("/company**")
@Secured("ROLE_ADMIN")
public class CompaniesController extends DataController<Company> {
    @Autowired
    private AppService appService;

    @Override
    protected Company getEntity(String id) {
        return appService.getCompany(id);
    }
}

我的问题是 URL /company/view 不受 ROLE_ADMIN 保护,任何人都可以访问,(我认为)因为 /view 未在使用 @Secured 的控制器中定义。

这可以通过覆盖视图方法并在我的公司类中定义映射来解决:

    . . .

    @Override
    @RequestMapping(value = "/view/{id}", method = RequestMethod.GET)
    public String view(String id, ModelMap map) {
        return super.view(id, map);
    }

    . . .

在这种情况下,安全工作正常,但我想知道是否有其他方法。由于我的抽象类中有很多方法,这将产生一个问题和混乱来覆盖所有方法只是为了调用超级。

有没有办法解决这个问题?

感谢大家的帮助:)

【问题讨论】:

    标签: java spring-mvc spring-security


    【解决方案1】:

    我知道已经过了一年,但我遇到了同样的问题,并想出了一个可能的解决方案。它不是 100% 基于注释的,但可以工作并且有点优雅

    抽象超类:

    @PreAuthorize("hasAnyRole(this.roles)")
    public abstract class DataController<E extends PersistentEntity> 
    {
        protected abstract E getEntity(String id);
    
        protected abstract String[] getRoles();
    
        @RequestMapping(value="/view/{id}", method=RequestMethod.GET)
        public String view(@PathVariable("id") String id, ModelMap map) {
           E ent = getEntity(id);
           map.put("entity", entity);
           return "showEntity";
        }
     }
    

    在子类上,您只需实现 getRoles() 以返回访问此类所需的角色数组。

    @PreAuthorize 是另一种检查身份验证的方法,它允许您使用 SpEL 表达式。 this.roles 指的是注解对象上的getRoles() 属性。

    【讨论】:

    • 如果我有不同的方法和不同的角色权限怎么办?在这里,您具有控制器访问权限。我需要在方法级别拥有权限。
    • 您应该能够在方法级别上放置类似的注释。您可能需要为不同的方法定义不同的来源。上面我有getRoles() 方法。您可能需要getRolesFunction1()getRolesFunction2() 等方法。然后用@PreAuthorize("hasAnyRole(this.rolesFunction1)") 等注释你的方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-13
    • 1970-01-01
    • 2018-01-02
    • 2014-02-04
    • 2013-04-29
    相关资源
    最近更新 更多