Spring整合SpringSecurity

SpringSecurity基礎使用

SpringSecurity是一個安全框架,主要功能是認證授權

從Spring入手SpringSecurity

1. Spring整合SpringSecurity

applicationContext.xml
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xmlns:mvc="http://www.springframework.org/schema/mvc"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc.xsd"><context:component-scan base-package="com.shaoby.service"></context:component-scan><import resource="spring-security.xml"/>
</beans>
spring-mvc.xml
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xmlns:mvc="http://www.springframework.org/schema/mvc"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc.xsd"><!-- 啟用注解掃描 --><context:component-scan base-package="com.shaoby.controller" /><!-- 配置視圖解析器 --><bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="prefix" value="/WEB-INF/views/" /><property name="suffix" value=".jsp" /></bean><!-- 啟用Spring MVC的注解 --><mvc:annotation-driven /><!-- 定義控制器 -->
<!--    <bean name="/example" class="com.shaoby.controller.ExampleController" />--></beans>
spring-security.xml
<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/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/securityhttp://www.springframework.org/schema/security/spring-security.xsd"><http auto-config="true"><intercept-url pattern="/login.jsp" access="permitAll()"/><intercept-url pattern="/**" access="hasAnyRole('ROLE_USER')" /><form-login login-page="/login.jsp" login-processing-url="/login" authentication-success-forward-url="/home.jsp"/><remember-metoken-validity-seconds="60"remember-me-parameter="remember-me"/><access-denied-handler error-page="/error.jsp"/></http><authentication-manager><authentication-provider><user-service><user name="user" password="{noop}123" authorities="ROLE_USER" /></user-service></authentication-provider></authentication-manager></beans:beans>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaeehttp://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"version="4.0"><display-name>Archetype Created Web Application</display-name>
<!--  初始化web容器--><context-param><param-name>contextConfigLocation</param-name><param-value>classpath:applicationContext.xml</param-value></context-param><!--配置Spring的監聽器,默認只加載WEB-INF目錄下的applicationContext.xml配置文件--><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener>
<!--亂碼--><filter><filter-name>characterEncodingFilter</filter-name><filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class><init-param><param-name>encoding</param-name><param-value>UTF-8</param-value></init-param><init-param><param-name>forceEncoding</param-name><param-value>true</param-value></init-param></filter><filter-mapping><filter-name>characterEncodingFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping>
<!--security--><filter><filter-name>springSecurityFilterChain</filter-name><filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class></filter><filter-mapping><filter-name>springSecurityFilterChain</filter-name><url-pattern>/*</url-pattern></filter-mapping>
<!--前端控制器--><servlet><servlet-name>dispatcherServlet</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><init-param><param-name>contextConfigLocation</param-name><param-value>classpath:spring-mvc.xml</param-value></init-param><load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name>dispatcherServlet</servlet-name><url-pattern>/</url-pattern></servlet-mapping>
</web-app>

2. 認證操作

2.1 自定義登錄頁面

自定義登錄頁面只需要在security配置文件中指定登錄頁面即可

<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/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/securityhttp://www.springframework.org/schema/security/spring-security.xsd"><http auto-config="true"><intercept-url pattern="/login.jsp" access="permitAll()"/><intercept-url pattern="/**" access="hasAnyRole('ROLE_USER')" /><!--指定登錄頁面或登錄成功頁面等,都在這個標簽中可以指定--><form-login login-page="/login.jsp" login-processing-url="/login" authentication-success-forward-url="/home.jsp"/><!-- 錯誤頁面--><access-denied-handler error-page="/error.jsp"/></http><authentication-manager><authentication-provider><user-service><user name="user" password="{noop}123" authorities="ROLE_USER" /></user-service></authentication-provider></authentication-manager>
</beans:beans>
2.2 關閉CSRF認證

使用csrf標簽指定disabled = 'true’即可

<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/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/securityhttp://www.springframework.org/schema/security/spring-security.xsd"><http auto-config="true"><intercept-url pattern="/login.jsp" access="permitAll()"/><intercept-url pattern="/**" access="hasAnyRole('ROLE_USER')" /><!--指定登錄頁面或登錄成功頁面等,都在這個標簽中可以指定--><form-login login-page="/login.jsp" login-processing-url="/login" authentication-success-forward-url="/home.jsp"/><!-- 錯誤頁面--><access-denied-handler error-page="/error.jsp"/><!--關閉CSRF認證--><csrf disabled="true"/></http><authentication-manager><authentication-provider><user-service><user name="user" password="{noop}123" authorities="ROLE_USER" /></user-service></authentication-provider></authentication-manager>
</beans:beans>

如果在JSP頁面中也可以通過引入標簽解決

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
-#引入
<%@ taglib prefix="security" uri="http://www.springframework.org/security/tags" %>
<html>
<head><title>登錄</title>
</head>
<body>
<h1>登錄頁面</h1>
<form action="/login" method="post">賬號:<input type="text" name="username"/> <br>密碼:<input type="password" name="password"/> <br>-#使用標簽<security:csrfInput/><input type="submit" value="登錄">
</form>
</body>
</html>
2.3 持久層認證
  1. 認證一般是通過持久層查詢進行認證的,這里暫時沒有鏈接數據庫,將數據寫死。
  2. ecurity實現持久層的認證只需要實現UserDetailsService,重寫loadUserByUserName,返回一個UserDetails對象即可,這個UserDetails對象可以通過任何方式獲得,一般是數據庫根據登錄用戶名查詢。
  3. 需要注意的是,如果密碼沒有采用加密方式,密碼前必須拼接{noop}字符串。
  4. 將寫好的實現類給Security指定
@Service
public class UserServiceImpl implements UserDetailsService {@Overridepublic UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {List<GrantedAuthority> list = new ArrayList<>();list.add(new SimpleGrantedAuthority("ROLE_USER"));UserDetails user = new User("admin", "{noop}123456", list);return user;}
}
<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/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/securityhttp://www.springframework.org/schema/security/spring-security.xsd"><http auto-config="true"><intercept-url pattern="/login.jsp" access="permitAll()"/><intercept-url pattern="/**" access="hasAnyRole('ROLE_USER')" /><!--指定登錄頁面或登錄成功頁面等,都在這個標簽中可以指定--><form-login login-page="/login.jsp" login-processing-url="/login" authentication-success-forward-url="/home.jsp"/><!-- 錯誤頁面--><access-denied-handler error-page="/error.jsp"/><!--關閉CSRF認證--><csrf disabled="true"/></http><authentication-manager><!--指定認證的類--><authentication-provider user-service-ref="userServiceImpl"></authentication-provider></authentication-manager>
</beans:beans>
2.4 密碼加密
  1. 密碼加密的方式有很多,比如MD5、MD4、BCryptPasswordEncoder等
  2. 如果使用加密的方式,一般是在持久層存儲的就是加密后的數據
  3. 使用加密的方法
  4. 將加密的方式注入到spring容器中
  5. 然后給Security指定加密方式
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xmlns:mvc="http://www.springframework.org/schema/mvc"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc.xsd"><context:component-scan base-package="com.shaoby.service"></context:component-scan>
<!--使用的加密方式的類--><bean name="bCryptPasswordEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"/><import resource="spring-security.xml"/>
</beans>
<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/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/securityhttp://www.springframework.org/schema/security/spring-security.xsd"><http auto-config="true"><intercept-url pattern="/login.jsp" access="permitAll()"/><intercept-url pattern="/**" access="hasAnyRole('ROLE_USER')" /><!--指定登錄頁面或登錄成功頁面等,都在這個標簽中可以指定--><form-login login-page="/login.jsp" login-processing-url="/login" authentication-success-forward-url="/home.jsp"/><!-- 錯誤頁面--><access-denied-handler error-page="/error.jsp"/><!--關閉CSRF認證--><csrf disabled="true"/></http><authentication-manager><!--指定認證的類--><authentication-provider user-service-ref="userServiceImpl"><!--給security指定加密的方式--><password-encoder ref="bCryptPasswordEncoder"/></authentication-provider></authentication-manager>
</beans:beans>
2.5 remember me
  1. 這個功能是在頁面勾選’記住我‘的勾選框后,下次再次訪問頁面不需要再次登錄
  2. 實現的原理是,在登錄成功后回返回給前端一個token,并存放在一張持久層表中或則內存中,前端存放在Cookie中,下次登錄只要攜帶Cookie,security就直接通過存儲的token比對,不需要重新認證
  3. 如果指定了數據源,就存放在持久層,如果沒有指定則存放在內存中
  4. token的過期時間是可以設置的
  5. 實現步驟:
  6. 開啟記住我功能
  7. 如果指定數據源則存放在數據庫中,如果沒有指定則存放在內存中
  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/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/securityhttp://www.springframework.org/schema/security/spring-security.xsd"><http auto-config="true"><intercept-url pattern="/login.jsp" access="permitAll()"/><intercept-url pattern="/**" access="hasAnyRole('ROLE_USER')" /><!--指定登錄頁面或登錄成功頁面等,都在這個標簽中可以指定--><form-login login-page="/login.jsp" login-processing-url="/login" authentication-success-forward-url="/home.jsp"/><!-- 錯誤頁面--><access-denied-handler error-page="/error.jsp"/><!--關閉CSRF認證--><csrf disabled="true"/><!--開啟remember功能 token-validity-seconds表示過期時間,單位秒;remember-me-parameter="remember-me"表示傳入的參數名;data-source-ref="dataSource"表示指定的數據源--><remember-metoken-validity-seconds="60"remember-me-parameter="remember-me"data-source-ref="dataSource"/></http><authentication-manager><!--指定認證的類--><authentication-provider user-service-ref="userServiceImpl"><!--給security指定加密的方式--><password-encoder ref="bCryptPasswordEncoder"/></authentication-provider></authentication-manager>
</beans:beans>

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/web/41768.shtml
繁體地址,請注明出處:http://hk.pswp.cn/web/41768.shtml
英文地址,請注明出處:http://en.pswp.cn/web/41768.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

大模型幻覺問題知識點總結

大模型幻覺問題知識點總結 定義&#xff1a; 大模型幻覺問題是指在自然語言處理&#xff08;NLP&#xff09;中&#xff0c;基于大規模預訓練模型&#xff08;如GPT-3、BERT等&#xff09;生成的文本看似合理且連貫&#xff0c;但實際上包含錯誤、不準確或虛假的信息。這種現象…

Aigtek高壓放大器指標有哪些要求和標準

高壓放大器是一類關鍵的電子設備&#xff0c;用于放大電信號并提供強大的輸出。在不同的應用領域&#xff0c;高壓放大器可能有不同的要求和標準。以下是一些常見的高壓放大器指標要求和標準&#xff0c;以確保其性能和可靠性&#xff1a; 1.幅度增益和頻率響應 高壓放大器的主…

人大金倉攜手中國一汽引領國產數據庫行業新浪潮

在國產化政策的推動下,人大金倉攜手中國一汽聯合開發更貼近汽車產業特定需求的數據庫功能和組件。從2023年2月至今,人大金倉已累計部署690套數據庫,適配應用系統170個,支撐中國一汽20多個核心系統和重要系統。目前,中國一汽在國內企業數據庫國產化替換率遙遙領先。此次合作為國…

貓咪健康新選擇!福派斯鮮肉貓糧里的果蔬纖維大揭秘

你們是不是對福派斯鮮肉貓糧中那些豐富的果蔬粗纖維特別好奇呢&#xff1f;&#x1f914; 其實&#xff0c;這些看似簡單的粗纖維&#xff0c;對貓咪的健康可是大有裨益的&#xff01; 粗纖維在貓糧中起到多種重要作用&#xff0c;并且對貓咪的健康和消化系統有著顯著的影響。以…

熱門開源項目推薦:探索開源世界的精彩

熱門開源項目推薦 隨著開源程序的發展&#xff0c;越來越多的程序員開始關注并加入開源大模型的行列。開源不僅為個人學習和成長提供了絕佳的平臺&#xff0c;也為整個技術社區帶來了創新和進步。無論你是初學者還是經驗豐富的開發者&#xff0c;參與開源項目都能讓你受益匪淺…

鄉村振興指數與其30個原始變量數據(Shp/Dta/Excel格式,2000-2022年)

數據簡介&#xff1a;這份數據是我國各地級市鄉村振興指數與其30各原始變量數據并對其進行地圖可視化表達。城鎮化是當今中國社會經濟發展的必由之路。當前我國城鎮化處于發展的關鍵時期&#xff0c;但城鎮化發展的加快卻是一把雙刃劍&#xff0c;為何要如此形容呢?因為當前城…

職升網:一級注冊計量師就業方向如何?

首先我們要知道&#xff0c;一級注冊計量師可以聘為工程師&#xff0c;可以負責計量基準和標準的量值傳遞工作。它可以從事一下7個方面的工作&#xff1a; 1.負責制定計量管理制度、工作計劃、并組織實施&#xff1b; 2.建設期參與設計工程等計量方面的工作&#xff0c;編制計…

k8s-第十二節-DaemonSet

DaemonSet是什么? DaemonSet 是一個確保全部或者某些節點上必須運行一個 Pod的工作負載資源(守護進程),當有node(節點)加入集群時, 也會為他們新增一個 Pod。 下面是常用的使用案例: 可以用來部署以下進程的pod 集群守護進程,如Kured、node-problem-detector日志收集…

紅黑樹模擬實現

目錄 概念 性質 節點定義 紅黑樹的插入 完整代碼 概念 紅黑樹&#xff0c;是一種二叉搜索樹&#xff0c;但在每個結點上增加一個存儲位表示結點的顏色&#xff0c;可以是Red或Black。通過對任何一條從根到葉子的路徑上各個結點著色方式的限制&#xff0c;紅黑樹確保沒有一條…

充電樁開源平臺,開發流程有圖有工具

慧哥充電樁開源平臺產品研發流程是確保產品從概念階段到市場推廣階段的有序進行的關鍵。以下是對您給出的步驟的詳細解釋和建議&#xff1a; 設計業務流程: 在這一步&#xff0c;團隊需要確定產品的核心功能、目標用戶以及如何滿足用戶需求。進行市場調研&#xff0c;了解競爭…

PostMan Error:Maximum response size reached

一、問題描述 用postman本地測試&#xff0c;restful api接口導出文件&#xff0c;文件大小為190M&#xff0c;服務沒問題&#xff0c;總是在導出時&#xff0c;拋出&#xff1a;Error:Maximum response size reached。開始以為是服務相應文件過大或者相應時間超時導致的。其實…

ts和js的關系

https://www.typescriptlang.org/zh/docs/handbook/typescript-from-scratch.html TypeScript&#xff08;TS&#xff09;和 JavaScript&#xff08;JS&#xff09;都是用于開發前端和后端應用的編程語言&#xff0c;但它們有一些顯著的區別。以下是主要的區別&#xff1a; 1…

雙向鏈表 -- 詳細理解和實現

歡迎光顧我的homepage 前言 雙向鏈表是一種帶頭雙向循環的鏈表。在雙向鏈表中&#xff0c;首先存在著一個頭結點&#xff1b;其次每個節點有指向下一個節點的指針next 和指向上一個節點的指針prev &#xff1b…

Trimble realworks 2024.02 中文激活版獲取License下載軟件

Trimble realworks 2024 是領先的3D點云和2D圖像處理解決方案&#xff0c;使用可您提供了一組用于處理的工具&#xff0c;以便為您的應用程序&#xff08;或項目&#xff09;獲取必要的信息。此處理可以分為三種模式&#xff0c;在注冊中&#xff0c;您可以注冊相對于其他掃描和…

通信協議_Modbus協議簡介

概念介紹 Modbus協議&#xff1a;一種串行通信協議&#xff0c;是Modicon公司&#xff08;現在的施耐德電氣Schneider Electric&#xff09;于1979年為使用可編程邏輯控制器&#xff08;PLC&#xff09;通信而發表。Modbus已經成為工業領域通信協議的業界標準&#xff08;De f…

大舍傳媒:如何在海外新聞媒體發稿報道摩洛哥?

引言 作為媒體行業的專家&#xff0c;我將分享一些關于在海外新聞媒體發稿報道摩洛哥的干貨教程。本教程將帶您深入了解三個重要的新聞媒體平臺&#xff1a;Mediterranean News、Morocco News和North African News。 地中海Mediterranean News Mediterranean News是一個知名…

合合信息大模型“加速器”重磅上線

大模型技術的發展和應用&#xff0c;預示著更加智能化、個性化未來的到來。如果將大模型比喻為正在疾馳的科技列車&#xff0c;語料便是珍貴的“燃料”。本次世界人工智能大會期間&#xff0c;合合信息為大模型打造的“加速器”解決方案備受關注。 在大模型訓練的上游階段&…

【計算機畢業設計】021基于weixin小程序微信點餐

&#x1f64a;作者簡介&#xff1a;擁有多年開發工作經驗&#xff0c;分享技術代碼幫助學生學習&#xff0c;獨立完成自己的項目或者畢業設計。 代碼可以私聊博主獲取。&#x1f339;贈送計算機畢業設計600個選題excel文件&#xff0c;幫助大學選題。贈送開題報告模板&#xff…

Python學習中使用循環(for, while)

在Python編程語言中&#xff0c;循環是一個非常重要的概念&#xff0c;可以幫助我們在代碼中重復執行某些操作。Python支持兩種主要的循環結構&#xff1a;for 循環和 while 循環。 1. for 循環 for 循環用于遍歷一個序列&#xff08;如列表、元組、字符串&#xff09;或其他…

第11章:標準化和軟件知識產權

第11章&#xff1a;標準化和軟件知識產權 標準化 國際標準(International Standard)是指國際標準化組織(ISO)、國際電工 委員會(IEC)所制定的標準。 標準 是對重復性事物和概念所做的統一規定。 標準化的特征包括橫向綜合性、政策性和統一性 。 標準化是指在經濟、技術、科學…