二十、Spring Boot 安全管理(Spring Security)

(一)、介绍

Spring Security是Spring 官方提供的一个高度自定义安全框架,是一种基于 Spring AOPServlet 过滤器的安全框架。
提供了声明式安全访问控制功能,减少了为系统安全而编写大量重复代码的工作。主要包含“认证”和“授权”(或者访问控制)两个核心功能。

官方文档

(二)、简单使用

1.创建Spring Boot项目

参考:Spring Boot项目创建(IDEA)

2.添加依赖

修改pox.xml文件。添加spring security相关依赖

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

3.启动项目测试

登录

注:

  • 默认登录账号user登录密码会打印在控制台
    登录密码
  • 默认账号信息可以通过项目配置文件(application.properties)修改:
spring.security.user.name=user
spring.security.user.password=password

(三)、自定义配置

1、用户信息实体类

  • 创建用户信息实体类
  • 实现接口UserDetails
    • 实现接口方法
 // 用户名
 String getUsername();
  // 用户密码
 String getPassword();
 // 获取用户权限
 Collection<? extends GrantedAuthority> getAuthorities();
 // 账户是否过期
 boolean isAccountNonExpired();
 // 账号是否锁定
 boolean isAccountNonLocked();
 // 凭证(密码)是否过期
 boolean isCredentialsNonExpired();
 // 账号是否启用
 boolean isEnabled();

注:在进行账号验证时只有 isAccountNonExpired()isAccountNonLocked()isCredentialsNonExpired()isEnabled()四项都为true时才能通过验证(没有这几个属性可以都设置默认返回true)。

2、创建配置文件

  • 新建类继承抽象类WebSecurityConfigurerAdapter并添加注解@Configuration
  • 重写configure方法,编写自定义登录信息认证逻辑。
示列代码:
package com.ikaros.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import java.io.PrintWriter;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 配置认证
        http.formLogin()
                // 哪个URL为登录页面
//                .loginPage("/login")
                // 当发现什么URL时执行登录逻辑
                .loginProcessingUrl("/login")
                 // 登录参数
                .usernameParameter("username")
                .passwordParameter("password")
                // 成功后跳转到哪里
                .successHandler(
                        (httpServletRequest, httpServletResponse, authentication) -> {
                    httpServletResponse.setContentType("application/json;charset=utf-8");
                    PrintWriter out = httpServletResponse.getWriter();
                    out.write("{\"status\":\"success\",\"msg\":\"登录成功\"}");
                    out.flush();
                    out.close();
                })
                // 失败后跳转到哪里
                .failureHandler(
                        (httpServletRequest, httpServletResponse, e) -> {
                    httpServletResponse.setContentType("application/json;charset=utf-8");
                    PrintWriter out = httpServletResponse.getWriter();
                    out.write("{\"status\":\"error\",\"msg\":\"登录失败,"+ e.getMessage()+"\"}");
                    out.flush();
                    out.close();
                });

        // 设置URL的授权问题
        // 多个条件取交集
        http.authorizeRequests()
                // 匹配 / 控制器  permitAll() 不需要被认证就可以访问
//                .antMatchers("/swagger**/**").permitAll()
                // anyRequest() 所有请求   authenticated() 必须被认证
                .anyRequest().authenticated();

        // 关闭csrf,禁用跨站伪造
        http.csrf().disable();


    }
    @Override
    public void configure(WebSecurity web) {
    	// 无需验证接口
        web.ignoring().antMatchers(
                "/swagger**/**",
                "/webjars/**",
                "/v3/**",
                "/doc.html");
    }
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
}

3、其它配置

(1)记住我配置
  • 前端配置
    前端请求参数需要包含参数remember-me且值为 true
  • security 配置

...
user表访问接口:
    private final UserServiceImpl userServiceImpl;
数据源配置:
    private final javax.sql.DataSource.DataSource dataSource;
...

...
记住我配置:
        // 记住我
        http
                .rememberMe()
                // 设置userDetailsService
                .userDetailsService(userServiceImpl)
                // 设置数据访问层
                .tokenRepository(persistentTokenRepository())
                // 记住我的时间(秒),24小时
                .tokenValiditySeconds(60 * 60 * 24)
                ;
...
数据访问:
/**
     * 持久化token
     *
     * Security中,默认是使用PersistentTokenRepository的子类InMemoryTokenRepositoryImpl,将token放在内存中
     * 如果使用JdbcTokenRepositoryImpl,会创建表persistent_logins,将token持久化到数据库
     * @return PersistentTokenRepository
     */
    @Bean
    public PersistentTokenRepository persistentTokenRepository() {
        JdbcTokenRepositoryImpl tokenRepository = new JdbcTokenRepositoryImpl();
        // 设置数据源
        tokenRepository.setDataSource(dataSource);
        // 启动创建表,创建成功后需要注释掉
        tokenRepository.setCreateTableOnStartup(true);
        return tokenRepository;
    }

(四)、配置详解

1.configure方法

protected void configure(AuthenticationManagerBuilder auth) throws Exception {}
public void configure(WebSecurity web) throws Exception {}
protected void configure(HttpSecurity httpSecurity) throws Exception {}
  • AuthenticationManagerBuilder:用于配置全局认证相关的信息,就是UserDetailsService和AuthenticationProvider
  • WebSecurity:用于全局请求忽略规则配置,比如一些静态文件,注册登录页面的放行
  • HttpSecurity用于具体的权限控制规则配置,我们这里只需要重写这个方法就可以了

2.HttpSecurity 常用方法

  • HttpSecurity 一些常用方法
方法说明
formLogin()开启表单的身份验证
loginPage()指定登录页面
successForwardUrl()指定登录成功之后跳转的页面
successHandler()登录成功后的擦操作逻辑
failureForwardUrl()指定登录失败之后跳转的页面
failureHandler()登录失败后的操作逻辑
authorizeRequests()开启使用HttpServletRequest请求的访问限制
oauth2Login()开启oauth2 验证
rememberMe()开启记住我的验证(使用cookie)
addFilter()添加自定义过滤器
csrf()开启csrf支持
登录成功/失败 后的操作逻辑
.successHandler(
(httpServletRequest, httpServletResponse, authentication) -> {
	httpServletResponse.sendRedirect("/index")
})
.failureHandler(
(httpServletRequest, httpServletResponse, authentication) -> {
	httpServletResponse.sendRedirect("/failure")
})
  • 一些认证方法
    认证方法

(五)、相关问题

1.跨域

跨域配置:

  • 允许跨域
...
 // 跨域
        http
                .cors()
                //禁用跨站伪造
                .and().csrf().disable();
...
  • 配置跨域(添加Bean)
 /**
     * 跨域处理
     * @return ..
     */
    @Bean
    CorsConfigurationSource corsConfigurationSource(){
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration configuration = new CorsConfiguration();
        // 允许携带凭证
        configuration.setAllowCredentials(true);
        // 允许从所有站点跨域
        configuration.addAllowedOriginPattern("*");
        // 允许所有方法
        configuration.setAllowedMethods(Collections.singletonList("*"));
        configuration.setAllowedHeaders(Collections.singletonList("*"));
        configuration.setMaxAge(Duration.ofHours(1));
        // 对所有URL生效
        source.registerCorsConfiguration("/**",configuration);
        return source;
    }

2.凭证

前端发送请求登录,登录成功后。再次发送请求访问后端接口,需要携带请求参数需要携带凭证信息(cookie信息),否则会没有凭证访问接口,自动重定向到登录页面(默认:/login)导致出现 302 错误。

axios配置:
// 携带凭证信息
axios.defaults.withCredentials = true;
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
## 介绍 使用 spring boot,基于 ssm 框架和 shiro 安全框架,开发的一个物流管理系统。前端使用的是 H-ui 开源框架,运用了 Bootstrap table、zTree、PageHelper、jQuery validate 等插件。 ## 特点 1. 基于 spring boot、maven 构建; 2. 运用了 springspring mvc、mybatis 和 shiro 框架; 3. 采用了 RBAC 的思路设计系统,采用了 Mysql 作为数据库支持; 4. 不同的角色登录系统会有不同的菜单列表,且会根据角色返回特定的数据; 5. 拥有基础数据管理模块,管理管理模块,角色管理模块,权限管理模块,客户管理模块,订单管理模块和业务处理模块; 6. 能够实现完整的业务流程:添加客户、添加订单、订单处理、财务报表。 ## 细节介绍 1. 业务员访问时,只能访问客户管理、订单管理、业务处理菜单,且只有添加的权力,没有修改和删除的权力; 2. 业务员添加订单时,只能基于自己拥有的客户添加; 3. 业务经理拥有客户管理、订单管理、业务处理的所有功能,可以查看所有业务员的客户和订单; 4. 总经理角色可以查看所有数据,但是没有修改的权力; 5. 仓管员只有业务处理中,测量物品信息和入库的功能,其他数据不可修改; 6. 财务可以查看审核订单价格详情并导出为 excel 表格。 -------- <项目介绍> 该资源内项目源码是个人的毕设,代码都测试ok,都是运行成功后才上传资源,答辩评审平均分达到96分,放心下载使用! 1、该资源内项目代码都经过测试运行成功,功能ok的情况下才上传的,请放心下载使用! 2、本项目适合计算机相关专业(如计科、人工智能、通信工程、自动化、电子信息等)的在校学生、老师或者企业员工下载学习,也适合小白学习进阶,当然也可作为毕设项目、课程设计、作业、项目初期立项演示等。 3、如果基础还行,也可在此代码基础上进行修改,以实现其他功能,也可用于毕设、课设、作业等。 下载后请首先打开README.md文件(如有),仅供学习参考, 切勿用于商业用途。 --------

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值