Book Image

SPRING COOKBOOK

Book Image

SPRING COOKBOOK

Overview of this book

Table of Contents (19 chapters)
Spring Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Displaying page elements only to authenticated users in views


In this recipe, you'll learn how to display some elements of a page only to authenticated users. For example, a summary box with the information about the account of the currently logged-in user.

How to do it…

Use the <sec:authorize> tag in the JSP file to add conditions for some content to be displayed:

  1. Add the Maven dependency for the Spring Security JSP tags library in pom.xml:

    <dependency>
      <groupId>org.springframework.security</groupId>
      <artifactId>spring-security-taglibs</artifactId>
      <version>3.2.5.RELEASE</version>
    </dependency>
  2. In the JSP, declare the tag library and use <sec:authorize>:

    <%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>    
    
    <sec:authorize access="isAuthenticated()">
      Username: <sec:authentication property="principal.username" />
    </sec:authorize>

How it works…

The text in the sec:authorize tag...