集成Spring Security安全问题的基本使用

Spring Security(安全)

在Web开发中,安全第一位,一般是实现Web安全问题使用过滤器,拦截器等,对功能性需求并没有那么高,在做网站之初,安全问题应该是在设计时就应该考虑进去,若整个网站的架构已经确认好了再去考虑Web的安全问题,那么将会产生许多的安全漏洞,和隐私泄露的问题。目前市面上流行的安全框架又shiro(在后面也会出有笔记)、SpringSecurity等,它两看似名字不一样,但底层原理都是类似的,此文讲述的时Spring Security的基本用法。

Spring Security是一个功能强大且高度可定制的身份验证和访问控制框架,侧重于为Java应用程序提供身份验证和授权。与所有Spring项目一样,Spring安全性的真正强大之处在于它可以轻松地扩展以满足定制需求

Spring Security 基于 Spring 框架,提供了一套 Web 应用安全性的完整解决方案。一般来说,Web 应用的安全性包括用户认证(Authentication)和用户授权(Authorization)两个部分。用户认证指的是验证某个用户是否为系统中的合法主体,也就是说用户能否访问该系统。用户认证一般要求用户提供用户名和密码。系统通过校验用户名和密码来完成认证过程。用户授权指的是验证某个用户是否有权限执行某个操作。在一个系统中,不同用户所具有的权限是不同的。比如对一个文件来说,有的用户只能进行读取,而有的用户可以进行修改。一般来说,系统会为不同的用户分配不同的角色,而每个角色则对应一系列的权限。

简介

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

记住几个类:

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

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

  • "认证”(Authentication) .
  • "授权”(Authorization)

这个概念是通用的,而不是只在Spring Security中存在。

1、用户认证和授权

首先导入相关的jar包和一些前端静态资源

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

在这里插入图片描述

编写第一个用户授权认证类

package com.cetus.config;


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;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    //链式编程
    //授权
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //首页所有人可以访问,功能页只有对应有权限的人才能访问
        //请求授权的规则
        http.authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("vip1")
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3");
        //没有权限会跳转到登录页面
        http.formLogin();
    }
          //认证,springboot 2.1.x可以直接使用,这里一般是从数据库中获得
        //密码编码:PasswordEncoder
          // 在Spring Security 5+ 新增了很多加密的方法 官方推荐的是使用bcrypt加密方式。
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("lisiqiang").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
                .and()
                .withUser("leizhicheng").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2")
                .and()
                .withUser("hujiangnan").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
    }
}

登录进去就能有自动拦截效果
在这里插入图片描述

2、注销及权限控制

注销功能在Security中很简单,只需在授权方法里加入一行代码即可

  //注销,开启注销功能,跳转到首页
        http.logout().logoutSuccessUrl("/");
       // http.logout().deleteCookies("remove").invalidateHttpSession(true);

点进logout()的源码注释,发现许多默认的配置,其中点击注销按钮后自动跳转到logout页面,并且也可使用链式编程来清除缓存和cookie

The following customization to log out when the URL "/custom-logout" is invoked. Log out will remove the cookie named "remove", not invalidate the HttpSession, clear the SecurityContextHolder, and upon completion redirect to "/logout-success".
	   @Configuration
	   @EnableWebSecurity
	   public class LogoutSecurityConfig {
	  
	   	@Bean
	   	public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
	   		http.authorizeRequests().antMatchers("/**").hasRole("USER").and().formLogin()
	   				.and()
	   				// sample logout customization
	   				.logout().deleteCookies("remove").invalidateHttpSession(false)
	   				.logoutUrl("/custom-logout").logoutSuccessUrl("/logout-success");
	   		return http.build();
	   	}
	  
	   	@Bean
	   	public UserDetailsService userDetailsService() {
	   		UserDetails user = User.withDefaultPasswordEncoder()
	   			.username("user")
	   			.password("password")
	   			.roles("USER")
	   			.build();
	   		return new InMemoryUserDetailsManager(user);
	   	}
	   }
	   
Returns:
the LogoutConfigurer for further customizations
Throws:
Exception

在前端thymeleaf模板引擎中,我们加一个注销的标签,注销图标是从国外的Semantic UI (semantic-ui.com)引用过来,只需将class里的名字修改即可

<a class="item" th:href="@{/logout}">
    <i class="paper plane icon"></i> 注销
</a>

我们现在又来一个需求:用户没有登录的时候,导航栏上只显示登录按钮,用户登录之后,导航栏可以显示登录的用户信息及注销按钮!还有就是,比如leizhicheng这个用户,它只有 vip1,vip2功能,那么登录则只显示这两个功能,而vip3的功能菜单不显示!这个就是真实的网站情况了!该如何做呢?

我们需要结合thymeleaf中的一些功能

首先导入maven的依赖:注意导入5这个版本它的适配性高些,不然后续会出现很多不兼容的问题

<!-- https://mvnrepository.com/artifact/org.thymeleaf.extras/thymeleaf-extras-springsecurity4 -->
<dependency>
    <groupId>org.thymeleaf.extras</groupId>
    <artifactId>thymeleaf-extras-springsecurity5</artifactId>
    <version>3.0.4.RELEASE</version>
</dependency>

导入命名空间

<html lang="en" xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5">
<head>

修改导航栏,增加一些判断是否呈现出来,而且在用户登录后,右边栏也会显示当前用户信息

<!--登录注销-->
<div class="right menu">
    <!--如果未登录,判断为用户未注册-->
    <div sec:authorize="!isAuthenticated()">
        <a class="item" th:href="@{/toLogin}">
            <i class="address card icon"></i> 登录
        </a>
    </div>
    <!--如果登录:用户名,注销-->
    <div sec:authorize="isAuthenticated()">
        <a class="item" >
         用户名:<span sec:authentication="name"></span>
            角色:<span sec:authentication="principal.authorities"></span>
        </a>
    </div>
    <div sec:authorize="isAuthenticated()">
    <a class="item" th:href="@{/logout}">
        <i class="paper plane icon"></i> 注销
    </a>
    </div>
</div>

重启看看我们想要的效果,若出现了404错误,可能是默认开启了csrf跨站请求伪造,而产生的安全问题,我们可以将表单请求改为Post请求,或者在Spring Security中关闭csrf功能

//注销,开启了注销功能,跳到首页
http.csrf().disable();//关闭csrf功能,登出失败的原因

现在重启之后我们就能看到登录和注销按钮就不会同时出现,从而达到了目的需求

接下来我们再完成角色模块的权限功能,同样,特定登录网站的人,通过角色的不同,所展示出来的功能也不同

<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}"><i class="bullhorn icon"></i> Level-1-1</a></div>
                <div><a th:href="@{/level1/2}"><i class="bullhorn icon"></i> Level-1-2</a></div>
                <div><a th:href="@{/level1/3}"><i class="bullhorn icon"></i> Level-1-3</a></div>
            </div>
        </div>
    </div>
</div>

<div class="column"sec:authorize="hasRole('vip2')">
    <div class="ui raised segment">
        <div class="ui">
            <div class="content"sec:authorize="hasRole('vip1')">
                <h5 class="content">Level 2</h5>
                <hr>
                <div><a th:href="@{/level2/1}"><i class="bullhorn icon"></i> Level-2-1</a></div>
                <div><a th:href="@{/level2/2}"><i class="bullhorn icon"></i> Level-2-2</a></div>
                <div><a th:href="@{/level2/3}"><i class="bullhorn icon"></i> Level-2-3</a></div>
            </div>
        </div>
    </div>
</div>

<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}"><i class="bullhorn icon"></i> Level-3-1</a></div>
                <div><a th:href="@{/level3/2}"><i class="bullhorn icon"></i> Level-3-2</a></div>
                <div><a th:href="@{/level3/3}"><i class="bullhorn icon"></i> Level-3-3</a></div>
            </div>
        </div>
    </div>
</div>

现在就搞定了控制权限了!

3、记住我和首页定制

现在一些网站都会有浏览器自动记住功能,就是一些记住密码的功能,一般要是学习javaWeb时会通过session自己设置一些参数,在Spring Security中可以直接使用

开启记住我功能

//定制请求的授权规则
@Override
protected void configure(HttpSecurity http) throws Exception {
//。。。。。。。。。。。
   //记住我
   http.rememberMe();
}

接下来重启项目,在登录时会出现一个记住我的功能,注意:这里的记住我功能和登录的页面时Spring Security自带的。打开页面检查功能,发现自动生成了Cookis和缓存,查看时间是默认保持两周的有效时间,点击注销时,也自动帮我们删除了cookie和缓存

上面说了此时的登录页面不是我们自己的,现在需要自定义我们自己的登录界面,在刚才的配置后面加入指定的loginpage

//没有权限会跳转到登录页面
http.formLogin().loginPage("/toLogin");

在前端也要做出相应的修改(查看formLogin源码发现后面还跟有.loginProcessingUrl(“/authentication/login/process”);在这里可以修改成与前端一样的请求页面,而且/toLogin还能继续生效)

<a class="item" th:href="@{/toLogin}">
    <i class="address card icon"></i> 登录
</a>

来到现在的自定义登录页面,我们也需要将表单的提交位置修改一下

<form th:action="@{/toLogin}" method="post">
   <div class="field">
       <label>Username</label>
       <div class="ui left icon input">
           <input type="text" placeholder="Username" name="user">
           <i class="user icon"></i>
       </div>
   </div>
   <div class="field">
       <label>Password</label>
       <div class="ui left icon input">
           <input type="password" name="pwd">
           <i class="lock icon"></i>
       </div>
   </div>
   <input type="submit" class="ui blue submit button"/>
</form>

这个请求提交上来我们还需做一些验证处理,在实际业务中经常出现的问题,就是前端程序员和后端程序员在属性的定义上可能出现歧义,比如前端是定义pwd,后端又是password,比较不好处理。又来到formLogin()方法的源码里

@Bean
	   	public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
	   		http.authorizeRequests().antMatchers("/**").hasRole("USER").and().formLogin()
	   				.usernameParameter("username") // default is username
	   				.passwordParameter("password") // default is password
	   				.loginPage("/authentication/login") // default is /login with an HTTP get
	   				.failureUrl("/authentication/login?failed") // default is /login?error
	   				.loginProcessingUrl("/authentication/login/process"); // default is /login@Bean

这里默认从前端来到name的名字只能为user、password才能生效被拿到,此时也可以修改

http.formLogin()
  .usernameParameter("username")
  .passwordParameter("password")

继续在登录页面增加记住我的多选框

<div class="field">
   <input type="checkbox" name="rememberMe" >记住我
</div>

后端验证处理!

//开启记住我功能
http.rememberMe().rememberMeParameter("rememberMe");

成功展示!

完整配置代码

package com.cetus.config;


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;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    //链式编程
    //授权
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //首页所有人可以访问,功能页只有对应有权限的人才能访问
        //请求授权的规则
        http.authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("vip1")
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3");
        //没有权限会跳转到登录页面
        http.formLogin().loginPage("/toLogin");
        //注销,开启了注销功能,跳到首页
        http.csrf().disable();//关闭csrf功能,登出失败的原因
        //注销,开启注销功能,跳转到首页
        http.logout().logoutSuccessUrl("/");
       // http.logout().deleteCookies("remove").invalidateHttpSession(true);

        //开启记住我功能
        http.rememberMe().rememberMeParameter("rememberMe");

    }
          //认证,springboot 2.1.x可以直接使用
        //密码编码:PasswordEncoder
          // 在Spring Security 5+ 新增了很多加密的方法
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("lisiqiang").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
                .and()
                .withUser("leizhicheng").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2")
                .and()
                .withUser("hujiangnan").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
    }
}

此文为跟随狂神学习笔记,记录学习过程,如有逻辑错误或理论有误,欢迎在评论区指正。如果觉得有用,一键三连更是对我最大的鼓励💬🥂🥂

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值