Spring Security --- The use of Spring Security in Thymeleaf

Table of contents

Preliminary

get attribute

Judgment of authority


  • Preliminary

  • Spring Security can control the display effect in some view technologies
  • Example: JSP or Thymeleaf
  • Thymeleaf is often used as a view display technology in projects that are not separated from the front and back ends and use Spring Boot
  • Thymeleaf's support for Spring Security is placed in thymeleaf-extras-springsecurityX
  • So you need to add the dependency of this jar package and the dependency of thymeleaf to the project

  • Introduce thymeleaf namespace and security namespace in html page

  • get attribute

  • You can get all getXXX contents in UsernamePasswordAuthenticationToken through sec:authentication="" in the html page
  • Contains the content of getXXX in the parent class
  • According to the source code, the following properties are obtained:
    • name: login account name
    • principal: login principal, which is UserDetails in custom login logic
    • credentials: Credentials
    • authorities: permissions and roles
    • details: It is actually an instance of WebAuthenticationDetails; remoteAddress (client ip) and sessionId (current sessionId) can be obtained
  • Implementation steps:
  • Write the following content in html to test the obtained value

  • Write the controller:
  • The thymeleaf page needs to control forwarding, write the following method in the controller class

  • Judgment of authority

  • In html pages, sec:authorize="expression" can be used to control permissions and determine whether to display certain content
  • The content of the expression is the same as the usage of access(expression)
  • If the user has the specified permission, display the corresponding content
  • If the expression is not true, the corresponding element is not displayed
  • Users with different permissions display different buttons:
    • Set user roles and permissions
    • Set the user to have admin, /insert, /delete permissions ROLE_abc role

    • Control page display effect
    • Determine the content displayed on the page based on user permissions and roles on the page

Guess you like

Origin blog.csdn.net/weixin_59624686/article/details/131264351