Spring Security笔记:Hello World

本文演示了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插件创建项目的好处在于,很多配置已经自动帮我们生成好了,基本的项目架子已经具备,不需要在这上面花太多心思,下面是项目结构图

二、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.zip

Spring Security笔记:Hello World

时间: 2024-10-09 21:25:24

Spring Security笔记:Hello World的相关文章

Spring Security笔记:Remember Me(下次自动登录)

前一节学习了如何限制登录尝试次数,今天在这个基础上再增加一点新功能:Remember Me. 很多网站,比如博客园,在登录页面就有这个选项,勾选“下次自动登录”后,在一定时间段内,只要不清空浏览器Cookie,就可以自动登录. 一.spring-security.xml 最简单的配置 1 <http auto-config="true" use-expressions="true"> 2 ... 3 <remember-me /> 4 <

Spring Security笔记:自定义Login/Logout Filter、AuthenticationProvider、AuthenticationToken

在前面的学习中,配置文件中的<http>...</http>都是采用的auto-config="true"这种自动配置模式,根据Spring Security文档的说明: ------------------ auto-config Automatically registers a login form, BASIC authentication, logout services. If set to "true", all of thes

Spring Security笔记:使用数据库进行用户认证(form login using database)

在前一节,学习了如何自定义登录页,但是用户名.密码仍然是配置在xml中的,这样显然太非主流,本节将学习如何把用户名/密码/角色存储在db中,通过db来实现用户认证 一.项目结构 与前面的示例相比,因为要连接db,所以多出了一个spring-database.xml用来定义数据库连接,此外,为了演示登录用户权限不足的场景,加了一个页面403.jsp,用来统一显示权限不足的提示信息 二.数据库表结构(oracle环境) 1 create table T_USERS 2 ( 3 d_username

Spring Security笔记:登录尝试次数限制

今天在前面一节的基础之上,再增加一点新内容,默认情况下Spring Security不会对登录错误的尝试次数做限制,也就是说允许暴力尝试,这显然不够安全,下面的内容将带着大家一起学习如何限制登录尝试次数. 首先对之前创建的数据库表做点小调整 一.表结构调整 T_USERS增加了如下3个字段: D_ACCOUNTNONEXPIRED,NUMBER(1) -- 表示帐号是否未过期D_ACCOUNTNONLOCKED,NUMBER(1), -- 表示帐号是否未锁定D_CREDENTIALSNONEXP

Spring Security笔记:HTTP Basic 认证

在第一节 Spring Security笔记:Hello World 的基础上,只要把Spring-Security.xml里改一个位置 1 <http auto-config="true"> 2 <intercept-url pattern="/admin" access="ROLE_USER" /> 3 <http-basic /> 4 </http> 注意第三行,加上<http-basi

Spring Security笔记:使用数据库进行用户认证(form login using database) - 菩提树下的杨过 - 博客园

body { font-family: "Microsoft YaHei UI","Microsoft YaHei",SimSun,"Segoe UI",Tahoma,Helvetica,Sans-Serif,"Microsoft YaHei", Georgia,Helvetica,Arial,sans-serif,宋体, PMingLiU,serif; font-size: 10.5pt; line-height: 1.5;

spring security笔记

当指定http元素的auto-config="true"时,就相当于如下内容的简写. <security:http> <security:form-login/> <security:http-basic/> <security:logout/> </security:http> 在Spring Security中,AuthenticationManager的默认实现是ProviderManager,而且它不直接自己处理认证请

Spring Security笔记:使用BCrypt算法加密存储登录密码

在前一节使用数据库进行用户认证(form login using database)里,我们学习了如何把“登录帐号.密码”存储在db中,但是密码都是明文存储的,显然不太讲究.这一节将学习如何使用spring security3新加入的bcrypt算法,将登录加密存储到db中,并正常通过验证. 一.Bcrypt算法 int t = 0; String password = "123456"; System.out.println(password + " -> "

关于Spring Security的笔记

1.web.xml配置文件 加载Spring Security,将DelegatingFilterProxy配置在DispatcherServlet之前. <filter> <filter-name>springSecurityFilterChain</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> <