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.xsdhttp://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 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 class='com.software.controller.UserDetailsServiceImpl'></beans:bean><!-- 定義 spring security 安全加密算法對象 --><beans:bean 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 class='com.software.controller.UserDetailsServiceImpl'></beans:bean> <!-- 定義 spring security 安全加密算法對象 --> <beans:bean class='com.software.controller.MyPasswordEncoder'></beans:bean>
到此這篇關于Spring Security 安全認證的示例代碼的文章就介紹到這了,更多相關Spring Security 安全認證內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章: