Spring Security 4 Hello World 基于注解 和 XML 例子(带源码)

简介: Spring Security 4 Hello World 基于注解 和 XML 例子(带源码)

下一篇:

Spring Security 4 自定义登录表单 注解和XML例子

原文:http://websystique.com/spring-security/spring-security-4-hello-world-annotation-xml-example/


【已翻译文章,点击分类里面的spring security 4进行查看】

【翻译by 明明如月 QQ 605283073】


本教程演示Spring MVC web项目中Spring Security 4的用法。通过url对访问进行验证。

我们将通过一个经典的hello world例子来学习Spring Security 4 的基本用法。

本文使用基于Servlet3.0容器的Spring注解(因此没有web.xml文件)。同样也会给出基于Security 配置的xml配置。

所用到的技术和软件:

  • Spring 4.1.6.RELEASE
  • Spring Security 4.0.1.RELEASE
  • Maven 3
  • JDK 1.7
  • Tomcat 8.0.21
  • Eclipse JUNO Service Release 2

让我们开始吧...

第1步: 项目目录结构

下面是最终的项目结构:

111.png

现在让我为你展示上面目录结构里面的内容和每个的详细介绍。

第2步: 更新 pom.xml 包含所需的依赖

1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
3. <modelVersion>4.0.0</modelVersion>
4. 
5. <groupId>com.websystique.springsecurity</groupId>
6. <artifactId>SpringSecurityHelloWorldAnnotationExample</artifactId>
7. <version>1.0.0</version>
8. <packaging>war</packaging>
9. 
10. <name>SpringSecurityHelloWorldAnnotationExample</name>
11. 
12. <properties>
13. <springframework.version>4.1.6.RELEASE</springframework.version>
14. <springsecurity.version>4.0.1.RELEASE</springsecurity.version>
15. </properties>
16. 
17. <dependencies>
18. <!-- Spring -->
19. <dependency>
20. <groupId>org.springframework</groupId>
21. <artifactId>spring-core</artifactId>
22. <version>${springframework.version}</version>
23. </dependency>
24. <dependency>
25. <groupId>org.springframework</groupId>
26. <artifactId>spring-web</artifactId>
27. <version>${springframework.version}</version>
28. </dependency>
29. <dependency>
30. <groupId>org.springframework</groupId>
31. <artifactId>spring-webmvc</artifactId>
32. <version>${springframework.version}</version>
33. </dependency>
34. 
35. <!-- Spring Security -->
36. <dependency>
37. <groupId>org.springframework.security</groupId>
38. <artifactId>spring-security-web</artifactId>
39. <version>${springsecurity.version}</version>
40. </dependency>
41. <dependency>
42. <groupId>org.springframework.security</groupId>
43. <artifactId>spring-security-config</artifactId>
44. <version>${springsecurity.version}</version>
45. </dependency>
46. 
47. <dependency>
48. <groupId>javax.servlet</groupId>
49. <artifactId>javax.servlet-api</artifactId>
50. <version>3.1.0</version>
51. </dependency>
52. <dependency>
53. <groupId>javax.servlet.jsp</groupId>
54. <artifactId>javax.servlet.jsp-api</artifactId>
55. <version>2.3.1</version>
56. </dependency>
57. <dependency>
58. <groupId>javax.servlet</groupId>
59. <artifactId>jstl</artifactId>
60. <version>1.2</version>
61. </dependency>
62. </dependencies>
63. 
64. <build>
65. <pluginManagement>
66. <plugins>
67. <plugin>
68. <groupId>org.apache.maven.plugins</groupId>
69. <artifactId>maven-compiler-plugin</artifactId>
70. <version>3.2</version>
71. <configuration>
72. <source>1.7</source>
73. <target>1.7</target>
74. </configuration>
75. </plugin>
76. <plugin>
77. <groupId>org.apache.maven.plugins</groupId>
78. <artifactId>maven-war-plugin</artifactId>
79. <version>2.4</version>
80. <configuration>
81. <warSourceDirectory>src/main/webapp</warSourceDirectory>
82. <warName>SpringSecurityHelloWorldAnnotationExample</warName>
83. <failOnMissingWebXml>false</failOnMissingWebXml>
84. </configuration>
85. </plugin>
86. </plugins>
87. </pluginManagement>
88. <finalName>SpringSecurityHelloWorldAnnotationExample</finalName>
89. </build>
90. </project>


首先需要注意的是maven-war-plugin 的声明。鉴于我们使用纯注解,甚至都没用web.xml。因此我们需配置此插件防止maven创建war包失败。

我们使用的是Spring 和 Spring Security(在本文发表时)最新版本。与此同时,由于我们将使用servlet api和jstl在我们界面中,我们也添加了JSP/Servlet/Jstl的依赖。

一般来说,容器也许已经包含了这些库,所以我们在pom.xml文件中,可以设置他们的scope 为provided。

第3步: 添加 Spring Security 配置类

添加spring security到我们应用中第一步是要创建Spring Security Java 配置类。

这个配置创建一个叫springSecurityFilterChain的Servlet过滤器,来对我们应用中所有的安全相关的事项(保护应用的所有url,验证用户名密码,表单重定向等)负责。

com.websystique.springsecurity.configuration.SecurityConfiguration

1. <pre class="brush: java; title: ; notranslate" title="" style="box-sizing: border-box; border: 0px; font-family: 'Courier 10 Pitch', Courier, monospace; font-size: 15px; margin-top: 0px; margin-bottom: 1.6em; outline: 0px; padding: 1.6em; vertical-align: baseline; line-height: 1.6; max-width: 100%; overflow: auto; color: rgb(64, 64, 64); background: rgb(238, 238, 238);">package com.websystique.springsecurity.configuration;
2. 
3. import org.springframework.beans.factory.annotation.Autowired;
4. import org.springframework.context.annotation.Configuration;
5. import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
6. import org.springframework.security.config.annotation.web.builders.HttpSecurity;
7. import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
8. import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
9. 
10. @Configuration
11. @EnableWebSecurity
12. public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
13. 
14.   @Autowired
15.   public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
16.     auth.inMemoryAuthentication().withUser("bill").password("abc123").roles("USER");
17.     auth.inMemoryAuthentication().withUser("admin").password("root123").roles("ADMIN");
18.     auth.inMemoryAuthentication().withUser("dba").password("root123").roles("ADMIN","DBA");//dba have two roles.
19.   }
20. 
21.   @Override
22.   protected void configure(HttpSecurity http) throws Exception {
23. 
24.     http.authorizeRequests()
25.       .antMatchers("/", "/home").permitAll() 
26.     .antMatchers("/admin/**").access("hasRole('ADMIN')")
27.     .antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')")
28.     .and().formLogin()
29.     .and().exceptionHandling().accessDeniedPage("/Access_Denied");
30. 
31.   }
32. }

上面这个类的configureGlobalSecurity方法为 AuthenticationManagerBuilder配置用户授权和角色信息 。

AuthenticationManagerBuilder (权限管理器创建器)创建负责所有权限请求的AuthenticationManager(权限管理器)。

注意:在上面例子中,我们使用的是 基于内存的权限认证,当然你也可以自由选择JDBC,LDAP或者基于其他技术的权限认证。

重写Configure方法,来配置HttpSecurity 来配置基于特定http请求的安全认证。

它默认是实用所有请求的,但是也可以通过requestMatcher(RequestMatcher)/antMathchers 或者其他类似的方法进行限定。

在上述配置中,我们可以看到‘/’ & ‘/home’这种Url配置是不安全的,任何人都可以访问。

只有具有ADMIN权限的用户才可以访问符合‘/admin/**’的url。只能够同时具有ADMIN 和 DBA权限的人才可以访问符合‘/db/**’ 的Url 。

formLogin 方法提供了基于表单的权限验证,将会产生一个默认的对用户的表单请求。

你也可以自定义登录表单。在接下来的文章里面,你可以看到类似的例子。

我们也会使用exceptionHandling().accessDeniedPage() ,在本例中它将获取所有的403(http访问拒绝)异常然后显示我们的用户定义的HTTP403页面(虽然也没有太大益处)。

上面的安全配置 XML 配置形式如下:

1. <beans:beans xmlns="http://www.springframework.org/schema/security"
2. xmlns:beans="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-4.1.xsd
5.     http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-4.0.xsd">
6. 
7. <http auto-config="true" >
8. <intercept-url pattern="/" access="permitAll" />
9. <intercept-url pattern="/home" access="permitAll" />
10. <intercept-url pattern="/admin**" access="hasRole('ADMIN')" />
11. <intercept-url pattern="/dba**" access="hasRole('ADMIN') and hasRole('DBA')" />
12. <form-login  authentication-failure-url="/Access_Denied" />
13. </http>
14. 
15. <authentication-manager >
16. <authentication-provider>
17. <user-service>
18. <user name="bill"  password="abc123"  authorities="ROLE_USER" />
19. <user name="admin" password="root123" authorities="ROLE_ADMIN" />
20. <user name="dba"   password="root123" authorities="ROLE_ADMIN,ROLE_DBA" />
21. </user-service>
22. </authentication-provider>
23. </authentication-manager>
24. 
25. 
26. </beans:beans>



第 4步: 通过war注册springSecurityFilter(spring安全过滤器)

下面是定制初始化war包中的springSecurityFilter(第三步中的)注册类。

com.websystique.springsecurity.configuration.SecurityWebApplicationInitializer

1. package com.websystique.springsecurity.configuration;
2. 
3. import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
4. 
5. public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {
6. 
7. }

上面对应的xml配置形式为:

1. <filter-name>springSecurityFilterChain</filter-name>
2. <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
3. </filter>
4. 
5. <filter-mapping>
6. <filter-name>springSecurityFilterChain</filter-name>
7. <url-pattern>/*</url-pattern>
8. </filter-mapping>


第5步: 添加 Controller(控制器)

com.websystique.springsecurity.controller.HelloWorldController

1. package com.websystique.springsecurity.controller;
2. 
3. import javax.servlet.http.HttpServletRequest;
4. import javax.servlet.http.HttpServletResponse;
5. 
6. import org.springframework.security.core.Authentication;
7. import org.springframework.security.core.context.SecurityContextHolder;
8. import org.springframework.security.core.userdetails.UserDetails;
9. import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
10. import org.springframework.stereotype.Controller;
11. import org.springframework.ui.ModelMap;
12. import org.springframework.web.bind.annotation.RequestMapping;
13. import org.springframework.web.bind.annotation.RequestMethod;
14. 
15. @Controller
16. public class HelloWorldController {
17. 
18. 
19.     @RequestMapping(value = { "/", "/home" }, method = RequestMethod.GET)
20.     public String homePage(ModelMap model) {
21.         model.addAttribute("greeting", "Hi, Welcome to mysite. ");
22.         return "welcome";
23.     }
24. 
25.     @RequestMapping(value = "/admin", method = RequestMethod.GET)
26.     public String adminPage(ModelMap model) {
27.         model.addAttribute("user", getPrincipal());
28.         return "admin";
29.     }
30. 
31.     @RequestMapping(value = "/db", method = RequestMethod.GET)
32.     public String dbaPage(ModelMap model) {
33.         model.addAttribute("user", getPrincipal());
34.         return "dba";
35.     }
36. 
37.     @RequestMapping(value="/logout", method = RequestMethod.GET)
38.        public String logoutPage (HttpServletRequest request, HttpServletResponse response) {
39.           Authentication auth = SecurityContextHolder.getContext().getAuthentication();
40.           if (auth != null){    
41.              new SecurityContextLogoutHandler().logout(request, response, auth);
42.           }
43.           return "welcome";
44.        }
45. 
46.     @RequestMapping(value = "/Access_Denied", method = RequestMethod.GET)
47.     public String accessDeniedPage(ModelMap model) {
48.         model.addAttribute("user", getPrincipal());
49.         return "accessDenied";
50.     }
51. 
52.     private String getPrincipal(){
53.         String userName = null;
54.         Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
55. 
56.         if (principal instanceof UserDetails) {
57.             userName = ((UserDetails)principal).getUsername();
58.         } else {
59.             userName = principal.toString();
60.         }
61.         return userName;
62.     }
63. }


controller类中的方法比较繁琐.getPrincipal 方法返回从Spring SecurityContext中记录的登录的用户。

logoutPage 方法简单调用 SecurityContextLogoutHandler().logout(request, response, auth)方法
来处理退出操作。

它很巧妙而且将你从不容易管理的jsp页面退出逻辑中解放出来。

你也许注意到上面没有出现 /login’,因为Spring Security默认会产生和处理。

第6步: 添加 SpringMVC 配置类

com.websystique.springsecurity.configuration.HelloWorldConfiguration

1. package com.websystique.springsecurity.configuration;
2. 
3. import org.springframework.context.annotation.Bean;
4. import org.springframework.context.annotation.ComponentScan;
5. import org.springframework.context.annotation.Configuration;
6. import org.springframework.web.servlet.ViewResolver;
7. import org.springframework.web.servlet.config.annotation.EnableWebMvc;
8. import org.springframework.web.servlet.view.InternalResourceViewResolver;
9. import org.springframework.web.servlet.view.JstlView;
10. 
11. @Configuration
12. @EnableWebMvc
13. @ComponentScan(basePackages = "com.websystique.springsecurity")
14. public class HelloWorldConfiguration {
15. 
16. @Bean
17. public ViewResolver viewResolver() {
18. InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
19.         viewResolver.setViewClass(JstlView.class);
20.         viewResolver.setPrefix("/WEB-INF/views/");
21.         viewResolver.setSuffix(".jsp");
22. 
23. return viewResolver;
24.     }
25. 
26. }


第7步: 添加Initializer(初始化器)类

com.websystique.springsecurity.configuration.HelloWorldConfiguration

1. package com.websystique.springsecurity.configuration;
2. 
3. import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
4. 
5. public class SpringMvcInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
6. 
7. @Override
8. protected Class<?>[] getRootConfigClasses() {
9. return new Class[] { HelloWorldConfiguration.class };
10.     }
11. 
12. @Override
13. protected Class<?>[] getServletConfigClasses() {
14. return null;
15.     }
16. 
17. @Override
18. protected String[] getServletMappings() {
19. return new String[] { "/" };
20.     }
21. 
22. }


注意上面的初始化器继承自AbstractAnnotationConfigDispatcherServletInitializer ,它是所有WebApplicationInitializer 实现的基类.

Servlet 3.0 环境下,通过实现WebApplicationInitializer 来配置ServletContext 。这意味着我们将不使用web.xml而且将在支持servlet3.0容器下发布此应用。

第8步: 添加Views(视图)


welcome.jsp

1. <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
2. <html>
3. <head>
4. <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
5. <title>HelloWorld page</title>
6. </head>
7. <body>
8.     Greeting : ${greeting}
9.     This is a welcome page.
10. </body>
11. </html>


admin.jsp


1. <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
2. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
3. <html>
4. <head>
5. <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
6. <title>HelloWorld Admin page</title>
7. </head>
8. <body>
9.     Dear <strong>${user}</strong>, Welcome to Admin Page.
10. <a href="<c:url value="/logout" />">Logout</a>
11. </body>
12. </html>

dba.jsp

1. <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
2. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
3. <html>
4. <head>
5. <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
6. <title>DBA page</title>
7. </head>
8. <body>
9.     Dear <strong>${user}</strong>, Welcome to DBA Page.
10. <a href="<c:url value="/logout" />">Logout</a>
11. </body>
12. </html>

accessDenied.jsp

1. <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
2. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
3. <html>
4. <head>
5. <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
6. <title>AccessDenied page</title>
7. </head>
8. <body>
9.     Dear <strong>${user}</strong>, You are not authorized to access this page
10. <a href="<c:url value="/logout" />">Logout</a>
11. </body>
12. </html>


第9步: 创建和发布应用

正如第7步提到的, 在我们应用中没有用到web.xml作为ServletContext 来启动程序.

现在构建 war 包(通过eclipse或者myeclipse)或者通过maven 命令行( mvn clean install). 在一个 Servlet 3.0 容器中发布本应用. 在这里我使用的是tomcat, 我将 war 文件放到 tomcat webapps 文件夹然后点击 tomcat安装目录的bin文件夹下的start.bat .

启动应用

打开浏览器 在地址栏输入 localhost:8080/SpringSecurityHelloWorldAnnotationExample/并回车


相关文章
|
3天前
|
运维 Java 程序员
Spring5深入浅出篇:基于注解实现的AOP
# Spring5 AOP 深入理解:注解实现 本文介绍了基于注解的AOP编程步骤,包括原始对象、额外功能、切点和组装切面。步骤1-3旨在构建切面,与传统AOP相似。示例代码展示了如何使用`@Around`定义切面和执行逻辑。配置中,通过`@Aspect`和`@Around`注解定义切点,并在Spring配置中启用AOP自动代理。 进一步讨论了切点复用,避免重复代码以提高代码维护性。通过`@Pointcut`定义通用切点表达式,然后在多个通知中引用。此外,解释了AOP底层实现的两种动态代理方式:JDK动态代理和Cglib字节码增强,默认使用JDK,可通过配置切换到Cglib
|
1天前
|
存储 前端开发 Java
Spring Boot自动装配的源码学习
【4月更文挑战第8天】Spring Boot自动装配是其核心机制之一,其设计目标是在应用程序启动时,自动配置所需的各种组件,使得应用程序的开发和部署变得更加简单和高效。下面是关于Spring Boot自动装配的源码学习知识点及实战。
11 1
|
2天前
|
JavaScript Java 开发者
Spring Boot中的@Lazy注解:概念及实战应用
【4月更文挑战第7天】在Spring Framework中,@Lazy注解是一个非常有用的特性,它允许开发者控制Spring容器的bean初始化时机。本文将详细介绍@Lazy注解的概念,并通过一个实际的例子展示如何在Spring Boot应用中使用它。
13 2
|
2天前
|
传感器 人工智能 前端开发
JAVA语言VUE2+Spring boot+MySQL开发的智慧校园系统源码(电子班牌可人脸识别)Saas 模式
智慧校园电子班牌,坐落于班级的门口,适合于各类型学校的场景应用,班级学校日常内容更新可由班级自行管理,也可由学校统一管理。让我们一起看看,电子班牌有哪些功能呢?
41 4
JAVA语言VUE2+Spring boot+MySQL开发的智慧校园系统源码(电子班牌可人脸识别)Saas 模式
|
3天前
|
前端开发 Java
SpringBoot之自定义注解参数校验
SpringBoot之自定义注解参数校验
14 2
|
9天前
|
Java 测试技术 开发者
【亮剑】如何通过自定义注解来实现 Spring AOP,以便更加灵活地控制方法的拦截和增强?
【4月更文挑战第30天】通过自定义注解实现Spring AOP,可以更灵活地控制方法拦截和增强。首先定义自定义注解,如`@MyCustomAnnotation`,然后创建切面类`MyCustomAspect`,使用`@Pointcut`和`@Before/@After`定义切点及通知。配置AOP代理,添加`@EnableAspectJAutoProxy`到配置类。最后,在需拦截的方法上应用自定义注解。遵循保持注解职责单一、选择合适保留策略等最佳实践,提高代码可重用性和可维护性。记得测试AOP逻辑。
|
9天前
|
Java Spring
springboot自带的@Scheduled注解开启定时任务
springboot自带的@Scheduled注解开启定时任务
|
10天前
|
设计模式 安全 Java
【初学者慎入】Spring源码中的16种设计模式实现
以上是威哥给大家整理了16种常见的设计模式在 Spring 源码中的运用,学习 Spring 源码成为了 Java 程序员的标配,你还知道Spring 中哪些源码中运用了设计模式,欢迎留言与威哥交流。
|
12天前
|
XML JSON Java
【SpringBoot】springboot常用注解
【SpringBoot】springboot常用注解
|
13天前
|
Java 数据库 开发者
了解Spring Boot:重要注解详解
了解Spring Boot:重要注解详解