0
点赞
收藏
分享

微信扫一扫

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

书坊尚 2022-02-24 阅读 71

二十、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.启动项目测试

登录

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();

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.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
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")
                // 成功后跳转到哪里
                .successHandler(new AuthenticationSuccessHandler() {
                    @Override
                    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
                        httpServletResponse.setContentType("application/json;charset=utf-8");
                        PrintWriter out = httpServletResponse.getWriter();
                        out.write("{\"status\":\"success\",\"msg\":\"登录成功\"}");
                        out.flush();
                        out.close();
                    }
                })
                // 失败后跳转到哪里
                .failureHandler(new AuthenticationFailureHandler() {
                    @Override
                    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
                        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) throws Exception {
        web.ignoring().antMatchers(
                "/swagger**/**",
                "/webjars/**",
                "/v3/**",
                "/doc.html");
    }
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
}

四、配置详解

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")
})
  • 一些认证方法
    认证方法
举报

相关推荐

0 条评论