Spring Security笔记:Hello World

简介: 本文演示了Spring Security的最最基本用法,二个页面(或理解成二个url),一个需要登录认证后才能访问(比如:../admin/),一个可匿名访问(比如:../welcome) 注:以下内容参考了 http://www.

本文演示了Spring Security的最最基本用法,二个页面(或理解成二个url),一个需要登录认证后才能访问(比如:../admin/),一个可匿名访问(比如:../welcome)

注:以下内容参考了 http://www.mkyong.com/spring-security/spring-security-hello-world-example/

 

一、利用STS(Spring Tools Suite)创建一个Spring MVC Project

如果不想使用STS,在普通Eclipse上安装Spring Tool Suite插件也行,用Spring插件创建项目的好处在于,很多配置已经自动帮我们生成好了,基本的项目架子已经具备,不需要在这上面花太多心思,下面是项目结构图

 pom文件中的dependencies

  1 <?xml version="1.0" encoding="UTF-8"?>
  2 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  4     <modelVersion>4.0.0</modelVersion>
  5     <groupId>com.cnblogs</groupId>
  6     <artifactId>SpringSecurity-HelloWorld-XML</artifactId>
  7     <name>SpringSecurity-HelloWorld-XML</name>
  8     <packaging>war</packaging>
  9     <version>1.0</version>
 10     <properties>
 11         <jdk.version>1.6</jdk.version>
 12         <spring.version>3.2.8.RELEASE</spring.version>
 13         <spring.security.version>3.2.3.RELEASE</spring.security.version>
 14         <jstl.version>1.2</jstl.version>
 15     </properties>
 16 
 17     <dependencies>
 18         <!-- Spring dependencies -->
 19         <dependency>
 20             <groupId>org.springframework</groupId>
 21             <artifactId>spring-core</artifactId>
 22             <version>${spring.version}</version>
 23         </dependency>
 24         <dependency>
 25             <groupId>org.springframework</groupId>
 26             <artifactId>spring-aop</artifactId>
 27             <version>${spring.version}</version>
 28         </dependency>
 29         <dependency>
 30             <groupId>org.springframework</groupId>
 31             <artifactId>spring-beans</artifactId>
 32             <version>${spring.version}</version>
 33         </dependency>
 34         <dependency>
 35             <groupId>org.springframework</groupId>
 36             <artifactId>spring-expression</artifactId>
 37             <version>${spring.version}</version>
 38         </dependency>
 39         <dependency>
 40             <groupId>org.springframework</groupId>
 41             <artifactId>spring-context</artifactId>
 42             <version>${spring.version}</version>
 43         </dependency>
 44         <dependency>
 45             <groupId>org.springframework</groupId>
 46             <artifactId>spring-context-support</artifactId>
 47             <version>${spring.version}</version>
 48         </dependency>
 49         <dependency>
 50             <groupId>org.springframework</groupId>
 51             <artifactId>spring-web</artifactId>
 52             <version>${spring.version}</version>
 53         </dependency>
 54 
 55         <dependency>
 56             <groupId>org.springframework</groupId>
 57             <artifactId>spring-webmvc</artifactId>
 58             <version>${spring.version}</version>
 59         </dependency>
 60 
 61         <!-- Spring Security -->
 62         <dependency>
 63             <groupId>org.springframework.security</groupId>
 64             <artifactId>spring-security-core</artifactId>
 65             <version>${spring.security.version}</version>
 66         </dependency>
 67 
 68         <dependency>
 69             <groupId>org.springframework.security</groupId>
 70             <artifactId>spring-security-web</artifactId>
 71             <version>${spring.security.version}</version>
 72         </dependency>
 73 
 74         <dependency>
 75             <groupId>org.springframework.security</groupId>
 76             <artifactId>spring-security-config</artifactId>
 77             <version>${spring.security.version}</version>
 78         </dependency>
 79 
 80         <!-- jstl for jsp page -->
 81         <dependency>
 82             <groupId>jstl</groupId>
 83             <artifactId>jstl</artifactId>
 84             <version>${jstl.version}</version>
 85         </dependency>
 86 
 87     </dependencies>
 88     <build>
 89         <plugins>
 90             <plugin>
 91                 <artifactId>maven-eclipse-plugin</artifactId>
 92                 <version>2.9</version>
 93                 <configuration>
 94                     <additionalProjectnatures>
 95                         <projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
 96                     </additionalProjectnatures>
 97                     <additionalBuildcommands>
 98                         <buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
 99                     </additionalBuildcommands>
100                     <downloadSources>true</downloadSources>
101                     <downloadJavadocs>true</downloadJavadocs>
102                 </configuration>
103             </plugin>
104             <plugin>
105                 <groupId>org.apache.maven.plugins</groupId>
106                 <artifactId>maven-compiler-plugin</artifactId>
107                 <version>2.5.1</version>
108                 <configuration>
109                     <source>1.6</source>
110                     <target>1.6</target>
111                     <compilerArgument>-Xlint:all</compilerArgument>
112                     <showWarnings>true</showWarnings>
113                     <showDeprecation>true</showDeprecation>
114                 </configuration>
115             </plugin>
116             <plugin>
117                 <groupId>org.codehaus.mojo</groupId>
118                 <artifactId>exec-maven-plugin</artifactId>
119                 <version>1.2.1</version>
120                 <configuration>
121                     <mainClass>org.test.int1.Main</mainClass>
122                 </configuration>
123             </plugin>
124         </plugins>
125     </build>
126 </project>
pom.xml

 

二、Controller

 1 package com.cnblogs.yjmyzz;
 2 
 3 import org.springframework.stereotype.Controller;
 4 import org.springframework.web.bind.annotation.RequestMapping;
 5 import org.springframework.web.bind.annotation.RequestMethod;
 6 import org.springframework.web.servlet.ModelAndView;
 7 
 8 @Controller
 9 public class HelloController {
10 
11     @RequestMapping(value = { "/", "/welcome" }, method = RequestMethod.GET)
12     public ModelAndView welcome() {
13 
14         ModelAndView model = new ModelAndView();
15         model.addObject("title", "Welcome - Spring Security Hello World");
16         model.addObject("message", "This is welcome page!");
17         model.setViewName("hello");
18         return model;
19 
20     }
21 
22     @RequestMapping(value = "/admin", method = RequestMethod.GET)
23     public ModelAndView admin() {
24 
25         ModelAndView model = new ModelAndView();
26         model.addObject("title", "Admin - Spring Security Hello World");
27         model.addObject("message", "This is protected page!");
28         model.setViewName("admin");
29 
30         return model;
31 
32     }
33 
34 }
HelloController

毫无撸点,二个普通的Action而已,分别对应视图admin.jsp以及hello.jsp

 

三、web.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
 5 
 6     <!-- The definition of the Root Spring Container shared by all Servlets 
 7         and Filters -->
 8     <context-param>
 9         <param-name>contextConfigLocation</param-name>
10         <param-value>/WEB-INF/spring/root-context.xml</param-value>
11     </context-param>
12 
13     <!-- Creates the Spring Container shared by all Servlets and Filters -->
14     <listener>
15         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
16     </listener>
17 
18     <!-- Processes application requests -->
19     <servlet>
20         <servlet-name>appServlet</servlet-name>
21         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
22         <init-param>
23             <param-name>contextConfigLocation</param-name>
24             <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
25         </init-param>
26         <load-on-startup>1</load-on-startup>
27     </servlet>
28 
29     <servlet-mapping>
30         <servlet-name>appServlet</servlet-name>
31         <url-pattern>/</url-pattern>
32     </servlet-mapping>
33 
34     <!-- Spring Security -->
35     <filter>
36         <filter-name>springSecurityFilterChain</filter-name>
37         <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
38     </filter>
39 
40     <filter-mapping>
41         <filter-name>springSecurityFilterChain</filter-name>
42         <url-pattern>/*</url-pattern>
43     </filter-mapping>
44 
45 </web-app>
web.xml

稍做解释一下:看似一大堆,但其实除了34-43行需要手动添加之外,其它全是STS工具自动生成的,34-43行通过添加一个过滤器,对每个请求进行“拦截”处理。

此外注意里面配置的几个xml文件

/WEB-INF/spring/root-context.xml 这是Spring-beans的核心主文件
/WEB-INF/spring/appServlet/servlet-context.xml 这是Spring-MVC的入口Servlet配置文件

四、servlet-context.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans:beans xmlns="http://www.springframework.org/schema/mvc"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4     xmlns:beans="http://www.springframework.org/schema/beans"
 5     xmlns:context="http://www.springframework.org/schema/context"
 6     xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
 7         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
 8         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
 9 
10     <!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
11     
12     <!-- Enables the Spring MVC @Controller programming model -->
13     <annotation-driven />
14 
15     <!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
16     <resources mapping="/resources/**" location="/resources/" />
17 
18     <!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
19     <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
20         <beans:property name="prefix" value="/WEB-INF/views/" />
21         <beans:property name="suffix" value=".jsp" />
22     </beans:bean>
23     
24     <context:component-scan base-package="com.cnblogs.yjmyzz" />
25     
26     
27     
28 </beans:beans>
servlet-context.xml

这个是工具自动生成的,主要用来处理Spring-MVC的相关内容,跟Security其实没啥关系

 

五、root-context.xml

1 <?xml version="1.0" encoding="UTF-8"?>
2 <beans xmlns="http://www.springframework.org/schema/beans"
3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
5 
6     <!-- Root Context: defines shared resources visible to all other web components -->
7     
8     <import resource="spring-security.xml" />
9 </beans>
root-context.xml

这个看似乎平淡无奇,但其实包含了“配置模块化”的思想,通过import,把跟Security相关的配置,单独放在另一个xml文件中,然后import进来,配置文件特别多的时候,这样可以使Spring的配置看上去更有条理

 

六、spring-security.xml

 1 <beans:beans xmlns="http://www.springframework.org/schema/security"
 2     xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 3     xsi:schemaLocation="http://www.springframework.org/schema/beans
 4     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
 5     http://www.springframework.org/schema/security
 6     http://www.springframework.org/schema/security/spring-security-3.2.xsd">
 7 
 8     <http auto-config="true">
 9         <intercept-url pattern="/admin" access="ROLE_USER" />
10     </http>
11 
12     <authentication-manager>
13         <authentication-provider>
14             <user-service>
15                 <user name="yjmyzz" password="123456" authorities="ROLE_USER" />
16             </user-service>
17         </authentication-provider>
18     </authentication-manager>
19 
20 </beans:beans>
spring-security.xml

这才是Security的精华所在,8-10行,表示“/admin”请求需要ROLE_USER角色的用户才能访问,12-18行配置了一个用户yjmyzz,以及密码123456,并将该用户授于ROLE_USER角色(当然:这里只是演示,实际应用中,更常见的做法是将用户名、密码放到数据库中)

 

七、admin.jsp及hello.jsp

hello.jsp

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8" session="false"%>
 3 
 4 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 5 <html>
 6 <head>
 7 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 8 <title>${title}</title>
 9 </head>
10 <body>
11     <h1>Title:${title}</h1>
12     <h1>Message:${message}</h1>
13 </body>
14 </html>
hello.jsp

admin.jsp

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8" session="true"%>
 3 <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
 4 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 5 <html>
 6 <head>
 7 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 8 <title>${title}</title>
 9 </head>
10 <body>
11     <h1>Title : ${title}</h1>
12     <h1>Message : ${message}</h1>
13 
14     <c:if test="${pageContext.request.userPrincipal.name != null}">
15         <h2>
16             Welcome : ${pageContext.request.userPrincipal.name} | <a
17                 href="<c:url value="/j_spring_security_logout" />"> Logout</a>
18         </h2>
19     </c:if>
20 </body>
21 </html>
admin.jsp

 二个常规页面,唯一值得注意的是17行的a链接: j_spring_security_logout,是Spring Security默认生成的logout地址,除非开发人员有其它设置,否则默认退出地址就是它

 

运行效果:

访问/welcome时,毫无阻力

 

 

访问/admin时,会重定向到Spring Security自动生成的login页面 spring_security_login

 

在登录页面输入yjmyzz/123456后,自动跳转到登录前的页面 /admin

 

最后:附示例源代码:SpringSecurity-HelloWorld-XML(0717).zip

目录
相关文章
|
2月前
|
XML Java 测试技术
spring复习01,IOC的思想和第一个spring程序helloWorld
Spring框架中IOC(控制反转)的思想和实现,通过一个简单的例子展示了如何通过IOC容器管理对象依赖,从而提高代码的灵活性和可维护性。
spring复习01,IOC的思想和第一个spring程序helloWorld
|
4月前
|
安全 Java 数据安全/隐私保护
使用Spring Security实现细粒度的权限控制
使用Spring Security实现细粒度的权限控制
|
4月前
|
安全 Java 数据库
实现基于Spring Security的权限管理系统
实现基于Spring Security的权限管理系统
|
4月前
|
安全 Java 数据安全/隐私保护
解析Spring Security中的权限控制策略
解析Spring Security中的权限控制策略
|
22天前
|
Java 数据库连接 Spring
【2021Spring编程实战笔记】Spring开发分享~(下)
【2021Spring编程实战笔记】Spring开发分享~(下)
23 1
|
22天前
|
XML Java 数据库连接
【2020Spring编程实战笔记】Spring开发分享~(上)
【2020Spring编程实战笔记】Spring开发分享~
42 0
|
2月前
|
Java 数据库连接 API
【Java笔记+踩坑】Spring Data JPA
从常用注解、实体类和各层编写方法入手,详细介绍JPA框架在增删改查等方面的基本用法,以及填充用户名日期、分页查询等高级用法。
【Java笔记+踩坑】Spring Data JPA
|
2月前
|
Java 数据库连接 数据格式
【Java笔记+踩坑】Spring基础2——IOC,DI注解开发、整合Mybatis,Junit
IOC/DI配置管理DruidDataSource和properties、核心容器的创建、获取bean的方式、spring注解开发、注解开发管理第三方bean、Spring整合Mybatis和Junit
【Java笔记+踩坑】Spring基础2——IOC,DI注解开发、整合Mybatis,Junit
|
5月前
|
JSON 安全 Java
Spring Security 6.x 微信公众平台OAuth2授权实战
上一篇介绍了OAuth2协议的基本原理,以及Spring Security框架中自带的OAuth2客户端GitHub的实现细节,本篇以微信公众号网页授权登录为目的,介绍如何在原框架基础上定制开发OAuth2客户端。
188 4
Spring Security 6.x 微信公众平台OAuth2授权实战
|
5月前
|
存储 安全 Java
Spring Security 6.x OAuth2登录认证源码分析
上一篇介绍了Spring Security框架中身份认证的架构设计,本篇就OAuth2客户端登录认证的实现源码做一些分析。
215 2
Spring Security 6.x OAuth2登录认证源码分析