Spring Security4.X 简单实例介绍

时间:2023-03-09 14:33:50
Spring Security4.X 简单实例介绍

简介

本例子采用的是SpringMVC、SpringSecurity和Spring整合的简单使用

使用gradle搭建的项目(gradle比maven更加便捷),可以自行了解

web.xml配置

 <?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1"> <!-- Spring启动监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> <!-- Spring配置 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/spring-service.xml</param-value>
</context-param> <!-- 配置DispatcherServlet -->
<servlet>
<servlet-name>Spring MVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/spring-web.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>Spring MVC</servlet-name>
<!-- 默认匹配所有的请求 -->
<url-pattern>/</url-pattern>
</servlet-mapping> <!-- 编码过滤器 乱码处理 -->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<async-supported>true</async-supported>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> <!-- 配置Spring Security -->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter> <filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> </web-app>

spring相关配置

  spring-service.xml

  

 <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd"> <import resource="spring-security.xml"/> </beans>

  spring-web.xml

 <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 1:开启SpringMVC注解模式 -->
<!-- 简化配置:
(1):自动注册DefaultAnnotationHandlerMapping,AnnotationMethodHandlerAdapter
(2).提供一系列:数据绑定,数字和日期的format @NumberFormat,@DataTimeFormat,
xml,json默认读写支持
-->
<mvc:annotation-driven/> <!-- 2:静态资源 默认Servlet配置
1:加入对静态资源的处理:js,gif,png
2:允许使用"/"做整体映射
-->
<mvc:default-servlet-handler/> <!-- 3:配置jsp 显示ViewResolver -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/views/"/>
<property name="suffix" value=".jsp"/>
</bean> <!--4: 扫描web相关的bean -->
<context:component-scan base-package="com.h3c.xservice.lc.controller" /> <bean id="mappingJacksonHttpMessageConverter"
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean> </beans>

  spring-security.xml

 <?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd"> <http auto-config="true" use-expressions="true">
<intercept-url pattern="/admin" access="hasRole('ROLE_USER')" />
<logout logout-url="/j_spring_security_logout" invalidate-session="true" logout-success-url="/login"/>
<csrf disabled="true"/>
</http> <authentication-manager>
<authentication-provider>
<user-service>
<user name="root" password="root" authorities="ROLE_USER"/>
</user-service>
</authentication-provider>
</authentication-manager> </beans:beans>

如果 配置access = "ROLE_USER",会出现500错误,4.X需要配置access = "hashRole('ROLE_USER')"

csrf标签下 disabled属性需要配置为true,否则logout会错

use-expressions = "true" 加和不加都没什么影响

java代码

 package com.h3c.xservice.lc.controller;

 import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView; @Controller
public class UserController { @RequestMapping(value = { "/", "/welcome" }, method = RequestMethod.GET)
public ModelAndView welcome() { ModelAndView model = new ModelAndView();
model.addObject("title", "Welcome - Spring Security Hello World");
model.addObject("message", "This is welcome page!");
model.setViewName("hello");
return model; } @RequestMapping(value = "/admin", method = RequestMethod.GET)
public ModelAndView admin() { ModelAndView model = new ModelAndView();
model.addObject("title", "Admin - Spring Security Hello World");
model.addObject("message", "This is protected page!");
model.setViewName("admin"); return model; } }

jsp代码

admin.jsp

 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<title>${title}</title>
</head>
<body>
<h1>Title : ${title}</h1>
<h1>Message : ${message}</h1> <c:if test="${pageContext.request.userPrincipal.name != null}">
<h2>
Welcome : ${pageContext.request.userPrincipal.name} |
<a href="<c:url value="/j_spring_security_logout" />"> Logout</a>
</h2>
</c:if>
</body>
</html>

hello.jsp

 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>${title}</title>
</head>
<body>
<h1>Title:${title}</h1>
<h1>Message:${message}</h1>
</body>
</html>

浏览器访问

    

  访问127.0.0.1:8080/项目名/welcome,如下

Spring Security4.X 简单实例介绍

  访问127.0.0.1:8080/项目名/admin,如下

  Spring Security4.X 简单实例介绍

当账号密码错误的时候会有错误提示,可以自行测试。正确后,会进去admin页面,如下

Spring Security4.X 简单实例介绍

因为我配置了点击Logout后重定向到登录页面,所以点击后又会去到上图页面。

参考学习资料:

http://www.tuicool.com/articles/R7bQ3eb

http://www.cnblogs.com/yjmyzz/p/spring-security-with-spring-mvc-helloworld.html

http://docs.spring.io/spring-security/site/docs/4.1.3.RELEASE/reference/htmlsingle/