SpringBoot使用篇---SpringBoot整合springSecurity

在这里插入图片描述

目录:

   前言
   SpringBoot整合SpringSecurity
   总结
   
分享与交流html

前言

   安全是项目运行的重要保障,每个项目在公测以前都会进行严格的认证和受权,阻挡恶意请求,保护项目安全。尽管如此,咱们依然有时候能听到某某公司数据泄露,某某公司有重大Bug,因此安全验证就变得愈来愈重要,是咱们在项目中须要考虑的重要因素。
   Java领域经常使用的安全框架有Shiro和SpringBoot。Shiro拥有轻量级的特性从而被普遍使用,但它是第三方框架;Spring Security是一个相对重量级的安全框架,经过名字咱们应该也能看到,它是Spring官方的框架,所以在整合方面要占有必定的优点,并且它的功能比Shiro强大些,只要Shiro能实现通常它都能实现。同时SpringBoot提供了自动化配置,作到了开箱即用,所以Spring Security相对来讲是Java领域安全框架的最优选择之一。java

SpringBoot整合SpringSecurity

  具体步骤以下👇
(1)SpringBoot工程如何搭建能够参考SpringBoot框架搭建
(2)引入SpringBoot相关依赖web

<parent>
	        <groupId>org.springframework.boot</groupId>
	        <artifactId>spring-boot-starter-parent</artifactId>
	        <version>2.2.4.RELEASE</version>
	        <relativePath/> <!-- lookup parent from repository --> </parent>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
<dependency>
            <groupId>org.yaml</groupId>
            <artifactId>snakeyaml</artifactId>
            <version>1.23</version>
        </dependency>

(3)引入SpringSecurity依赖spring

<dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>5.1.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>5.1.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-core</artifactId>
            <version>5.1.5.RELEASE</version>
        </dependency>

(4)配置SpringBoot配置文件数据库

#注意每一个属性名和属性值之间至少一个空格,注释使用#不是//
spring:
  thymeleaf:
    prefix: classpath:/templates/ #前缀
    suffix: .html #后缀
    servlet:
      content-type: text/html #在请求中,客户端告诉服务端实际请求的内容
                              #在响应中,服务端告诉请求端实际响应的内容
    encoding: utf-8 #设置编码格式
    mode: HTML  #校验HTML格式
    cache: false #关闭缓存,在开发过程当中可当即看到修改后的结果

(5)建立Handler缓存

@Controller
@RequestMapping("security")
public class SecurityController {

    @RequestMapping("add")
    public String add(){
        return "add";
    }

    @RequestMapping("update")
    public String update(){
        return "update";
    }

    @RequestMapping("find")
    public String find(){
        return "find";
    }

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

    @RequestMapping("error403")
    public String forbidden(){
        return "error403";
    }
    
    @RequestMapping("/login")
    public String login(){
        return "login";
    }

(6)建立相对应页面
index.html安全

<body>
<a href="/security/add">添加功能</a>
<a href="/security/update">修改功能</a>
<a href="/security/find">查询功能</a>
<a href="/security/delete">删除功能</a>
</body>

add.htmlmvc

<body>
添加功能页面
</body>

find.htmlapp

<body>
查找功能页面
</body>

delete.html框架

<body>
删除功能页面
</body>

update.html

<body>
删除功能页面
</body>

login.html

<body>
<form action="/login" method="post">
    用户名:<input type="text" name="userName"><br/>
    密码:<input type="password" name="password"><br/>
    <input type="submit" value="登陆">
</form>
</body>

(7)一个简单的mvc就完成了,咱们继续实现SpringSecurity
建立SpringSecurityConfig

@Configuration
@EnableWebSecurity //启动SpringSecurity过滤器链
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {


    //该方法做用是代替配置文件中配置的<security:authentication-manager>
    /* <security:authentication-manager>用于配置对用户输入密码进行加密并与数据库密码进行配对 */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //若是程序报错There is no PasswordEncoder mapped for the id "null",就将该段注释添加下边代码
        //或者在MyPasswordEncoder类上加一个@Component注解,使它成为一个Bean
        auth.inMemoryAuthentication().withUser("admin").password("123456").authorities("ADMIN_ADD","ADMIN_FIND");//自定义登陆用户用户名和密码并赋予一些权限

        //上边代码若是使程序报错,就更换如下代码,这个是使用了匿名内部类
        //auth.inMemoryAuthentication().passwordEncoder(new MyPasswordEncoder()).withUser("lxy").password("lxy").authorities("ADMIN_ADD","ADMIN_FIND");
    }

    /*该方法做用是代替配置文件中配置的<security:http>标签 <security:http> 用来配置拦截资源--拦截什么资源,须要什么样的身份进行访问 自定义spring security拦截器 权限不足的处理 ReadMe功能 */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests()
                    .antMatchers("/security/add").hasAuthority("ADMIN_ADD") //ADMIN_ADD身份用户可访问/security/add页面
                    .antMatchers("/security/find").hasAuthority("ADMIN_FIND")
                    .antMatchers("/security/update").hasAuthority("ADMIN_UPDATE")
                    .antMatchers("/security/delete").hasAuthority("ADMIN_DELETE")
                    .antMatchers("/login").permitAll() //login页面不拦截,任何权限均可访问login页面
                    .antMatchers("/**") //表明拦截全部的访问请求
                    .fullyAuthenticated()
                    .and()
                    .formLogin()  //登录页面是springSecurity默认的  .formLogin().loginPage("/login")自定义登录页面  也可设置为 .httpBasic()  登录页面是弹窗框
                    .and()
                    .csrf().disable(); //关闭跨站请求拦截
    }
}

(8)建立MyPasswordEncoder

@Component
public class MyPasswordEncoder implements PasswordEncoder {
    @Override
    public String encode(CharSequence charSequence) {
        return charSequence.toString();
    }

    @Override
    public boolean matches(CharSequence charSequence, String s) {
        return s.equals(charSequence.toString());
    }
}

(9)建立错误页面处理类ErrorPageConfig
   环境是基于SpringBoot2.0以上版本,如下版本是继承mbeddedServletContainerCustomizer

@Configuration
public class ErrorPageConfig implements ErrorPageRegistrar {


    @Override
    public void registerErrorPages(ErrorPageRegistry registry) {
        ErrorPage error403Page=new ErrorPage(HttpStatus.FORBIDDEN,"/error403");
        registry.addErrorPages(error403Page);
    }
}

(10)配置SpringBoot启动类

@SpringBootApplication
@MapperScan("cn.lxy.spring_boot1.repository")
public class SpringBoot1Application {

    public static void main(String[] args) {
        SpringApplication.run(SpringBoot1Application.class, args);
    }

}

(11)测试
   访问localhost:8080/index
在这里插入图片描述
   页面被拦截自动跳转到登录页面,登录页面是SpringSecurity默认的登录页面,也可自定义登录页面。
在这里插入图片描述
   帐号或密码输入错误,登录失败
在这里插入图片描述
   输入上边咱们设置好的admin/123456,进入localhost:8080/index
在这里插入图片描述
   访问添加功能查询功能
在这里插入图片描述
在这里插入图片描述
   访问修改功能删除功能
在这里插入图片描述
在这里插入图片描述

总结

   以上是SpringBoot整合SpringSecurity的简单使用,SpringSecurity还有不少须要学习的地方。相比于Shiro,Spring Security因其是Spring全家桶中的一员,所以能够和Spring应用无缝衔接,使用起来会更加方便,系统安全是项目运行的重中之重,使用Spring Security进行管理,能够对访问权限进行认证,从而提升项目的安全性。

分享与总结

   因为能力有限,博客总结不免有不足,还请大佬们不吝赐教😄