Spring Security 身份验证

使用Spring Security进行身份验证还是比较简单。

什么叫身份验证?

身份验证如同我们进公园验门票,进火车站难车票和身份证一样,它是验证身份,不是权限。权限在一定程序上等同于权力,如火车票上的座位号,有座位号就有坐某个位置的权力。

这里有一个应用场景:

有3个页面,index页面是入口,在index上访问hello页面。hello页面需要身份验证后才能登录。

我们通过实例来学习Spring Security 身份验证,新建一个Spring boot工程,工程结构如下:

Spring Security需要添加安全相关的依赖,它的pm.xml如下:

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

<?xml version="1.0" encoding="UTF-8"?>

<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <parent>

        <groupId>org.springframework.boot</groupId>

        <artifactId>spring-boot-starter-parent</artifactId>

        <version>2.1.11.RELEASE</version>

        <relativePath/> <!-- lookup parent from repository -->

    </parent>

    <groupId>com.example</groupId>

    <artifactId>spring-security</artifactId>

    <version>0.0.1-SNAPSHOT</version>

    <name>spring-security</name>

    <description>Demo project for Spring Boot</description>

    <properties>

        <java.version>1.8</java.version>

        <maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>

    </properties>

    <dependencies>

        <dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-starter-security</artifactId>

        </dependency>

        <dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-starter-thymeleaf</artifactId>

        </dependency>

        <dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-starter-web</artifactId>

        </dependency>

        <dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-devtools</artifactId>

            <scope>runtime</scope>

            <optional>true</optional>

        </dependency>

        <dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-starter-test</artifactId>

            <scope>test</scope>

        </dependency>

        <dependency>

            <groupId>org.springframework.security</groupId>

            <artifactId>spring-security-test</artifactId>

            <scope>test</scope>

        </dependency>

    </dependencies>

    <build>

        <plugins>

            <plugin>

                <groupId>org.springframework.boot</groupId>

                <artifactId>spring-boot-maven-plugin</artifactId>

            </plugin>

        </plugins>

    </build>

</project>

spring-boot-starter-security 加载Spring Security 相关的依赖

为简单说明,仅用了个3个HTML,及注册3个MVC控制器

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

package com.wangshenghua.spring.security.start;

import org.springframework.context.annotation.Configuration;

import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;

import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration

public class MvcConfig implements WebMvcConfigurer {

    public void addViewControllers(ViewControllerRegistry registry) {

        registry.addViewController("/index").setViewName("index");

        registry.addViewController("/").setViewName("index");

        registry.addViewController("/hello").setViewName("hello");

        registry.addViewController("/login").setViewName("login");

    }

}

HTML中加入了springsecurity标签,thymeleaf中叫命名空间

index.html

1

2

3

4

5

6

7

8

9

10

11

12

13

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml"

xmlns:th="https://www.thymeleaf.org"

xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity3">

    <head>

        <title>首页  - Spring Security 示例</title>

    </head>

    <body>

        <h1>Spring Security 示例</h1>

        <p>点击 <a th:href="@{/hello}">这里</a> 访问/hello</p>

    </body>

</html>

加入命名空间xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity3"

点击链接访问hello页面

hello.html

1

2

3

4

5

6

7

8

9

10

11

12

13

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org"

      xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity3">

    <head>

        <title>Hello World! - Spring Security 示例</title>

    </head>

    <body>

        <h1 th:inline="text">Hello [[${#httpServletRequest.remoteUser}]]!</h1>

        <form th:action="@{/logout}" method="post">

            <input type="submit" value="注销"/>

        </form>

    </body>

</html>

hello页面显示登录用户名[[${#httpServletRequest.remoteUser}]]

还有一个表单,请求指向logout,logout由Spring Security 框架实现,程序无需关注怎么实现,这也节省了工作量。

登录页面login.html

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

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml"

    xmlns:th="https://www.thymeleaf.org"

    xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity3">

<head>

<meta charset="UTF-8">

<title>登录 - Spring Security 示例</title>

</head>

<body>

    <div th:if="${param.error}">无效的用户名和密码。</div>

    <div th:if="${param.logout}">你已经退出。</div>

    <form th:action="@{/login}" method="post">

        <div>

            <label>用户名 : <input type="text" name="username" />

            </label>

        </div>

        <div>

            <label>密码: <input type="password" name="password" />

            </label>

        </div>

        <div>

            <input type="submit" value="登录" />

        </div>

    </form>

</body>

</html>

表单提示两个域,一个用户名,一个密码,请求login由Spring Security 框架处理,程序员也不需要关注,也节省了开发时间。

第10行和第11行接收两个参数,参数不同显示不同的提示。

Spring Security 核心部分是继承org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter

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

package com.wangshenghua.spring.security.start;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.security.config.annotation.web.builders.HttpSecurity;

import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;

import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

import org.springframework.security.core.userdetails.User;

import org.springframework.security.core.userdetails.UserDetails;

import org.springframework.security.core.userdetails.UserDetailsService;

import org.springframework.security.provisioning.InMemoryUserDetailsManager;

@Configuration

@EnableWebSecurity

public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override

    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests()

        .antMatchers("/""/index").permitAll() //根路径和/index无需验证可访问

        .anyRequest().authenticated()//其它页面要验证才能访问

        .and().formLogin().loginPage("/login").permitAll()//登录页面无需验证可访问

        .and().logout().permitAll();//退出功能无需验证可访问

    }

    @Bean

    @Override

    public UserDetailsService userDetailsService() {

        //构建一用户

        UserDetails user = User.withUsername("admin").password("{noop}admin").roles("USER").build();

        return new InMemoryUserDetailsManager(user);//将用户放于内存里

    }

}

它创建一个用户(用户名,密码,角色),并将用户放到内存中。

同时指定了哪些资源无需身份验证可以访问,哪些资源必须身份验证后方可访问。见代码注解。


运行演示:

源码下载

本文转自王二的网站,已获原文作者许可,欢迎转载

https://www.wangshenghua.com/wiki/spring-security/2bf63f12d9898ebaa32fa29ea48e33b0/

发布了10 篇原创文章 · 获赞 20 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/code386/article/details/103967758
今日推荐