Skip to content

SpringSecurity学习使用

没写完,后空可以看看若依,没空就算了。

前置

这里使用若依分离版项目: https://gitee.com/y_project/RuoYi-Vue

#前端运行(以管理员身份运行)
npm install

# 强烈建议不要用直接使用 cnpm 安装,会有各种诡异的 bug,可以通过重新指定 registry 来解决 npm 安装速度慢的问题。
npm install --registry=https://registry.npmmirror.com

# 本地开发 启动项目
npm run dev

后端配置

改一下数据库配置和服务器配置,

# 开发环境配置
server:
  # 服务器的HTTP端口,默认为80
  port: 端口
  servlet:
    # 应用的访问路径
    context-path: /应用路径

关于 context-path 的配置说明

如果你的服务器(或虚拟主机)只部署了一个应用,或者你希望应用直接响应域名根路径(例如,http://www.example.com/),你可以不设置上下文路径,即使用默认的根路径/。这种情况下,你可以在配置文件中省略context-path的设置。

如果服务器上部署了多个应用,或者出于其他原因(如API版本控制)需要将应用部署在非根路径下,就需要设置一个具体的上下文路径。这样做可以避免不同应用间的路由冲突,也使得URL具有更好的可读性和组织性。


报错:错误: 找不到或无法加载主类 com.ruoyi.RuoYiApplication

解决:重新 clean ,再 install 一下,同时再加载前通过 父目录下的 Lifecycle 下进行 clean install;再重新加载依赖。


加密操作:

public static String encryptPassword(String password)  
{  
    // 创建BCryptPasswordEncoder对象(用于密码加密的类)  
    BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();  
    return passwordEncoder.encode(password);  
}

基于BCrypt算法的密码哈希机制;他提供的是一种单向的密码保护机制,旨在确保即使数据库被泄露,攻击者也无法恢复出用户的原始密码。这是目前Web应用中存储用户密码的推荐做法之一。

BCrypt算法会在每次加密时自动生成一个盐(Salt)【随机盐值】,并将盐值整合到最终的哈希结果中。这意味着即使两个用户使用了相同的密码,由于盐的随机性,他们存储在数据库中的哈希值也将是不同的。

判定密码是否相同

/**  
 * 判断密码是否相同  
 *  
 * @param rawPassword 真实密码  
 * @param encodedPassword 加密后字符  
 * @return 结果  
 */  
public static boolean matchesPassword(String rawPassword, String encodedPassword)  
{  
    BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();  
    return passwordEncoder.matches(rawPassword, encodedPassword);  
}

matches 方法(提取盐操作,生成哈希值,比较哈希值)

  1. 提取盐值encodedPassword(数据库中的哈希值)包括了原始密码哈希的结果和用于创建这个哈希的盐值。matches方法首先从encodedPassword中提取出用于哈希的盐值。
  2. 重新哈希:使用提取出的盐值和同样的哈希算法(及其参数,如工作因子),对rawPassword(用户输入的密码)进行哈希处理。
  3. 比较哈希值:将上一步生成的哈希值与encodedPassword进行比较。因为盐值是在原始密码哈希时随机生成的,并存储于encodedPassword中,所以即使是同一个密码,每次哈希的结果也是唯一的。但是,使用相同的密码和盐值,按照相同的方法进行哈希,将产生相同的哈希值。
  4. 返回结果
    • 如果两个哈希值相同,说明用户输入的密码正确,matches方法返回true
    • 如果两个哈希值不同,说明密码不匹配,matches方法返回false

认证授权流程

一、常用用法

引入使用,添加Spring Security依赖:

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

基本配置

默认情况下,Spring Security会添加一些自动配置,包括一个默认的用户(用户名是user,密码在启动时控制台输出)和基本的登录页面。

要自定义配置,你可以创建一个配置类并继承WebSecurityConfigurerAdapter,然后覆盖其中的方法

在若依的分离版本项目中,使用的配置类文件是: SecurityConfig

一般我们会 覆盖 configure 方法进行重写,添加一些自定义配置

package com.ruoyi.framework.config;  
  
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.context.annotation.Bean;  
import org.springframework.http.HttpMethod;  
import org.springframework.security.authentication.AuthenticationManager;  
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;  
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;  
import org.springframework.security.config.annotation.web.builders.HttpSecurity;  
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;  
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;  
import org.springframework.security.config.http.SessionCreationPolicy;  
import org.springframework.security.core.userdetails.UserDetailsService;  
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;  
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;  
import org.springframework.security.web.authentication.logout.LogoutFilter;  
import org.springframework.web.filter.CorsFilter;  
import com.ruoyi.framework.config.properties.PermitAllUrlProperties;  
import com.ruoyi.framework.security.filter.JwtAuthenticationTokenFilter;  
import com.ruoyi.framework.security.handle.AuthenticationEntryPointImpl;  
import com.ruoyi.framework.security.handle.LogoutSuccessHandlerImpl;  
  
/**  
 * spring security配置  
 *   
 * @author ruoyi  
 */@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)  
public class SecurityConfig extends WebSecurityConfigurerAdapter  
{  
    /**  
     * 自定义用户认证逻辑  
     */  
    @Autowired  
    private UserDetailsService userDetailsService;  
      
    /**  
     * 认证失败处理类  
     */  
    @Autowired  
    private AuthenticationEntryPointImpl unauthorizedHandler;  
  
    /**  
     * 退出处理类  
     */  
    @Autowired  
    private LogoutSuccessHandlerImpl logoutSuccessHandler;  
  
    /**  
     * token认证过滤器  
     */  
    @Autowired  
    private JwtAuthenticationTokenFilter authenticationTokenFilter;  
      
    /**  
     * 跨域过滤器  
     */  
    @Autowired  
    private CorsFilter corsFilter;  
  
    /**  
     * 允许匿名访问的地址  
     */  
    @Autowired  
    private PermitAllUrlProperties permitAllUrl;  
  
    /**  
     * 解决 无法直接注入 AuthenticationManager  
     *     * @return     * @throws Exception  
     */  
    @Bean  
    @Override    public AuthenticationManager authenticationManagerBean() throws Exception  
    {  
        return super.authenticationManagerBean();  
    }  
  
    /**  
     * anyRequest          |   匹配所有请求路径  
     * access              |   SpringEl表达式结果为true时可以访问  
     * anonymous           |   匿名可以访问  
     * denyAll             |   用户不能访问  
     * fullyAuthenticated  |   用户完全认证可以访问(非remember-me下自动登录)  
     * hasAnyAuthority     |   如果有参数,参数表示权限,则其中任何一个权限可以访问  
     * hasAnyRole          |   如果有参数,参数表示角色,则其中任何一个角色可以访问  
     * hasAuthority        |   如果有参数,参数表示权限,则其权限可以访问  
     * hasIpAddress        |   如果有参数,参数表示IP地址,如果用户IP和参数匹配,则可以访问  
     * hasRole             |   如果有参数,参数表示角色,则其角色可以访问  
     * permitAll           |   用户可以任意访问  
     * rememberMe          |   允许通过remember-me登录的用户访问  
     * authenticated       |   用户登录后可访问  
     */  
    @Override  
    protected void configure(HttpSecurity httpSecurity) throws Exception  
    {  
        // 注解标记允许匿名访问的url  
        ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = httpSecurity.authorizeRequests();  
        permitAllUrl.getUrls().forEach(url -> registry.antMatchers(url).permitAll());  
  
        httpSecurity  
                // CSRF禁用,因为不使用session  
                .csrf().disable()  
                // 禁用HTTP响应标头  
                .headers().cacheControl().disable().and()  
                // 认证失败处理类  
                .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()  
                // 基于token,所以不需要session  
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()  
                // 过滤请求  
                .authorizeRequests()  
                // 对于登录login 注册register 验证码captchaImage 允许匿名访问  
                .antMatchers("/login", "/register", "/captchaImage").permitAll()  
                // 静态资源,可匿名访问  
                .antMatchers(HttpMethod.GET, "/", "/*.html", "/**/*.html", "/**/*.css", "/**/*.js", "/profile/**").permitAll()  
                .antMatchers("/swagger-ui.html", "/swagger-resources/**", "/webjars/**", "/*/api-docs", "/druid/**").permitAll()  
                // 除上面外的所有请求全部需要鉴权认证  
                .anyRequest().authenticated()  
                .and()  
                .headers().frameOptions().disable();  
        // 添加Logout filter  
        httpSecurity.logout().logoutUrl("/logout").logoutSuccessHandler(logoutSuccessHandler);  
        // 添加JWT filter  
        httpSecurity.addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);  
        // 添加CORS filter  
        httpSecurity.addFilterBefore(corsFilter, JwtAuthenticationTokenFilter.class);  
        httpSecurity.addFilterBefore(corsFilter, LogoutFilter.class);  
    }  
  
    /**  
     * 强散列哈希加密实现  
     */  
    @Bean  
    public BCryptPasswordEncoder bCryptPasswordEncoder()  
    {  
        return new BCryptPasswordEncoder();  
    }  
  
    /**  
     * 身份认证接口  
     */  
    @Override  
    protected void configure(AuthenticationManagerBuilder auth) throws Exception  
    {  
        auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());  
    }  
}

二、权限控制