Getting started with MVC(7)

本文详细介绍了MVC框架内置的CSRF防护机制,包括如何配置防护选项、使用注解确保请求验证以及在视图中插入隐藏字段来传递CSRF令牌。此外还介绍了如何通过MVC上下文获取应用路径等信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

MVC Security

MVC has built-in some security features to protect pages, eg. CSRF protection.

CSRF protection

MVC has built-in CSRF protection, there is aCsrfinterface.

  1. ConfigureCsrfin theApplicationclass. Override thegetPropertiesmethod.

    @Override
    public Map<String, Object> getProperties() {
        Map<String, Object> props = new HashMap<>();
    
        props.put(Csrf.CSRF_PROTECTION, Csrf.CsrfOptions.EXPLICIT);
    
        //view folder
        //props.put(ViewEngine.DEFAULT_VIEW_FOLDER, ViewEngine.VIEW_FOLDER);
        return super.getProperties();
    }

    And there are some options to configure CSRF viaCsrf.CsrfOptions.

    • OFF to disable Csrf.
    • EXPLICIT to enable Csrf wtih annotation@CsrfValidon the Controller method.
    • IMPLICIT to enable Csrf autmaticially. No need@CsrfValid.
  2. Add annotation@CsrfValidon the Controller method.

    @POST
    @CsrfValid
    @ValidateOnExecution(type = ExecutableType.NONE)
    public Response save(@Valid @BeanParam TaskForm form) {
    }
  3. In the view, add hidden field to insert the Csrf value.

    <input type="hidden" name="${mvc.csrf.name}" value="${mvc.csrf.token}"/>

When you run the codes on Glassfish, in the view, the Csrf field looks like:

<input value="f3ca389f-efba-4f28-afe7-2a1e7231a238" name="X-Requested-By" type="hidden" />

Every request will generate a unique X-Requested-By value.

When the form is submitted, and it will be validated by MVC provider.

MvcContext

MvcContextinterface includes the contextual data of MVC, such as context path, application path, etc. And also includes MVC security, such asCsrfandEncoders.

In the above section, we have usedCsrf.

At the runtime environment,MvcContextis exposed by EL ${mvc} in the view.

  • ${mvc.contextPath}will get context path.
  • ${mvc.applicationPath}will get the application path declared in theApplicationclass.
  • ${mvc.csrf.name}generate the Csrf token name.
  • ${mvc.csrf.token}generate the Csrf token value.
  • ${mvc.encoders.js(jsValue)}will escape the js scripts.
  • ${mvc.encoders.html(htmlValue)}will escape the html snippets.

Source Codes

  1. Clone the codes from my github.com account.

    https://github.com/hantsy/ee8-sandbox/

  2. Open the mvc project in NetBeans IDE.

  3. Run it on Glassfish.
  4. After it is deployed and runging on Glassfish application server, navigate http://localhost:8080/ee8-mvc/mvc/tasks in browser.

转载于:https://my.oschina.net/hantsy/blog/661688

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值