Spring Security身份认证之HelloSpringSecurity(附源码)

简介:

    在上一篇文档中,对Spring Security中的身份认证的流程和管理进行了详细介绍,本文将从实践的角度告诉大家如何使用最简便的方式用Spring Security进行身份验证。


    开发环境如下:

    JDK 1.7

    Tomcat 7

    Eclipse 

    Spring Security 3.2.5

    

    项目目录结构如下:


wKiom1TAYmXSnIpFAAGNOsTljug259.jpg


    1.新建Maven Project,对Maven不熟悉的童鞋请自行充电,现在这个念头不学习Maven绝对是不行的。


wKioL1TAX7KRtrmRAAIaDlk0914608.jpg


    2. 在Pom.xml添加相关jar依赖。


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
< project  xmlns = "http://maven.apache.org/POM/4.0.0"  xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd" >
   < modelVersion >4.0.0</ modelVersion >
   < groupId >com.favccxx.favsecurity</ groupId
   < artifactId >HelloSpringSecurity</ artifactId
   < packaging >war</ packaging
   < version >0.0.1-SNAPSHOT</ version >  
   < name >HelloSpringSecurity Maven Webapp</ name >
   < url >http://maven.apache.org</ url >
   
     < properties >
           < spring.version >3.2.8.RELEASE</ spring.version >
   </ properties >
   
   < dependencies >   
     < dependency >    
       < groupId >junit</ groupId >  
       < artifactId >junit</ artifactId >
       < version >3.8.1</ version >
       < scope >test</ scope >
     </ dependency
     
     
     < dependency >
         < groupId >org.springframework</ groupId >
         < artifactId >spring-core</ artifactId >
         < version >${spring.version}</ version >
     </ dependency >
     < dependency >
         < groupId >org.springframework</ groupId >
         < artifactId >spring-webmvc</ artifactId >
         < version >${spring.version}</ version >
     </ dependency >
     < dependency >
         < groupId >org.springframework</ groupId >
         < artifactId >spring-beans</ artifactId >
         < version >${spring.version}</ version >
     </ dependency >
     < dependency >
         < groupId >org.springframework</ groupId >
         < artifactId >spring-context</ artifactId >
         < version >${spring.version}</ version >
     </ dependency >
     < dependency >
         < groupId >org.springframework</ groupId >
         < artifactId >spring-aop</ artifactId >
         < version >${spring.version}</ version >
     </ dependency >
     < dependency >
         < groupId >org.springframework</ groupId >
         < artifactId >spring-tx</ artifactId >
         < version >${spring.version}</ version >
     </ dependency >
<!--    <dependency> -->
<!--        <groupId>org.springframework</groupId> -->
<!--        <artifactId>spring-test</artifactId> -->
<!--        <version>${spring.version}</version> -->
<!--    </dependency> -->
     < dependency >
         < groupId >org.freemarker</ groupId >
         < artifactId >freemarker</ artifactId >
         < version >2.3.20</ version >
     </ dependency >
     < dependency >
         < groupId >org.springframework</ groupId >
         < artifactId >spring-orm</ artifactId >
         < version >${spring.version}</ version >
     </ dependency >
     
     
      < dependency
         < groupId >org.springframework.security</ groupId >
         < artifactId >spring-security-web</ artifactId >
         < version >3.2.5.RELEASE</ version
       </ dependency
       < dependency >
         < groupId >org.springframework.security</ groupId >
         < artifactId >spring-security-config</ artifactId >
         < version >3.2.5.RELEASE</ version >
       </ dependency >
        
       < dependency >
            < groupId >jstl</ groupId >
            < artifactId >jstl</ artifactId >
            < version >1.2</ version >
        </ dependency >
   </ dependencies >
   < build >
     < finalName >HelloSpringSecurity</ finalName >
   </ build >
</ project >


    3. 配置web.xml,在容器启动时加载Spring MVC的配置文件与Spring Security的配置文件。


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<? xml  version = "1.0"  encoding = "UTF-8" ?>
< web-app  id = "helloSpringSecurity"  version = "2.4"  xmlns = "http://java.sun.com/xml/ns/j2ee"
     xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation = "http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" >
     < display-name >Hello Spring Security</ display-name >
     
     < context-param >
         < param-name >contextConfigLocation</ param-name >
         < param-value >
             classpath:springSecurity.xml
         </ param-value >
     </ context-param >
     
     < listener >
          < listener-class >org.springframework.web.context.ContextLoaderListener</ listener-class >
      </ listener >
      
      < 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 >
      
      < servlet >
         < servlet-name >springMVC</ servlet-name >
         < servlet-class >org.springframework.web.servlet.DispatcherServlet</ servlet-class >
          < init-param >
              < param-name >contextConfigLocation</ param-name >
              < param-value >classpath:spring-context.xml</ param-value >
         </ init-param >
         < load-on-startup >1</ load-on-startup >
     </ servlet >
     < servlet-mapping >
         < servlet-name >springMVC</ servlet-name >
         < url-pattern >/</ url-pattern >
     </ servlet-mapping >
 
</ web-app >


    4. SpringSecurity.xml配置文件如下


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<? 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:security = "http://www.springframework.org/schema/security"
     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
         http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.2.xsd">
 
     < security:http  auto-config = "true" >
         < security:intercept-url  pattern = "/admin"  access = "ROLE_ADMIN" />
         < security:intercept-url  pattern = "/confidential"  access = "ROLE_SUPERADMIN" />
     </ security:http >
     
     
     < security:authentication-manager >
         < security:authentication-provider >
             < security:user-service >
                 < security:user  name = "favccxx"  password = "favccxx"  authorities = "ROLE_USER,ROLE_ADMIN" />
                 < security:user  name = "super"  password = "super"  authorities = "ROLE_SUPERADMIN" />
             </ security:user-service >
         </ security:authentication-provider
     </ security:authentication-manager >
     
</ beans >


    5.spring-context.xml配置文件如下


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<? 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:mvc = "http://www.springframework.org/schema/mvc"
     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-3.2.xsd
         http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
 
     < mvc:annotation-driven ></ mvc:annotation-driven >
     
     < context:component-scan  base-package = "com.favccxx.favsecurity.web" ></ context:component-scan >
     
     < bean  id = "viewResolver"
         class = "org.springframework.web.servlet.view.UrlBasedViewResolver" >
         < property  name = "viewClass"
             value = "org.springframework.web.servlet.view.JstlView"  />
         < property  name = "prefix"  value = "/WEB-INF/views"  />
         < property  name = "suffix"  value = ".jsp"  />
     </ bean >
 
</ beans >


    6. 新建HelloSpringSecurityController.java文件,代码如下:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package  com.favccxx.favsecurity.web;
 
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  HelloSpringSecurityController {
     
     @RequestMapping ( "/hello" )
     public  ModelAndView hello(){
         ModelAndView mav =  new  ModelAndView();
         mav.addObject( "title" "Welcome - Spring Security Hello World" );
         mav.addObject( "message" "This is welcome page!" );
         mav.setViewName( "/hello" );
         return  mav;
     }
     
     @RequestMapping (value = {  "/" "/welcome"  }, method = RequestMethod.GET)
      public  ModelAndView welcome() {
         ModelAndView mav =  new  ModelAndView();
         mav.addObject( "title" "Welcome - Spring Security Hello World" );
         mav.addObject( "message" "This is welcome page!" );
         mav.setViewName( "/hello" );
         return  mav;
      }
     
      @RequestMapping (value =  "/admin" , method = RequestMethod.GET)
           public  ModelAndView admin() {
       
               ModelAndView mav =  new  ModelAndView();
               mav.addObject( "title" "Admin - Spring Security Hello World" );
               mav.addObject( "message" "This is protected page!" );
               mav.setViewName( "/admin" );
              return  mav;
      
         }
      
      }
 
}


    7. 在/WEB-INF/views文件夹下分别创建admin.jsp和hello.jsp


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<%@ page language="java" contentType="text/html; charset=UTF-8"
     pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>    
<!DOCTYPE html>
< html >
< head >
< meta  http-equiv = "Content-Type"  content = "text/html; charset=UTF-8" >
< 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 >


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


    8. 系统运行效果图如下


wKiom1TAYYzRUp5pAAFnGxlExwo893.jpg

wKioL1TAYmSRjfnQAAEXAbGEuwE726.jpg

wKiom1TAYY2Cl1oaAAG_KHPe-pQ373.jpg


    备注:猛击此处下载源代码





本文转自 genuinecx 51CTO博客,原文链接:http://blog.51cto.com/favccxx/1606889,如需转载请自行联系原作者
目录
相关文章
|
1月前
|
XML 缓存 Java
Spring源码之 Bean 的循环依赖
循环依赖是 Spring 中经典问题之一,那么到底什么是循环依赖?简单说就是对象之间相互引用, 如下图所示: 代码层面上很好理解,在 bean 创建过程中 class A 和 class B 又经历了怎样的过程呢? 可以看出形成了一个闭环,如果想解决这个问题,那么在属性填充时要保证不二次创建 A对象 的步骤,也就是必须保证从容器中能够直接获取到 B。 一、复现循环依赖问题 Spring 中默认允许循环依赖的存在,但在 Spring Boot 2.6.x 版本开始默认禁用了循环依赖 1. 基于xml复现循环依赖 定义实体 Bean java复制代码public class A {
|
1月前
|
存储 安全 Java
Spring Boot整合Spring Security--学习笔记
Spring Boot整合Spring Security--学习笔记
53 0
|
2月前
|
Java 关系型数据库 数据库连接
Spring源码解析--深入Spring事务原理
本文将带领大家领略Spring事务的风采,Spring事务是我们在日常开发中经常会遇到的,也是各种大小面试中的高频题,希望通过本文,能让大家对Spring事务有个深入的了解,无论开发还是面试,都不会让Spring事务成为拦路虎。
35 1
|
11天前
|
安全 数据安全/隐私保护
Springboot+Spring security +jwt认证+动态授权
Springboot+Spring security +jwt认证+动态授权
|
1月前
|
Java 测试技术 数据库连接
【Spring源码解读!底层原理高级进阶】【下】探寻Spring内部:BeanFactory和ApplicationContext实现原理揭秘✨
【Spring源码解读!底层原理高级进阶】【下】探寻Spring内部:BeanFactory和ApplicationContext实现原理揭秘✨
|
19小时前
|
存储 安全 Java
第10章 Spring Security 的未来趋势与高级话题(2024 最新版)(下)
第10章 Spring Security 的未来趋势与高级话题(2024 最新版)
7 2
|
19小时前
|
安全 Cloud Native Java
第10章 Spring Security 的未来趋势与高级话题(2024 最新版)(上)
第10章 Spring Security 的未来趋势与高级话题(2024 最新版)
8 2
|
1天前
|
安全 Java Spring
Spring Security 5.7 最新配置细节(直接就能用),WebSecurityConfigurerAdapter 已废弃
Spring Security 5.7 最新配置细节(直接就能用),WebSecurityConfigurerAdapter 已废弃
13 0
|
2天前
|
Java 关系型数据库 MySQL
一套java+ spring boot与vue+ mysql技术开发的UWB高精度工厂人员定位全套系统源码有应用案例
UWB (ULTRA WIDE BAND, UWB) 技术是一种无线载波通讯技术,它不采用正弦载波,而是利用纳秒级的非正弦波窄脉冲传输数据,因此其所占的频谱范围很宽。一套UWB精确定位系统,最高定位精度可达10cm,具有高精度,高动态,高容量,低功耗的应用。
一套java+ spring boot与vue+ mysql技术开发的UWB高精度工厂人员定位全套系统源码有应用案例
|
4天前
|
安全 Java 数据安全/隐私保护
使用Spring Security进行Java身份验证与授权
【4月更文挑战第16天】Spring Security是Java应用的安全框架,提供认证和授权解决方案。通过添加相关依赖到`pom.xml`,然后配置`SecurityConfig`,如设置用户认证信息和URL访问规则,可以实现应用的安全保护。认证流程包括请求拦截、身份验证、响应生成和访问控制。授权则涉及访问决策管理器,如基于角色的投票。Spring Security为开发者构建安全应用提供了全面且灵活的工具,涵盖OAuth2、CSRF保护等功能。