Spring Security - 案例

Spring Security



简介

  • Spring Security是针对Spring项目的安全框架,也是SpringBoot底层安全模块默认的技术选型,他可以实现强大的Web安全控制,对于安全控制,我们仅需要引入spring-boot-starter-security模块,进行少量的配置,即可实现强大的安全管理!
  • 重要Java类
    • WebSecurityConfigurerAdapter:自定义Security策略
    • AuthenticationManagerBuilder:自定义认证策略
    • @EnableWebSecurity:开启WebSecurity模式
  • Spring Security的两个主要目标是“认证 - Authentication”和“授权 - Authorization”(访问控制)

案例

1. pom.xml

<?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>
	  <groupId>com.murphy</groupId>
    <artifactId>springsecurity</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springsecurity</name>
    
  <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
      	<!-- security -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <!-- thymeleaf整合security -->
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity5</artifactId>
            <version>3.0.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- thymeleaf -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-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>
1.1 项目结构

在这里插入图片描述

1.2 静态资源 - templates
  • index.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>首页</title>
    <!--semantic-ui-->
    <link href="https://cdn.bootcss.com/semantic-ui/2.4.1/semantic.min.css" rel="stylesheet">
    <link th:href="@{/css/qinstyle.css}" rel="stylesheet">
</head>
<body>

<!--主容器-->
<div class="ui container">

    <div class="ui segment" id="index-header-nav" th:fragment="nav-menu">
        <div class="ui secondary menu">
            <a class="item"  th:href="@{/index}">首页</a>

            <!--登录注销-->
            <div class="right menu">
                <!--未登录-->
                <a class="item" th:href="@{/toLogin}">
                    <i class="address card icon"></i> 登录
                </a>
              	<!--注销-->
                <a class="item" th:href="@{/logout}">
                    <i class="sign-out icon"></i> 注销
                </a>
            </div>
        </div>
    </div>

    <div class="ui segment" style="text-align: center">
        <h3>Spring Security Study</h3>
    </div>

    <div>
        <br>
        <div class="ui three column stackable grid">
            <div class="column">
                <div class="ui raised segment">
                    <div class
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
以下是使用Spring Security的简单案例: 1. 创建一个Spring Boot应用程序 2. 添加Spring Security依赖项 3. 创建一个Spring Security配置类 4. 添加用户和角色 5. 在控制器中保护端点 1. 创建一个Spring Boot应用程序 首先,您需要创建一个新的Spring Boot应用程序。您可以使用Spring Initializr来创建一个新的项目。请确保选择了Spring Web和Thymeleaf作为依赖项。 2. 添加Spring Security依赖项 在pom.xml中添加以下依赖项: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> ``` 3. 创建一个Spring Security配置类 创建一个名为SecurityConfig的类,并将其标记为@Configuration和@EnableWebSecurity。在配置类中,您可以定义安全规则,例如哪些URL需要身份验证,哪些角色可以访问受保护的URL等。 ``` @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/admin/**").hasRole("ADMIN") .antMatchers("/user/**").hasRole("USER") .anyRequest().authenticated() .and() .formLogin() .and() .logout() .logoutSuccessUrl("/login?logout") .and() .csrf().disable(); } @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("admin").password("{noop}admin").roles("ADMIN") .and() .withUser("user").password("{noop}user").roles("USER"); } } ``` 在上面的代码中,我们定义了以下安全规则: - /admin/** URL需要ADMIN角色才能访问 - /user/** URL需要USER角色才能访问 - 任何其他URL需要进行身份验证 - 我们使用基于表单的身份验证,因此我们需要提供一个登录页面 - 我们禁用了CSRF保护,以便简化示例 我们还定义了两个用户:admin和user。这些用户将在内存中进行身份验证,密码使用了{noop}前缀,这是因为Spring Security 5需要密码进行编码,但是在本示例中我们使用了没有编码的密码。 4. 添加用户和角色 我们在SecurityConfig类中定义了两个用户:admin和user。这些用户将在内存中进行身份验证。在实际情况下,您可能会使用其他身份验证提供程序,例如数据库或LDAP。 5. 在控制器中保护端点 现在我们可以在控制器中保护端点。为此,请使用@PreAuthorize注释指定所需的角色。 ``` @Controller public class HomeController { @GetMapping("/") public String home() { return "home"; } @GetMapping("/admin") @PreAuthorize("hasRole('ADMIN')") public String admin() { return "admin"; } @GetMapping("/user") @PreAuthorize("hasRole('USER')") public String user() { return "user"; } } ``` 在上面的代码中,我们使用@PreAuthorize注释来指定保护/admin和/user端点所需的角色。如果用户没有所需的角色,则无法访问这些端点。 现在您可以启动应用程序并尝试访问以下URL: - http://localhost:8080/ - 首页,不需要身份验证 - http://localhost:8080/admin - 需要ADMIN角色才能访问 - http://localhost:8080/user - 需要USER角色才能访问 如果您尝试访问/admin或/user URL而不先进行身份验证,则会重定向到登录页面。在登录页面上,您可以使用admin或user作为用户名,使用相应的密码进行身份验证。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xmurphymurphy

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值