栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Spring Boot(十三)--------集成SpringSecurity

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring Boot(十三)--------集成SpringSecurity

Spring Boot(十三)--------集成SpringSecurity 22、SpringSecurity 22.1 安全简介

在 Web 开发中,安全一直是非常重要的一个方面。安全虽然属于应用的非功能性需求,但是应该在应用开发的初期就考虑进来。如果在应用开发的后期才考虑安全的问题,就可能陷入一个两难的境地:一方面,应用存在严重的安全漏洞,无法满足用户的要求,并可能造成用户的隐私数据被攻击者窃取;另一方面,应用的基本架构已经确定,要修复安全漏洞,可能需要对系统的架构做出比较重大的调整,因而需要更多的开发时间,影响应用的发布进程。因此,从应用开发的第一天就应该把安全相关的因素考虑进来,并在整个应用的开发过程中市面上存在比较有名的:Shiro,Spring Security这里需要阐述一下的是,每一个框架的出现都是为了解决某一问题而产生了,那么Spring Security框架的出现是为了解决什么问题呢Spring Security官网地址:Spring Security帮助文档:Spring Security ReferenceSpring Security是一个功能强大且高度可定制的身份验证和访问控制框架。它实际上是保护基于spring的应用程序的标准Spring Security是一个框架,侧重于为Java应用程序提供身份验证和授权。与所有Spring项目一样,Spring安全性的真正强大之处在于它可以轻松地扩展以满足定制需求从官网的介绍中可以知道这是一个权限框架。想我们之前做项目是没有使用框架是怎么控制权限的?对于权限 一般会细分为功能权限,访问权限,和菜单权限。代码会写的非常的繁琐,冗余怎么解决之前写权限代码繁琐,冗余的问题,一些主流框架就应运而生而Spring Scecurity就是其中的一种Spring 是一个非常流行和成功的 Java 应用开发框架。Spring Security 基于 Spring 框架,提供了一套 Web 应用安全性的完整解决方案。一般来说,Web 应用的安全性包括用户认证(Authentication)和用户授权(Authorization)两个部分

用户认证指的是验证某个用户是否为系统中的合法主体,也就是说用户能否访问该系统。用户认证一般要求用户提供用户名和密码。系统通过校验用户名和密码来完成认证过程用户授权指的是验证某个用户是否有权限执行某个操作。在一个系统中,不同用户所具有的权限是不同的。比如对一个文件来说,有的用户只能进行读取,而有的用户可以进行修改。一般来说,系统会为不同的用户分配不同的角色,而每个角色则对应一系列的权限 对于上面提到的两种应用情景,Spring Security 框架都有很好的支持

在用户认证方面,Spring Security 框架支持主流的认证方式,包括 HTTP 基本认证、HTTP 表单验证、HTTP 摘要认证、OpenID 和 LDAP 等在用户授权方面,Spring Security 提供了基于角色的访问控制和访问控制列表(Access Control List,ACL),可以对应用中的领域对象进行细粒度的控制 22.2. 实验环境搭建

新建一个初始的Spring Boot项目

导入静态资源

导入thymeleaf依赖


    org.springframework.boot
    spring-boot-starter-thymeleaf

新建RouterController,测试导入的新页面跳转

@Controller
public class RouterController {

    @RequestMapping({"/","/index"})
    public String index(){
        return "index";
    }

    @RequestMapping("/toLogin")
    public String toLogin(){
        return "view/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;
    }
}

首页

登录

详情页

22.3 认识SpringSecurity

Spring Security是针对Spring项目的安全框架,也是Spring Boot底层安全模块默认的技术选型,他可以实现强大的Web安全控制,对于安全控制,我们仅需要引入spring-boot-starter-security模块,进行少量的配置,即可实现强大的安全管理

记住几个类:

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

Spring Security的两个主要目标是 “认证” 和 “授权”(访问控制)

“认证”(Authentication)

身份验证是关于验证您的凭据,如用户名/用户ID和密码,以验证您的身份身份验证通常通过用户名和密码完成,有时与身份验证因素结合使用

“授权” (Authorization)

授权发生在系统成功验证您的身份后,最终会授予您访问资源(如信息,文件,数据库,资金,位置,几乎任何内容)的完全权限这个概念是通用的,而不是只在Spring Security 中存在 22.4 认证和授权

目前的测试环境,可以访问任意页面,使用Spring Security增加上认证和授权的功能引入Spring Security依赖


   org.springframework.boot
   spring-boot-starter-security

编写Spring Security配置类,参考官网或帮助文档,重写configure(HttpSecurity http)方法

//授权
//开启web的security模式
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    //链式编程
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //首页所有人都可以访问,功能页只有对应有权限的人才能访问
        http.authorizeHttpRequests()
                //首页所有人可以访问
                .antMatchers("/").permitAll()
                //只有vip1可以访问level1下的页面
                .antMatchers("/level1/**").hasRole("vip1")
                //只有vip2可以访问level2下的页面
                .antMatchers("/level2/**").hasRole("vip2")
                //只有vip3可以访问level3下的页面
                .antMatchers("/level3/**").hasRole("vip3");
    }
}

此时再次访问,发现会报错误403,因为没有登录时,没有权限开启没有权限默认跳转到登录页面http.formLogin();加这一句即可

//授权
//开启web的security模式
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    //链式编程
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        ...

        //没有权限默认会跳转到登录页面
        http.formLogin();
    }
}

测试,发现在没有权限的时候,点击访问会跳转到登录页面

查看刚才登录页的注释信息,仿写configure(AuthenticationManagerBuilder auth)方法

//认证
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //正常情况下,这些数据应该在数据库中读取
        auth.inMemoryAuthentication()
                //用户zzz 密码为123456,可以访问vip1和vip2
                .withUser("zzz").password("123456").roles("vip1","vip2")
                .and()
                .withUser("mmm").password("123456").roles("vip1","vip2","vip3")
                .and()
                .withUser("ttt").password("123456").roles("vip1");
    }

测试,会报错500,IllegalArgumentException: There is no PasswordEncoder mapped for the id "null"

原因时,需要将前端传过来的密码进行某种方式加密,否则无法登录

//认证
    //密码编码:PasswordEncoder
    //在Spring Security5.0+中,新增了很多加密方式
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //正常情况下,这些数据应该在数据库中读取auth.jdbcAuthenticaiton
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                //用户zzz 密码为123456,可以访问vip1和vip2
                .withUser("zzz").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2")
            	//继续写
                .and()
                .withUser("mmm").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
                .and()
                .withUser("ttt").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
    }
}

测试成功 22.5 权限控制和注销

开启自动配置的注销功能,http.logout()方法

//授权
    //链式编程
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        ...
        
        //注销,开启了注销功能
        http.logout();
    }

在前端页面增加注销按钮


     注销

测试成功,点击注销会跳转到登录页面

如果想要注销后,仍旧可以跳转到首页,该如何处理?

添加logoutSuccessUrl()方法,跳转到首页

//授权
    //链式编程
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        ...

        //注销,开启了注销功能 ,并跳转到首页
        http.logout().logoutSuccessUrl("/");
    }

用户没有登录时,导航栏只显示登录按钮,用户登录后,导航栏显示登录的用户信息及注销按钮。zzz用户访问时,只有vip1和vip2的权限,如何不显示vip3呢?我们需要结合themeleaf中的一些功能,导入thymeleaf和springsecurity整合包的依赖Spring Boot2.0.9之前使用整合包4(springsecurity4),2.0.9之后使用整合包5(springsecurity5)


   org.thymeleaf.extras
   thymeleaf-extras-springsecurity5
   3.0.4.RELEASE

修改前端页面,导入命名空间


修改导航栏,增加认证判断


测试成功

点击注销后,不能直接跳转到首页,需要确认一下,如何修改?

该方法默认防止CDRF跨站请求伪造,因为会产生安全问题,将请求改为post表单提交,在spring security中关闭CSRF功能http.csrf.disable()

//授权
    //链式编程
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        ...
        //防止网站攻击 关闭csrf
        http.csrf().disable();
        //注销,开启了注销功能 并跳转到首页
        http.logout().logoutSuccessUrl("/");
    }

测试,点击注销按钮后,直接退出到首页 22.6 记住我

一般来说,会有一个记住密码的功能,该如何实现?添加http.remember()方法

//授权
    //链式编程
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        ...
        //开启记住我功能:cookie默认保存2周
        http.rememberMe();
    }

测试,发现关闭浏览器后,用户仍然存在可以查看浏览器的cookie,发现注销的时候,spring security帮助我们删除了这个cookie 22.7 定制登录页

现在的登录页面是spring security默认的,如何使用自己写的Login页面?在登录页配置后面指定loginpage

//授权
    //链式编程
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        ...
        //没有权限默认会跳转到登录页面
        //跳转到指定的登录页
        http.formLogin().loginPage("/toLogin");
    }

修改前端代码

 

登录的时候,这些信息发送到哪里也需要配置,login.html配置提交请求及方式,必须为post方式

这个请求提交上来,还需要验证处理,怎么做?

查看formLogin()方法的源码,需要配置接收登录的用户名和密码的参数

//授权
    //链式编程
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        ...
        http.formLogin().loginPage("/toLogin").usernameParameter("user").passwordParameter("pwd");
    }

在登录页添加“记住我“的选择框

 记住我

后端验证处理,添加记住我选择框的名字,使用rememberMeParameter()方法

//授权
    //链式编程
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        ...
        //开启记住我功能 :cookie默认保存2周
        http.rememberMe().rememberMeParameter("remember");
    }

测试成功 22.8 完整的配置代码

SecurityConfig完整代码

//开启web的security模式
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    //授权
    //链式编程
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //首页所有人都可以访问,功能页只有对应有权限的人才能访问
        http.authorizeHttpRequests()
                //首页所有人可以访问
                .antMatchers("/").permitAll()
                //只有vip1可以访问level1下的页面
                .antMatchers("/level1/**").hasRole("vip1")
                //只有vip2可以访问level2下的页面
                .antMatchers("/level2/**").hasRole("vip2")
                //只有vip3可以访问level3下的页面
                .antMatchers("/level3/**").hasRole("vip3");

        //没有权限默认会跳转到登录页面
        //跳转到指定的登录页
        //配置接收的用户名密码的对应参数名
        http.formLogin().loginPage("/toLogin").usernameParameter("username").passwordParameter("password");

        //防止网站攻击 关闭csrf
        http.csrf().disable();
        //注销,开启了注销功能 并跳转到首页
        http.logout().logoutSuccessUrl("/");

        //开启记住我功能 :cookie默认保存2周
        http.rememberMe().rememberMeParameter("remember");
    }

    //认证
    //密码编码:PasswordEncoder
    //在Spring Security5.0+中,新增了很多加密方式
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //正常情况下,这些数据应该在数据库中读取
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                //用户zzz 密码为123456,可以访问vip1和vip2
                .withUser("zzz").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2")
                .and()
                .withUser("mmm").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
                .and()
                .withUser("ttt").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/754025.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号