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/并回车


相关文章
|
14天前
|
缓存 监控 Java
SpringBoot @Scheduled 注解详解
使用`@Scheduled`注解实现方法周期性执行,支持固定间隔、延迟或Cron表达式触发,基于Spring Task,适用于日志清理、数据同步等定时任务场景。需启用`@EnableScheduling`,注意线程阻塞与分布式重复问题,推荐结合`@Async`异步处理,提升任务调度效率。
305 128
|
1月前
|
XML 安全 Java
使用 Spring 的 @Aspect 和 @Pointcut 注解简化面向方面的编程 (AOP)
面向方面编程(AOP)通过分离横切关注点,如日志、安全和事务,提升代码模块化与可维护性。Spring 提供了对 AOP 的强大支持,核心注解 `@Aspect` 和 `@Pointcut` 使得定义切面与切入点变得简洁直观。`@Aspect` 标记切面类,集中处理通用逻辑;`@Pointcut` 则通过表达式定义通知的应用位置,提高代码可读性与复用性。二者结合,使开发者能清晰划分业务逻辑与辅助功能,简化维护并提升系统灵活性。Spring AOP 借助代理机制实现运行时织入,与 Spring 容器无缝集成,支持依赖注入与声明式配置,是构建清晰、高内聚应用的理想选择。
287 0
|
16天前
|
XML Java 数据格式
常用SpringBoot注解汇总与用法说明
这些注解的使用和组合是Spring Boot快速开发和微服务实现的基础,通过它们,可以有效地指导Spring容器进行类发现、自动装配、配置、代理和管理等核心功能。开发者应当根据项目实际需求,运用这些注解来优化代码结构和服务逻辑。
126 12
|
29天前
|
Java 测试技术 数据库
使用Spring的@Retryable注解进行自动重试
在现代软件开发中,容错性和弹性至关重要。Spring框架提供的`@Retryable`注解为处理瞬时故障提供了一种声明式、可配置的重试机制,使开发者能够以简洁的方式增强应用的自我恢复能力。本文深入解析了`@Retryable`的使用方法及其参数配置,并结合`@Recover`实现失败回退策略,帮助构建更健壮、可靠的应用程序。
111 1
使用Spring的@Retryable注解进行自动重试
|
29天前
|
传感器 Java 数据库
探索Spring Boot的@Conditional注解的上下文配置
Spring Boot 的 `@Conditional` 注解可根据不同条件动态控制 Bean 的加载,提升应用的灵活性与可配置性。本文深入解析其用法与优势,并结合实例展示如何通过自定义条件类实现环境适配的智能配置。
探索Spring Boot的@Conditional注解的上下文配置
|
29天前
|
智能设计 Java 测试技术
Spring中最大化@Lazy注解,实现资源高效利用
本文深入探讨了 Spring 框架中的 `@Lazy` 注解,介绍了其在资源管理和性能优化中的作用。通过延迟初始化 Bean,`@Lazy` 可显著提升应用启动速度,合理利用系统资源,并增强对 Bean 生命周期的控制。文章还分析了 `@Lazy` 的工作机制、使用场景、最佳实践以及常见陷阱与解决方案,帮助开发者更高效地构建可扩展、高性能的 Spring 应用程序。
Spring中最大化@Lazy注解,实现资源高效利用
|
1月前
|
安全 IDE Java
Spring 的@FieldDefaults和@Data:Lombok 注解以实现更简洁的代码
本文介绍了如何在 Spring 应用程序中使用 Project Lombok 的 `@Data` 和 `@FieldDefaults` 注解来减少样板代码,提升代码可读性和可维护性,并探讨了其适用场景与限制。
Spring 的@FieldDefaults和@Data:Lombok 注解以实现更简洁的代码
|
1月前
|
缓存 监控 安全
Spring Boot 的执行器注解:@Endpoint、@ReadOperation 等
Spring Boot Actuator 提供多种生产就绪功能,帮助开发者监控和管理应用。通过注解如 `@Endpoint`、`@ReadOperation` 等,可轻松创建自定义端点,实现健康检查、指标收集、环境信息查看等功能,提升应用的可观测性与可管理性。
Spring Boot 的执行器注解:@Endpoint、@ReadOperation 等
|
1月前
|
Java 测试技术 编译器
@GrpcService使用注解在 Spring Boot 中开始使用 gRPC
本文介绍了如何在Spring Boot应用中集成gRPC框架,使用`@GrpcService`注解实现高效、可扩展的服务间通信。内容涵盖gRPC与Protocol Buffers的原理、环境配置、服务定义与实现、测试方法等,帮助开发者快速构建高性能的微服务系统。
147 0
|
1月前
|
XML Java 测试技术
使用 Spring 的 @Import 和 @ImportResource 注解构建模块化应用程序
本文介绍了Spring框架中的两个重要注解`@Import`和`@ImportResource`,它们在模块化开发中起着关键作用。文章详细分析了这两个注解的功能、使用场景及最佳实践,帮助开发者构建更清晰、可维护和可扩展的Java应用程序。
137 0