Spring Security 安全认证

时间:2022-07-28
本文章向大家介绍Spring Security 安全认证,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

1.1 动态用户

1.1.1 放行资源

  如果我们再配置的时候没有放行登录页等一些不需要登录就可以看到的资源,那么访问的时候就会全部拦截导致访问不到。所以我们要配置放行一些无需登录就可以看到的资源。

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
             xmlns:beans="http://www.springframework.org/schema/beans" 
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://www.springframework.org/schema/beans 
                http://www.springframework.org/schema/beans/spring-beans.xsd
                http://www.springframework.org/schema/security 
                http://www.springframework.org/schema/security/spring-security.xsd">

    <!-- 设置页面不登陆也可以访问 -->
    <http pattern="/login.html" security="none"></http>
    <http pattern="/css/**" security="none"></http>
    <http pattern="/js/**" security="none"></http>
    <http pattern="/img/**" security="none"></http>

    <!-- 页面的拦截规则    use-expressions:是否启动 SPEL 表达式 默认是 true -->
    <http use-expressions="false">
        <!-- 当前用户必须有 ROLE_USER 的角色 才可以访问根目录及所属子目录的资源 -->
        <intercept-url pattern="/**" access="ROLE_USER"/>
        <!-- 开启表单登陆功能 -->
        <form-login/>
    </http>

    <!-- 认证管理器 -->
    <authentication-manager>
        <authentication-provider>
            <user-service>
            	<!-- 配置静态用户 -->
                <user name="admin" password="123456" authorities="ROLE_USER"/>
            </user-service>
        </authentication-provider>
    </authentication-manager>

</beans:beans>

1.1.2 动态用户

  我们之前配置的都是再配置文件中静态用户,如果用户更改就需要修改配置文件十分的不方便,这个时候我们就需要从数据库中读取用户了。修改时直接修改数据库就行了。

☞ 认证类

/**
 * Created with IntelliJ IDEA.
 *
 * @author Demo_Null
 * @date 2020/10/12
 * @description 认证类
 */
public class UserDetailsServiceImpl implements UserDetailsService {
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        // UserDetails 对象
        UserDetails userDetails = null;
        
        // 构建角色列表
        List<GrantedAuthority> grantedAuths = new ArrayList<GrantedAuthority>();
        grantedAuths.add(new SimpleGrantedAuthority("ROLE_SELLER"));

        // 根据用户名获取用户

        // 判断用户是否存在
        if (Objects.equals("admin", s)) {
            // 构建一个 User 返回,Security 会自动核验密码
            userDetails =  new User("admin","123456", grantedAuths);
        }

        return userDetails;

    }
}

☞ 认证管理器

<!-- 认证管理器 -->
<authentication-manager>
    <authentication-provider user-service-ref="userDetailService"></authentication-provider>
</authentication-manager>
<beans:bean id="userDetailService" class="com.software.controller.UserDetailsServiceImpl"></beans:bean>

1.2 加密

1.2.1 BCrypt 加密算法

  用户表的密码通常使用 MD5 等不可逆算法加密后存储,为防止彩虹表破解更会先使用一个特定的字符串加密,然后再使用一个随机的 salt(盐值) 加密。 特定字符串是程序代码中固定的,salt 是每个密码单独随机,一般给用户表加一个字段单独存储,比较麻烦。 BCrypt 算法将 salt 随机并混入最终加密后的密码,验证时也无需单独提供之前的 salt,从而无需单独处理 salt 问题。

☞ 配置加密

<!-- 认证管理器 -->
<authentication-manager>
    <authentication-provider user-service-ref="userDetailService">
        <password-encoder ref="passwordEncoder"></password-encoder>
    </authentication-provider>
</authentication-manager>
<beans:bean id="userDetailService" class="com.software.controller.UserDetailsServiceImpl"></beans:bean>

<!-- 定义 spring security 安全加密算法对象 -->
<beans:bean id="passwordEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder">
</beans:bean>

☞ 加密

/**
 * Created with IntelliJ IDEA.
 *
 * @author Demo_Null
 * @date 2020/10/12
 * @description BCrypt 加密
 */
public class UserDetailsServiceImpl implements UserDetailsService {
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        // UserDetails 对象
        UserDetails userDetails = null;

        // 构建角色列表
        List<GrantedAuthority> grantedAuths = new ArrayList<GrantedAuthority>();
        grantedAuths.add(new SimpleGrantedAuthority("ROLE_SELLER"));

        // 根据用户名获取用户

        // 判断用户是否存在
        if (Objects.equals("admin", s)) {
            // 模拟密码已加密
            BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
            String encode = bCryptPasswordEncoder.encode("123456");


            // 构建一个 User 返回,Security 会自动核验密码
            userDetails =  new User("admin",encode, grantedAuths);
        }

        return userDetails;

    }
}

1.2.2 自定义加密算法

☞ 自定义加密算法

/**
 * Created with IntelliJ IDEA.
 *
 * @author Demo_Null
 * @date 2020/10/12
 * @description 加密工具类
 */ 
public class MD5Util {
    private static final String SALT = "Demo_Null";

    public static String encode(String password) {
        password = password + SALT;
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        char[] charArray = password.toCharArray();
        byte[] byteArray = new byte[charArray.length];

        for (int i = 0; i < charArray.length; i++)
            byteArray[i] = (byte) charArray[i];
        byte[] md5Bytes = md5.digest(byteArray);
        StringBuffer hexValue = new StringBuffer();
        for (int i = 0; i < md5Bytes.length; i++) {
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16) {
                hexValue.append("0");
            }
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();
    }
}

☞ 自定义加密

/**
 * Created with IntelliJ IDEA.
 *
 * @author Demo_Null
 * @date 2020/10/12
 * @description 自定义加密算法
 */
public class MyPasswordEncoder implements PasswordEncoder {
    @Override
    public String encode(CharSequence charSequence) {
        return MD5Util.encode((String)charSequence);
    }

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

☞ 修改安全加密算法对象

    <!-- 认证管理器 -->
    <authentication-manager>
        <authentication-provider user-service-ref="userDetailService">
            <password-encoder ref="passwordEncoder"></password-encoder>
        </authentication-provider>
    </authentication-manager>
    <beans:bean id="userDetailService" class="com.software.controller.UserDetailsServiceImpl"></beans:bean>

    <!-- 定义 spring security 安全加密算法对象 -->
    <beans:bean id="passwordEncoder" class="com.software.controller.MyPasswordEncoder"></beans:bean>