美文网首页Spring Security
Spring Security 入门教程(三)- 基于登录认证记

Spring Security 入门教程(三)- 基于登录认证记

作者: 老亚瑟程序猿 | 来源:发表于2018-12-14 17:58 被阅读77次

    介绍

    本篇文章基于Spring Security 入门教程(一) - 简单的登录认证 基础上修改的记住我教程。

    项目代码:https://github.com/Bootcap/spring-security-study-session

    一、配置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 http://maven.apache.org/maven-v4_0_0.xsd">
    
      <modelVersion>4.0.0</modelVersion>
    
      <name>spring-security-study-session</name>
      <groupId>com.bootcap.session.security</groupId>
      <artifactId>spring-security-study-session</artifactId>
      <version>1.0.0-SNAPSHOT</version>
    
      <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.1.RELEASE</version>
      </parent>
    
      <properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
      </properties>
    
    
      <dependencies>
     <!-- Spring Boot-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-devtools</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</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-security</artifactId>
            </dependency>
    
            <!-- Test -->
            <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>
    

    二、修改TemplateConfig.java类
    路径:src/java/com/bootcap/session/security/configuration/TemplateConfig.java

    @Configuration
    public class TemplateConfig implements WebMvcConfigurer {
    
        @Override
        public void addViewControllers(ViewControllerRegistry registry) {
            registry.addViewController("/").setViewName("index");
            registry.addViewController("/index").setViewName("index");
            registry.addViewController("/login").setViewName("login");
        }
    }
    

    三、修改WebSecurityConfig.java
    路径:src/java/com/bootcap/session/security/configuration/WebSecurityConfig.java

    package com.bootcap.session.security.configuration;
    
    /**
     * Created by jack.
     * 2018-12-10 11:03
     */
    @Configuration
    @EnableWebSecurity
    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    
        @Override
        public void configure(WebSecurity web) throws Exception {
            web.ignoring()
                    .antMatchers("/js/**","/img/**");
        }
    
        // 重点修改的方法 
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests()
                    .anyRequest().authenticated()
                    .and()
                        .formLogin()
                            .loginPage("/login")
                            .permitAll().defaultSuccessUrl("/")
                    .and()
                        .logout()
                            .invalidateHttpSession(true)
                            .clearAuthentication(true)
                            .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
                            .logoutSuccessUrl("/login?logout")
                            .permitAll()
                    .and()
                        .rememberMe()
                            .key("unique-and-secret")
                            .rememberMeCookieName("rememberMeCookieName") // 设置cookie名称
                            .tokenValiditySeconds(24 * 60 * 60); // 设置令牌有效期,默认为2周
    
        }
    
        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.inMemoryAuthentication() // 在内存中进行身份验证
                    .passwordEncoder(new BCryptPasswordEncoder())
                    .withUser("user")
                    .password(new BCryptPasswordEncoder().encode("123456"))
                    .roles("USER");
        }
    
    }
    
    

    四、修改页面文件
    路径:src/resources/templates/

    4.1 修改login.html,在原基础上加上记住我复选框
    <!DOCTYPE html>
    <html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>登录页面</title>
    </head>
    <body>
    <h1>登录页面</h1>
    <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> 密&nbsp;&nbsp;&nbsp;码: <input type="password" name="password"/> </label></div>
        <div>
            <input id="remember-me" name="remember-me" type="checkbox"/> 记住我
            <input type="submit" value="登录"/>
        </div>
    </form>
    </body>
    </html>
    
    4.2 修改index.html
    <!DOCTYPE html>
    <html xmlns:th="http://www.thymeleaf.org"
          xmlns:sec="http://www.w3.org/1999/xhtml">
    <head>
        <meta charset="utf-8"/>
        <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
        <meta name="viewport" content="width=device-width, initial-scale=1"/>
    
    
        <title>Spring Security 登录认证记住我实例</title>
    </head>
    <body>
    <div class="container">
        <h1>Spring Security 登录认证记住我实例</h1>
    
        <div class="container">
            <p>
                <span sec:authorize="isAuthenticated()">
                        | 登录用户: <span sec:authentication="name"></span> |
                        角色: <span sec:authentication="principal.authorities"></span> |
                        <a th:href="@{/logout}">退出登录</a>
                    </span>
            </p>
        </div>
    
    </div>
    
    
    </body>
    </html>
    

    五、启动Application.java运行项目

    5.1 项目启动完成后,浏览器访问:localhsot:8080,会自动跳到登录页面进行登录,并勾选记住我。
    5.2 登录成功后会挑战到index.html页面,通过debug发现,spring security已经为我们分配了刚才命名的cookie。
    5.3 为了验证是记住我登录,我们把JSESSIONID删除,并刷新页面,会发现又刚删除的JSESSIONID又产生了。而且Value值已经改变。

    上一篇:Spring Security 入门教程(二)- 基于数据库信息进行验证
    下一篇:敬请期待

    相关文章

      网友评论

        本文标题:Spring Security 入门教程(三)- 基于登录认证记

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