Spring Security的简单使用

目录什么是Spring SecuritySpring Security测试SpringSecurity的使用静态资源一些其他的小东西

什么是Spring Security

    Spring Security是一个功能强大且高度可定制的身份验证和访问控制框架。它实际上是保护基于spring的应用程序的标准。 Spring Security是一个框架,侧重于为Java应用程序提供身份验证和授权。与所有Spring项目一样,Spring安全性的真正强大之处在于它可以轻松地扩展以满足定制需求 在用户认证方面,Spring Security 框架支持主流的认证方式,包括 HTTP 基本认证、HTTP 表单验证、HTTP 摘要认证、OpenID 和 LDAP 等。在用户授权方面,Spring Security 提供了基于角色的访问控制和访问控制列表(Access Control List,ACL),可以对应用中的领域对象进行细粒度的控制。

Spring Security测试

前期准备

    新建一个springboot项目,导入web模板和thymeleaf模板 导入静态资源

    关闭thymeleaf缓存spring.thymeleaf.cache=false 先创建一个TestController来测试一下项目是否搭建成功
package com.example.controller;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;@Controllerpublic class TestController {    @RequestMapping("/")    public String index(){        return "index";    }    @RequestMapping("/toLogin")    public String toLogin(){        return "views/login";    }    @RequestMapping("/level1/{id}")    public String level1(@PathVariable("id") int id){        return "views/level1/"+id;    }    @RequestMapping("/level2/{id}")    public String level2(@PathVariable("id") int id){        return "views/level2/"+id;    }    @RequestMapping("/level3/{id}")    public String level3(@PathVariable("id") int id){        return "views/level3/"+id;    }}

SpringSecurity的使用

引入spring-boot-starter-security模块

 <dependency>       <groupId>org.springframework.boot</groupId>       <artifactId>spring-boot-starter-security</artifactId></dependency>

认识SpringSecurity的几个重要的类

WebSecurityConfigurerAdapter:自定义Security策略 AuthenticationManagerBuilder:自定义认证策略 @EnableWebSecurity:开启WebSecurity模式

SpringSecurity—授权(认真看代码和注释)

//授权    @Override    protected void configure(HttpSecurity http) throws Exception {        http.authorizeRequests().antMatchers("/").permitAll() //首页所有人可以访问                .antMatchers("/level1/**").hasRole("vip1")   //level1下的页面,VIP1可以访问                .antMatchers("/level2/**").hasRole("vip2")                .antMatchers("/level3/**").hasRole("vip3");        //开启自动配置的登录功能,        //即,没有登录的时候,除了首页,其他页面都访问不了,这时候,你访问其他页面的时候,        //它直接跳转到它内置的登陆页面,让你登录 http.formLogin();        http.formLogin().loginPage("/toLogin");//自定义登录页,将自定义的登录页替换掉内置的登录页        //用来处理用户登录提交的表单        http.formLogin().usernameParameter("username")                .passwordParameter("password")                .loginPage("/toLogin")                .loginProcessingUrl("/login");        //开启自动配置的注销的功能        // /logout 注销请求  http.logout();        http.csrf().disable();//关闭csrf功能:跨站请求伪造,默认只能通过post方式提交logout请求        http.logout().logoutSuccessUrl("/");//注销成功就返回首页        //开启记住我功能 http.rememberMe();        http.rememberMe().rememberMeParameter("remember");//在自定义登录页添加 记住我    }

SpringSecurity—认证(认真看代码和注释)

    //认证    @Override    protected void configure(AuthenticationManagerBuilder auth) throws Exception {        /*            auth.inMemoryAuthentication().withUser("xiaomi").password("123").roles("vip1")            这样写是不行的,会出现500错误。                原因:密码没有加密            Spring security 5.0中新增了多种加密方式,也改变了密码的格式。            要想我们的项目还能够正常登陆,需要修改一下configure中的代码。我们要将前端传过来的密码进行某种方式加密            spring security 官方推荐的是使用bcrypt加密方式。            这里通过 passwordEncoder(new BCryptPasswordEncoder())  的方式进行加密       */        // 在内存中定义认证的规则        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())                .withUser("xiaolong").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1")                .and()                .withUser("xiaomi").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2")                .and()                .withUser("xiaohu").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3");        //在jdbc中定义认证的规则        //auth.jdbcAuthentication()    }

启动测试

静态资源

login.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="external nofollow"  rel="external nofollow"  rel="stylesheet"></head><body><!--主容器--><div class="ui container">    <div class="ui segment">        <div style="text-align: center">            <h1 class="header">登录</h1>        </div>        <div class="ui placeholder segment">            <div class="ui column very relaxed stackable grid">                <div class="column">                    <div class="ui form">                        <form th:action="@{/login}" method="post">                            <div class="field">                                <label>Username</label>                                <div class="ui left icon input">                                    <input type="text" placeholder="Username" name="username">                                    <i class="user icon"></i>                                </div>                            </div>                            <div class="field">                                <label>Password</label>                                <div class="ui left icon input">                                    <input type="password" name="password">                                    <i class="lock icon"></i>                                </div>                            </div>                            <div class="field">                                <input type="checkbox" name="remember">记住我                            </div>                            <input type="submit" class="ui blue submit button"/>                        </form>                    </div>                </div>            </div>        </div>        <div style="text-align: center">            <div class="ui label">                </i>注册            </div>            <br><br>        </div>        <div class="ui segment" style="text-align: center">            <h3>Spring Security</h3>        </div>    </div></div><script th:src="@{/js/jquery-3.1.1.min.js}"></script><script th:src="@{/js/semantic.min.js}"></script></body></html>

index.html

<!DOCTYPE html><html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/extras/spring-security"><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="external nofollow"  rel="external nofollow"  rel="stylesheet">    <link th:href="@{/css/mystyle.css}" rel="external nofollow"  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}" rel="external nofollow" >首页</a>            <!--登录注销-->            <div class="right menu">                <!--未登录-->                <!--sec:authorize="!isAuthenticated() 未认证即未登录-->                <div sec:authorize="!isAuthenticated()">                    <a class="item" th:href="@{/toLogin}" rel="external nofollow" >                        <i class="address card icon"></i> 登录                    </a>                </div>                <!--已登录-->                <!--sec:authorize="!isAuthenticated() 已认证即已经有用户登录-->                <div sec:authorize="isAuthenticated()">                    <a class="item">                        <i class="address card icon"></i>                        用户名:<span sec:authentication="principal.username"></span>                        角色:<span sec:authentication="principal.authorities"></span>                    </a>                </div>                <!--注销-->                <div sec:authorize="isAuthenticated()">                    <a class="item" th:href="@{/logout}" rel="external nofollow" >                        <i class="sign-out icon"></i> 注销                    </a>                </div>            </div>        </div>    </div>    <div class="ui segment" style="text-align: center">        <h3>Spring Security</h3>    </div>    <div>        <br>        <div class="ui three column stackable grid">            <!-- sec:authorize="hasRole('vip1') 永拥有vip1权限的人才能看到 -->            <div class="column" sec:authorize="hasRole('vip1')">                <div class="ui raised segment">                    <div class="ui">                        <div class="content">                            <h5 class="content">Level 1</h5>                            <hr>                            <div><a th:href="@{/level1/1}" rel="external nofollow" ><i class="bullhorn icon"></i> Level-1-1</a></div>                            <div><a th:href="@{/level1/2}" rel="external nofollow" ><i class="bullhorn icon"></i> Level-1-2</a></div>                            <div><a th:href="@{/level1/3}" rel="external nofollow" ><i class="bullhorn icon"></i> Level-1-3</a></div>                        </div>                    </div>                </div>            </div>            <!-- sec:authorize="hasRole('vip2') 永拥有vip2权限的人才能看到 -->            <div class="column" sec:authorize="hasRole('vip2')">                <div class="ui raised segment">                    <div class="ui">                        <div class="content">                            <h5 class="content">Level 2</h5>                            <hr>                            <div><a th:href="@{/level2/1}" rel="external nofollow" ><i class="bullhorn icon"></i> Level-2-1</a></div>                            <div><a th:href="@{/level2/2}" rel="external nofollow" ><i class="bullhorn icon"></i> Level-2-2</a></div>                            <div><a th:href="@{/level2/3}" rel="external nofollow" ><i class="bullhorn icon"></i> Level-2-3</a></div>                        </div>                    </div>                </div>            </div>            <!-- sec:authorize="hasRole('vip3') 永拥有vip3权限的人才能看到 -->            <div class="column" sec:authorize="hasRole('vip3')">                <div class="ui raised segment">                    <div class="ui">                        <div class="content">                            <h5 class="content">Level 3</h5>                            <hr>                            <div><a th:href="@{/level3/1}" rel="external nofollow" ><i class="bullhorn icon"></i> Level-3-1</a></div>                            <div><a th:href="@{/level3/2}" rel="external nofollow" ><i class="bullhorn icon"></i> Level-3-2</a></div>                            <div><a th:href="@{/level3/3}" rel="external nofollow" ><i class="bullhorn icon"></i> Level-3-3</a></div>                        </div>                    </div>                </div>            </div>        </div>    </div>    </div><script th:src="@{/js/jquery-3.1.1.min.js}"></script><script th:src="@{/js/semantic.min.js}"></script></body></html>

一些其他的小东西

    如果你在测试TestController之前已经提前把spring-boot-starter-security这个依赖导入,那么你请求首页的时候,程序会自动跳转到登录页面,任何请求都会被拦截,停留在登录页面 如果用户还没有登录,你只能看到首页,你点击首页的任何界面的请求都会跳转到默认的登录页面。然后,你通过你认证过的用户进行登录,登录成功后会返回你之前点击的那个界面的请求。也就是说,本来界面有一个/level1/1.html你点击它,没登录,会直接跳转到默认的登录界面,登陆成功后,会返回/level1/1.html,而不是返回首页,这是默认的 分析一下自定义登录页的实现

以上就是Spring Security的简单使用的详细内容,更多关于Spring Security的使用的资料请关注其它相关文章!

深重如溺入蓝色的海洋,无法呼吸。

Spring Security的简单使用

相关文章:

你感兴趣的文章:

标签云: