chapter09_保护Web应用_5_保护视图

  • 之前的种种操作都是为了不要让某些没有权限的用户看到某个页面,接下来要做的是这些用户能看到页面,但是看不到页面的全部。即,页面中的某些部分根据用户有无权限决定是否渲染

  • JSP的视图保护方案

    (1) 声明

    <%@ taglib prefix=“security” uri=“http://www.springframework.org/security/tags” %>

    (2) 标签

    security:authentication 用户渲染当前用户认证对象的详细信息

    security:authorize 如果用户被授予了特定权限或spEL表达式计算结果为true,则渲染其中的内容

    (3) 访问认证信息的细节

    需求:你好,xxx同学!

    示例

      Hello there...<security:authentication property="principal.username"/>
    

    其中,property属性用来表示用户认证对象的一个属性

    (4) 条件性的渲染内容

    需求:根据用户权限决定是否渲染内容

    示例

      <security:authorize access="hasRole('ROLE_USER')">
    
          <div>
              fuck!
          </div>
    
      </security:authorize>
    

    其中,access属性被赋值为一个SpEL表达式,表达式的值为真的时候则渲染;而且可以使用and连接多个条件

  • Thymeleaf的视图保护方案

    (1) 注册"方言",之后才能使用

    示例 WebConfig.java

      @Configuration
      @EnableWebMvc
      @ComponentScan("spittr.web")
      public class WebConfig extends WebMvcConfigurerAdapter {
    
          ...
    
          @Bean
          public SpringTemplateEngine templateEngine(TemplateResolver templateResolver) {
    
              SpringTemplateEngine templateEngine = new SpringTemplateEngine();
              templateEngine.setTemplateResolver(templateResolver);
              
              templateEngine.addDialect(new SpringSecurityDialect());
    
              return templateEngine;
          }
    
          ...
      }
    

    (2) 在html中声明命名空间

      <html xmlns="http://www.w3.org/1999/xhtml"
            xmlns:th="http://www.thymeleaf.org"
            xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
    

    (3) 访问认证信息的细节

      sec:authentication 等价于JSP的 <security:authentication>
    

    示例

      Hello there...<span sec:authentication="name">user-name</span>
    

    (4) 条件性的渲染内容

    sec:authorize 等价于JSP的 <security:authorize access=“xxx”>

    示例

      <div sec:authorize="isAuthenticated()">
    

猜你喜欢

转载自blog.csdn.net/captxb/article/details/87884664