美文网首页
Spring Boot 集成 Spring Security 实

Spring Boot 集成 Spring Security 实

作者: 又语 | 来源:发表于2020-04-21 15:43 被阅读0次

    本文介绍 Spring Boot 集成 Spring Security 实现账号认证。


    1. 创建 Spring Boot 工程

    参考:IntelliJ IDEA 创建 Spring Boot 工程

    2. 添加依赖

    添加 spring-boot-starter-security 依赖,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>
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.2.6.RELEASE</version>
            <relativePath/>
        </parent>
        <groupId>tutorial.spring.security</groupId>
        <artifactId>spring-security-authentication-1</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <name>spring-security-authentication-1</name>
        <description>Demo project for Spring Boot integrated with Spring Security</description>
    
        <properties>
            <java.version>1.8</java.version>
        </properties>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-security</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
                <exclusions>
                    <exclusion>
                        <groupId>org.junit.vintage</groupId>
                        <artifactId>junit-vintage-engine</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>
        </dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
    
    </project>
    

    3. 创建 Controller 层代码

    package tutorial.spring.security.controller;
    
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    public class DemoController {
    
        @GetMapping("/demo")
        public String demo() {
            return "Spring Security Authentication Demo";
        }
    }
    

    4. 启动应用

    部分启动日志如下:

    ......
    2020-04-21 15:43:21.398  INFO 18600 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
    2020-04-21 15:43:21.414  INFO 18600 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
    2020-04-21 15:43:21.415  INFO 18600 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.33]
    2020-04-21 15:43:21.570  INFO 18600 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
    2020-04-21 15:43:21.570  INFO 18600 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1867 ms
    2020-04-21 15:43:21.837  INFO 18600 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
    2020-04-21 15:43:22.108  INFO 18600 --- [           main] .s.s.UserDetailsServiceAutoConfiguration : 
    
    Using generated security password: 68815f43-a745-49e9-9fc7-e0aec8090d77
    
    2020-04-21 15:43:22.232  INFO 18600 --- [           main] o.s.s.web.DefaultSecurityFilterChain     : Creating filter chain: any request, [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@31e32ea2, org.springframework.security.web.context.SecurityContextPersistenceFilter@1d4664d7, org.springframework.security.web.header.HeaderWriterFilter@4bff2185, org.springframework.security.web.csrf.CsrfFilter@847f3e7, org.springframework.security.web.authentication.logout.LogoutFilter@5d58c727, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter@2d6aca33, org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter@6090f3ca, org.springframework.security.web.authentication.ui.DefaultLogoutPageGeneratingFilter@1473b8c0, org.springframework.security.web.authentication.www.BasicAuthenticationFilter@a50ae65, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@56ccd751, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@488b50ec, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@5b5c0057, org.springframework.security.web.session.SessionManagementFilter@7fedfe27, org.springframework.security.web.access.ExceptionTranslationFilter@6f099cef, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@78411116]
    2020-04-21 15:43:22.328  INFO 18600 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
    2020-04-21 15:43:22.335  INFO 18600 --- [           main] SpringSecurityAuthentication1Application : Started SpringSecurityAuthentication1Application in 3.357 seconds (JVM running for 4.435)
    

    分析:

    • Using generated security password 是随机生成的用于登录的字符串,默认情况下每次启动应用这个密码都会变。

    • 日志中打印出了 Spring Security 默认的安全过滤器链,依次为:

      • org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter
      • org.springframework.security.web.context.SecurityContextPersistenceFilter
      • org.springframework.security.web.header.HeaderWriterFilter
      • org.springframework.security.web.csrf.CsrfFilter
      • org.springframework.security.web.authentication.logout.LogoutFilter
      • org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter
      • org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter
      • org.springframework.security.web.authentication.ui.DefaultLogoutPageGeneratingFilter
      • org.springframework.security.web.authentication.www.BasicAuthenticationFilter
      • org.springframework.security.web.savedrequest.RequestCacheAwareFilter
      • org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter
      • org.springframework.security.web.authentication.AnonymousAuthenticationFilter
      • org.springframework.security.web.session.SessionManagementFilter
      • org.springframework.security.web.access.ExceptionTranslationFilter
      • org.springframework.security.web.access.intercept.FilterSecurityInterceptor

      这其中的某些过滤器十分常用,如 LogoutFilterUsernamePasswordAuthenticationFilter 等,有关过滤器更详细的知识将在其它文章中详述。

    5. 浏览器访问

    5.1. 打开浏览器,访问 http://localhost:8080/demo,此时页面被自动重定向到 http://localhost:8080/login,显示出一个登录页面(这个登录页面是 Spring Security 框架提供的);
    5.2. 在登录页面输入默认的用户名 user 和启动日志中生成的随机密码 68815f43-a745-49e9-9fc7-e0aec8090d77 后点击 Sign in 按钮,页面自动跳转到 http://localhost:8080/demo 并显示 Spring Security Authentication Demo

    相关文章

      网友评论

          本文标题:Spring Boot 集成 Spring Security 实

          本文链接:https://www.haomeiwen.com/subject/dtouihtx.html