美文网首页
Spring Security 2 --Guides(文末有项目

Spring Security 2 --Guides(文末有项目

作者: _River_ | 来源:发表于2021-04-09 01:15 被阅读0次
学习连接(阿里中间件工程师 徐靖峰 徐老师的相关文章):
https://www.cnkirito.moe/tags/Spring-Security/

0:整体流程

1: 在MvcConfig配置接口是跳到页面的
2:WebSecurityConfig 配置了 放行 拦截 以及 权限
3:http://localhost:8080  或者 http://localhost:8080/home 跳到主页  (被放行)
4:点击 here 想要跳到  hello页面
5:但在被拦截了 需要先跳 login页面
6:在login页面输入 账号密码 提交  
    账号密码错误则跳到http://localhost:8080/login?error
7:成功则跳到到 hello页面
8:退出则返回到 login页面 http://localhost:8080/login?logout
1:引入依赖(SpringBoot 整合)
由于我们集成了 springboot,所以不需要显示的引入 Spring Security 文档中描述 core,config 依赖,
只需要引入 spring-boot-starter-security 即可。
<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-thymeleaf</artifactId>
    </dependency>
</dependencies>
2:创建一个不受安全限制的 web 页面
这是一个首页,不受安全限制
这个简单的页面上包含了一个链接,跳转到 “/hello”

 src/main/resources/templates/home.html
 src/main/resources/templates/hello.html
<!DOCTYPE html>
<!-- home -->
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
    <head>
        <title>Spring Security Example</title>
    </head>
    <body>
        <h1>Welcome!</h1>

        <p>Click <a th:href="@{/hello}">here</a> to see a greeting.</p>
    </body>
</html>
<!DOCTYPE html>
<!-- hello -->
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
    <head>
        <title>Hello World!</title>
    </head>
    <body>
        <h1>Hello world!</h1>
    </body>
</html>
3:接下来配置 Spring MVC,使得我们能够访问到页面。
//该配置可以让http 请求该接口的时候 直接跳转到 templates的页面
@Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/home").setViewName("home");
        registry.addViewController("/").setViewName("home");
        registry.addViewController("/hello").setViewName("hello");
        registry.addViewController("/login").setViewName("login");
    }

}
4:配置 Spring Security
@EnableWebSecurity 注解
    使得 SpringMVC 集成了 Spring Security 的 web 安全支持。
WebSecurityConfig 继承配置类 WebSecurityConfigurerAdapter,
    重写了其中的特定方法,用于自定义 Spring Security 配置。

configure(HttpSecurity) 
定义了哪些 URL 路径应该被拦截,如字面意思所描述
”/“, “/home” 允许所有人访问,
”/login” 作为登录入口,也被允许访问,
“/hello” 则需要登陆后才可以访问。

configureGlobal(AuthenticationManagerBuilder) 
在内存中配置一个用户,admin/admin 分别是用户名和密码,这个用户拥有 USER 角色。
@Configuration
@EnableWebSecurity 
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { 
    @Override
   
    protected void configure(HttpSecurity http) throws Exception {
        http 
            .authorizeRequests()
                .antMatchers("/", "/home").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
            .logout()
                .permitAll();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
       // auth 
         //   .inMemoryAuthentication()
           //     .withUser("admin").password("admin").roles("USER");
                
      //这是因为Spring boot 2.0.3引用的security 依赖是 spring security 5.X版本,
      //页面提交时候,密码以明文的方式进行匹配。
      auth       
            .inMemoryAuthentication()
                .passwordEncoder(new MyPasswordEncoder())                       
                .withUser("admin").password("admin").roles("USER");
    }
}
5:创建登录页面
这个 Thymeleaf 模板提供了一个用于提交用户名和密码的表单,
name=”username”,name=”password” 是默认的表单值,并发送到“/ login”。 

在默认配置中,Spring Security 提供了一个拦截该请求并验证用户的过滤器。

注意:为Spring Secuirty 自带的
如果验证失败,该页面将重定向到“/ login?error”,并显示相应的错误消息。
当用户选择注销,请求会被发送到“/ login?logout”。

 src/main/resources/templates/login.html
<!DOCTYPE html>
<!-- login -->
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
    <head>
        <title>Spring Security Example </title>
    </head>
    <body>
        <div th:if="${param.error}">
            Invalid username and password.
        </div>
        <div th:if="${param.logout}">
            You have been logged out.
        </div>
        <form th:action="@{/login}" method="post">
            <div><label> User Name : <input type="text" name="username"/> </label></div>
            <div><label> Password: <input type="password" name="password"/> </label></div>
            <div><input type="submit" value="Sign In"/></div>
        </form>
    </body>
</html>
6:改动hello页面。
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
    <head>
        <title>Hello World!</title>
    </head>
    <body>
    <!-- remoteUser 可以获取用户名 -->
        <h1 th:inline="text">Hello [[${#httpServletRequest.remoteUser}]]!</h1>
        <form th:action="@{/logout}" method="post">
            <input type="submit" value="Sign Out"/>
        </form>
    </body>
</html>

项目连接

请配合项目代码食用效果更佳:
项目地址:
https://github.com/hesuijin/hesuijin-study-project
Git下载地址:
https://github.com.cnpmjs.org/hesuijin/hesuijin-study-project.git

security 项目模块下  securitySoundCodeDemo包

相关文章

网友评论

      本文标题:Spring Security 2 --Guides(文末有项目

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