Spring Security 4 安全视图片段 使用标签(Spring Security 标签)

2021-08-27 15:19:04 浏览数 (1)

上一篇文章:Spring Security 4 退出 示例(带源码)

下一篇文章:

Spring Security 4 基于角色的登录例子(带源码)

原文地址: http://websystique.com/spring-security/spring-security-4-secure-view-layer-using-taglibs/

【剩余文章,将尽快翻译完毕,敬请期待。 翻译by 明明如月 QQ 605283073】

本教程向你展示怎样创建安全视图层,Spring MVC web 应用中,使用Spring Security 标签,基于用户角色显示或者隐藏部分jsp或者视图。

第一步,想使用Spring Security标签需要在pom.xml文件中添加 spring-security-taglibs依赖

代码语言:javascript复制
    org.springframework.security
    spring-security-taglibs
    4.0.1.RELEASE

下一步,在views或者jsp页面头添加包含标签

代码语言:javascript复制
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags"%>

最后,我们可以使用 Spring Security 表单式中 hasRole, hasAnyRole等标签,如下:

代码语言:javascript复制
<%@ 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"%>


    
    Welcome page


    Dear ${user}, Welcome to Home Page.
    ">Logout
 
    

    

    
        View all information| This part is visible to Everyone
    
 
    

    
        
            Edit this page | This part is visible only to ADMIN
        
    
 
    

    
        
            Start backup | This part is visible only to one who is both ADMIN & DBA

如果你需要根据角色 显示或者隐藏视图中的片段,可以参考上面的例子。

下面是本例中 Security Configuration 的配置:

代码语言:javascript复制
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
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
 
     
    @Autowired
    public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().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");
    }
}

上面配置对应的xml配置如下:

代码语言:javascript复制

controller

代码语言:javascript复制
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;
 
@Controller
public class HelloWorldController {
 
     
    @RequestMapping(value = { "/", "/home" }, method = RequestMethod.GET)
    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 request, 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;
    }
 
}

其他代码和本系列其他文章一样。

部署 &启动

下载本项目的完整代码。在Servlet 3.0 (Tomcat7/8)容器中构建和部署。

打开浏览器输入: localhost:8080/SpringSecuritySecureViewFragmentsUsingSecurityTaglibs/

将来到登录界面

输入USER 角色的账户

你将看到少量的信息

退出后 再用ADMIN角色的账户登陆

提交表单,你将看到ADMIN角色相关的操作

退出,用DBA 角色账户登陆

你将看到DBA角色 对应的页面

本文结束。 下一篇文章将教你怎样用基于用户权限的登录。也就是说,根据登录权限 登录后重定向到不同的urls

代码下载地址: http://websystique.com/?smd_process_download=1&download_id=1388

0 人点赞