• Spring-Security教程【一】简单的登录认证


    一,引入jar包,注意不要引入security

            <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>

    二,配置文件

    # 端口号
    server:
      port: 8080
    
    spring:
      # thymeleaf配置
      thymeleaf:
        enabled: true
        encoding: UTF-8
        mode: HTML
        servlet:
          content-type: text/html
        prefix: classpath:/templates/
        suffix: .html

    三,创建一个不受保护的界面

    Web页面包含两个简单的视图:index主页和“hello”页面,都定义在Thymeleaf模板中。

    路径:src/main/resources/templates/index.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>Spring Security Index</title>
    </head>
    <body>
        <h1>Index Page</h1>
        <a th:href="@{/hello}">点击前往hello页面</a>
    </body>
    </html>

    路径:src/main/resources/templates/hello.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>Hello</title>
    </head>
    <body>
        <h1>Hello Spring Security</h1>
    </body>
    </html>

    四,配置springmvc视图控制器

    由于web应用基于springmvc,因此需要配置视图控制器来暴露这些模板

    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 TemplateConfig implements WebMvcConfigurer {
    
        @Override
        public void addViewControllers(ViewControllerRegistry registry) {
            registry.addViewController("/").setViewName("index");
            registry.addViewController("/index").setViewName("index");
            registry.addViewController("/hello").setViewName("hello");
            registry.addViewController("/login").setViewName("login");
        }
    }

    运行main方法,并在浏览器地址栏输入:http://localhost:8080/

    如果看到index.html页面,说明已经成功运行

    点击跳转到hello页面,无需任何认证即可进行跳转

    五,引入并使用Spring Security

    在上述的两个视图中,我们希望在访问"/hello"时需要登录才能够进入Hello页面。此时我们可以通过Spring Security来实现。(如果Spring Security在类路径上,则Spring Boot会使用"Basic"认证自动保护所有HTTP请求,也可以自定义设置
        <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
    package com.example.jwtdemo.config;
    
    import org.springframework.context.annotation.Configuration;
    import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
    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.crypto.bcrypt.BCryptPasswordEncoder;
    
    /**
     * @author Jensen Zhan
     */
    @Configuration
    @EnableWebSecurity
    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests()
                    .antMatchers("/","/index").permitAll() // permitAll被允许访问
                    .anyRequest().authenticated() // 其余的请求需要认证后才可允许访问
                    .and()
                    .formLogin()
                    .loginPage("/login")
                    .permitAll()
                    .and()
                    .logout()
                    .permitAll();
        }
    
        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.inMemoryAuthentication() // 在内存中进行身份验证
                    .passwordEncoder(new BCryptPasswordEncoder())
                    .withUser("user")
                    .password(new BCryptPasswordEncoder().encode("123456"))
                    .roles("USER");
        }
    
    }

    【说明】:

    • WebSecurityConfig类使用了@EnableWebSecurity注解,以启用Spring Security的Web安全支持。

    • configure(HttpSecurity)方法自定义有哪些url需要被认证,哪些不需要。当用户登录后将会被重定向请求到需要身份认证的页面(hello.html),否则在用户未登录的情况下将会跳转到登录页面

    • configure(AuthenticationManagerBuilder)方法用于设置认证的条件保存于内存中,用户名为“user”,密码为“123456”,角色为User。同时该方法也可以修改认证方式为jdbc进行认证


    创建登录页面(认证时需要用到)
    <!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>
    <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 type="submit" value="登录"/></div>
    </form>
    </body>
    </html>

    修改hello.html

    在认证成功后跳转到hello.html页面,我们希望能够看到登录的用户名,同时允许用户退出登录,因此我们需要修改hello.html页面

    路径:src/main/resources/templates/hello.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>Hello</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.html页面中使用了HttpServletRequest#getRemoteUser()的thymeleaf集成来显示用户名。

    • 页面中退出登录表单会将请求提交到"/logout",成功注销后程序会重定向到"/login?logout"

    启动程序
  • 相关阅读:
    Python操作Excel,使用xlwings
    TortoiseGit的使用
    QsLog日志
    状态机 1748一次遍历
    socket理解
    __gcd函数,求最大公约数
    opencv resize的一个小问题
    iOS要想访问工程里的资源文件
    iOS 真机socket连不上问题
    要看
  • 原文地址:https://www.cnblogs.com/zhanzhuang/p/13067788.html
Copyright © 2020-2023  润新知