Spring Security 4 Safe View Picture segment using tags (Spring security tab)

Source: Internet
Author: User

Previous post: Spring Security 4 output example (with source)

Next post:

 Spring Security 4 Role-based login example (with source)


Original address: http://websystique.com/spring-security/spring-security-4-secure-view-layer-using-taglibs/

"The rest of the article will be translated as soon as possible, please look forward. Translated by clearly like the month QQ 605283073 "

This tutorial shows you how to create a secure view layer that uses spring security tags to display or hide part of a JSP or view based on a user rolein a spring MVC web App .


The first step is to use the Spring security tag to add the spring-security-taglibs dependency in the pom.xml file

<dependency>    <groupId>org.springframework.security</groupId>    <artifactId> Spring-security-taglibs</artifactid>    <version>4.0.1.RELEASE</version></dependency>

Next, add the include tag to the views or JSP page header

<%@ taglib prefix= "SEC" uri= "Http://www.springframework.org/security/tags"%>


Finally, we can useSpringSecurity form in a single-Hasrole, Hasanyrole and other labels, as follows:

<%@ page language= "java" contenttype= "text/html; Charset=iso-8859-1 "pageencoding=" iso-8859-1 "%><%@ taglib prefix=" C "uri=" Http://java.sun.com/jsp/jstl/core "    %><%@ taglib prefix= "SEC" uri= "Http://www.springframework.org/security/tags"%>
If you need to show or hide the clips in the view based on the role, you can refer to the example above.

Here is the configuration of the Security configuration in this example:

Package com.websystique.springsecurity.configuration; Import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.context.annotation.configuration;import Org.springframework.security.config.annotation.authentication.builders.authenticationmanagerbuilder;import Org.springframework.security.config.annotation.web.builders.httpsecurity;import Org.springframework.security.config.annotation.web.configuration.enablewebsecurity;import Org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @Configuration @enablewebsecuritypublic class Securityconfiguration extends Websecurityconfigureradapter {@Autowi Red public void configureglobalsecurity (Authenticationmanagerbuilder auth) throws Exception {auth.inmemoryauthe        Ntication (). Withuser ("Bill"). Password ("abc123"). Roles ("USER");        Auth.inmemoryauthentication (). Withuser ("admin"). Password ("root123"). Roles ("admin"); Auth.inmemoryauthentication (). Withuser ("DBA "). Password (" root123 "). Roles (" ADMIN "," DBA ");         } @Override protected void Configure (Httpsecurity http) throws Exception {http.authorizerequests () . Antmatchers ("/", "Home"). Access ("Hasrole (' USER ') or Hasrole (' ADMIN ') or Hasrole (' DBA ')"). and (). Formlogin (). LoginPage ("/login"). Usernameparameter ("Ssoid"). Passwordparameter ("password"). and (). ExceptionHandling ().    Accessdeniedpage ("/access_denied"); }}

The XML configuration corresponding to the above configuration is as follows:

<beans:beans xmlns= "http://www.springframework.org/schema/security" xmlns:beans= "http// Www.springframework.org/schema/beans "xmlns:xsi=" Http://www.w3.org/2001/XMLSchema-instance "xsi:schemalocation="    Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd Http://www.springframework.org/schema/security http://www.springframework.org/schema/security/ Spring-security-4.0.xsd "> 
Controller

Package Com.websystique.springsecurity.controller; Import Javax.servlet.http.httpservletrequest;import javax.servlet.http.HttpServletResponse; Import Org.springframework.security.core.authentication;import Org.springframework.security.core.context.securitycontextholder;import Org.springframework.security.core.userdetails.userdetails;import Org.springframework.security.web.authentication.logout.securitycontextlogouthandler;import Org.springframework.stereotype.controller;import Org.springframework.ui.modelmap;import Org.springframework.web.bind.annotation.requestmapping;import Org.springframework.web.bind.annotation.RequestMethod; @Controllerpublic class Helloworldcontroller {@RequestMapping (value = {"/", "/Home"}, method = Requestmethod.g        ET) Public String homepage (Modelmap model) {Model.addattribute ("user", Getprincipal ());    return "Welcome"; } @RequestMapping (value = "/access_denied", method = requestmethod.get) public String accessdeniedpage (ModElmap model) {Model.addattribute ("user", Getprincipal ());    return "accessDenied";    } @RequestMapping (value = "/login", method = requestmethod.get) public String LoginPage () {return ' login '; } @RequestMapping (value= "/logout", method = requestmethod.get) public String logoutpage (HttpServletRequest requ        EST, httpservletresponse response) {Authentication auth = Securitycontextholder.getcontext (). Getauthentication ();        if (auth! = null) {new Securitycontextlogouthandler (). Logout (Request, response, Auth);    } return "Redirect:/login?logout";        private String Getprincipal () {string userName = null;         Object principal = Securitycontextholder.getcontext (). Getauthentication (). Getprincipal ();        if (principal instanceof userdetails) {userName = ((userdetails) principal). GetUserName ();        } else {userName = principal.tostring ();    } return userName; } } 

Other code is the same as other articles in this series.

Deploy & Start Download the complete code for this project. In Servlet 3.0(TOMCAT7/8)Build and deploy in the container.
Open Browser Input:localhost:8080/springsecuritysecureviewfragmentsusingsecuritytaglibs/Future to login interface

Enter the account for the user role


You will see a small amount of information


Exit and log in with Admin role account


Submit the form and you will see the admin role related actions


Exit, log in with DBA role account


You'll see the page for the DBA role



This article concludes. The next article will teach you how to use login based on user rights. That is, redirect to a different URLs after logging on with logon rights

Code: http://websystique.com/?smd_process_download=1&download_id=1388

Spring Security 4 Safe View Picture segment using tags (Spring security tab)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.