Springboot注解,spring security oauth2.0 實現

 2023-11-07 阅读 32 评论 0

摘要:oauth應該屬于security的一部分。關于oauth的的相關知識可以查看阮一峰的文章:http://www.ruanyifeng.com/blog/2014/05/oauth_2_0.html Springboot注解,一、目標   現在很多系統都支持第三方賬號密碼等登陸我們自己的系統,例如:我們經常會看到ÿ

oauth應該屬于security的一部分。關于oauth的的相關知識可以查看阮一峰的文章:http://www.ruanyifeng.com/blog/2014/05/oauth_2_0.html

Springboot注解,一、目標

  現在很多系統都支持第三方賬號密碼等登陸我們自己的系統,例如:我們經常會看到,一些系統使用微信賬號,微博賬號、QQ賬號等登陸自己的系統,我們現在就是要模擬這種登陸的方式,很多大的公司已經實現了這種授權登陸的方式,并提供了相應的API,供我們開發人員調用。他們實際上用的也規范是oauth2.0的規范,通過用戶授權的方式,獲取一些信息。以前就做過一些類似的,如:

spring security5?微信掃碼登陸:http://www.cnblogs.com/0201zcr/p/5133062.html

微信客戶端授權登陸:http://www.cnblogs.com/0201zcr/p/5131602.html  

  但是假如你的系統要提供其他網站使用你的賬號密碼登陸,你就需要寫好相應的接口規范, 給人家調用。用得比較多的是使用spring security oauth實現的方式。

我們這里使用meaven導入我們所需要的jar包,使用配置文件的方式攔截我們的請求并進行驗證是否有效,然后即可獲取我們需要的信息。

這里主要是模擬了通過給予第三方賬號密碼的方式,在第三方進行鑒權,然后將access_token等信息傳回過來,然后要登錄的系統在通過這個返回的access_token去第三方請求一些用戶授權的數據。即可完成第三方的賬號密碼登錄。

二、Spring security oauth?相關依賴meaven配置

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"><modelVersion>4.0.0</modelVersion><groupId>org.zhangfc</groupId><artifactId>demo4ssh-security-oauth2</artifactId><packaging>war</packaging><version>0.0.1-SNAPSHOT</version><properties><spring.version>4.0.4.RELEASE</spring.version><hibernate.version>4.3.5.Final</hibernate.version><spring-security.version>3.2.4.RELEASE</spring-security.version><spring-security-oauth2.version>2.0.2.RELEASE</spring-security-oauth2.version></properties><dependencies><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-orm</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework.security</groupId><artifactId>spring-security-config</artifactId><version>${spring-security.version}</version></dependency><dependency><groupId>org.springframework.security</groupId><artifactId>spring-security-taglibs</artifactId><version>${spring-security.version}</version></dependency><dependency><groupId>org.springframework.security.oauth</groupId><artifactId>spring-security-oauth2</artifactId><version>${spring-security-oauth2.version}</version></dependency><dependency><groupId>org.hibernate</groupId><artifactId>hibernate-core</artifactId><version>${hibernate.version}</version></dependency><dependency><groupId>javax.servlet.jsp.jstl</groupId><artifactId>javax.servlet.jsp.jstl-api</artifactId><version>1.2.1</version></dependency><dependency><groupId>taglibs</groupId><artifactId>standard</artifactId><version>1.1.2</version></dependency><dependency><groupId>tomcat</groupId><artifactId>servlet-api</artifactId><version>5.5.23</version><scope>provided</scope></dependency><dependency><groupId>tomcat</groupId><artifactId>jsp-api</artifactId><version>5.5.23</version><scope>provided</scope></dependency><dependency><groupId>commons-fileupload</groupId><artifactId>commons-fileupload</artifactId><version>1.3.1</version></dependency><dependency><groupId>org.hibernate</groupId><artifactId>hibernate-validator</artifactId><version>5.1.2.Final</version></dependency><dependency><groupId>c3p0</groupId><artifactId>c3p0</artifactId><version>0.9.1.2</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.31</version></dependency><dependency><groupId>org.codehaus.jackson</groupId><artifactId>jackson-mapper-asl</artifactId><version>1.9.13</version></dependency></dependencies><build><finalName>demo4ssh-security-oauth2</finalName></build>
</project>

三、web.xml文件配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="http://java.sun.com/xml/ns/javaee"xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"metadata-complete="true" version="3.0"><context-param><param-name>contextConfigLocation</param-name><param-value>classpath:/META-INF/infrastructure.xml,classpath*:/META-INF/applicationContext*.xml</param-value></context-param><listener>    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><servlet><servlet-name>spring-dispatcher</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class></servlet><servlet-mapping><servlet-name>spring-dispatcher</servlet-name><url-pattern>/</url-pattern></servlet-mapping><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></web-app>

四、applicationContext-security.xml

  oauth2是security的一部分,配置也有關聯,就不再單建文件

  添加http攔截鏈

<!--  /oauth/token 是oauth2登陸驗證請求的url     用于獲取access_token  ,默認的生存時間是43200秒,即12小時--><http pattern="/oauth/token" create-session="stateless"authentication-manager-ref="oauth2AuthenticationManager"><intercept-url pattern="/oauth/token" access="IS_AUTHENTICATED_FULLY" />     <!--  可以訪問的角色名稱,如果需要攔截,需要實現UserDetails接口,實現getAuthorities()方法--><anonymous enabled="false" /><http-basic entry-point-ref="oauth2AuthenticationEntryPoint" /><custom-filter ref="clientCredentialsTokenEndpointFilter"before="BASIC_AUTH_FILTER" /><access-denied-handler ref="oauth2AccessDeniedHandler" /></http>

這個標簽處理/oauth/token的網絡請求,這是oauth2的登錄驗證請求,那么登錄需要什么,首先,和Spring Security一樣,需要一個認證管理器,Spring Oauth2需要兩個認證管理器,第一個就是之前Spring中配置的那一個,用來驗證用戶名密碼的,

<!-- 驗證的權限控制 --><authentication-manager><authentication-provider><!-- <password-encoder hash="md5"> <salt-source user-property="email"/> </password-encoder> --><jdbc-user-service data-source-ref="dataSource"users-by-username-query="select username, password, 1 from user where username = ?"authorities-by-username-query="select u.username, r.role from user u left join role r on u.role_id=r.id where username = ?" /></authentication-provider></authentication-manager>

還有一個是用來區分客戶端用戶的,給它起個名字叫oauth2AuthenticationManager:

<oauth2:client-details-service id="clientDetailsService" ><oauth2:client client-id="mobile_1"authorized-grant-types="password,authorization_code,refresh_token,implicit"secret="secret_1" scope="read,write,trust"      /></oauth2:client-details-service><beans:bean id="oauth2ClientDetailsUserService"class="org.springframework.security.oauth2.provider.client.ClientDetailsUserDetailsService"><beans:constructor-arg ref="clientDetailsService" /></beans:bean><authentication-manager id="oauth2AuthenticationManager"><authentication-provider user-service-ref="oauth2ClientDetailsUserService" /></authentication-manager>

這兒設置了一種客戶端,id叫做mobile_1,secret叫做secret_1,針對read、write和trust幾個域有效。這幾個域會在訪問控制中被用到。

  當登錄成功之后會得到一個token,再次訪問的時候需要攜帶這個token,spring-oauth2根據這個token來做認證,那么spring-oauth2必須先存一份token和用戶關系的對應,因為不用session了,這就相當于session,那么這個token在服務器中怎么存,有兩種主要的存儲方式,一是創建數據表,把token存到數據庫里,我現在追求簡單可用,采用第二種方式,直接存到內存里。下面配置一個管理token的service:

<!-- for spring oauth2 --><!--token在服務器存儲的方式    InMemoryTokenStore :保存在內存     ;JdbcTokenStore : 保存在數據庫中 --><beans:bean id="tokenStore"class="org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore" /><!--<beans:bean id="tokenServices"class="org.springframework.security.oauth2.provider.token.DefaultTokenServices">-->     <!--令牌服務的實體--><beans:bean id="tokenServices"class="org.zhangfc.demo4ssh.service.MyTokenService">      <!-- 自己重寫的類 -->

下面配置4個基本的bean:分別處理訪問成功、訪問拒絕、認證點和訪問控制:

<!--處理訪問成功--><beans:bean id="oauth2AuthenticationEntryPoint"class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint" /><!--處理訪問拒絕--><beans:bean id="oauth2AccessDeniedHandler"class="org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler" /><!--處理認證點--><beans:bean id="oauthUserApprovalHandler"class="org.springframework.security.oauth2.provider.approval.DefaultUserApprovalHandler" /><!--處理訪問控制--><beans:bean id="oauth2AccessDecisionManager"class="org.springframework.security.access.vote.UnanimousBased"><beans:constructor-arg><beans:list><beans:beanclass="org.springframework.security.oauth2.provider.vote.ScopeVoter" /><beans:bean class="org.springframework.security.access.vote.RoleVoter" /><beans:beanclass="org.springframework.security.access.vote.AuthenticatedVoter" /></beans:list></beans:constructor-arg></beans:bean>

配置這個oauth2的server所能支持的請求類型:

<!--oauth2 的server所能支持的請求類型--><oauth2:authorization-serverclient-details-service-ref="clientDetailsService" token-services-ref="tokenServices"user-approval-handler-ref="oauthUserApprovalHandler"><oauth2:authorization-code /><oauth2:implicit /><oauth2:refresh-token /><oauth2:client-credentials /><oauth2:password /></oauth2:authorization-server>

我們的請求里,要把驗證類型、用戶名密碼都作為表單參數提交,這就需要配置下面的filter:

    <beans:bean id="clientCredentialsTokenEndpointFilter"class="org.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilter"><beans:property name="authenticationManager" ref="oauth2AuthenticationManager" /></beans:bean>

  下面定義一種資源,指定spring要保護的資源,如果沒有這個,訪問控制的時候會說沒有Authentication object:

    <!--指定spring要保護的資源,如果沒有這個,訪問控制的時候會說沒有Authentication object:--><oauth2:resource-server id="mobileResourceServer"resource-id="mobile-resource" token-services-ref="tokenServices" />

  好了,到此為止基本配置就都有了,下面就看訪問控制的配置:在前面的攔截鏈上,已經為登錄驗證配了一個/auth/token,在這個標簽下面添加對/json和/admin這兩個路徑的控制

    <http pattern="/json**" create-session="never"entry-point-ref="oauth2AuthenticationEntryPoint"access-decision-manager-ref="oauth2AccessDecisionManager"><anonymous enabled="false" /><intercept-url pattern="/json**" access="ROLE_USER" /><custom-filter ref="mobileResourceServer" before="PRE_AUTH_FILTER" /><access-denied-handler ref="oauth2AccessDeniedHandler" /></http><http pattern="/admin**" create-session="never"entry-point-ref="oauth2AuthenticationEntryPoint"access-decision-manager-ref="oauth2AccessDecisionManager"><anonymous enabled="false" /><intercept-url pattern="/admin**" access="SCOPE_READ,ROLE_ADMIN" /><custom-filter ref="mobileResourceServer" before="PRE_AUTH_FILTER" /><access-denied-handler ref="oauth2AccessDeniedHandler" /></http>

  我們用oauth2AccessDecisionManager來做決策,這個地方需要注意,spring-security里面配置access="ROLE_USER,ROLE_ADMIN"是說user和admin都可以訪問,是一個“或”的關系,但是這里是“與”的關系,比如第二個,需要ROLE_ADMIN并且當前的scope包含read才可以,否則就沒有權限。認證失敗會返回一段xml,這個可以自定義handler來修改,暫且按下不表。

  ?默認的12小時access_token可能對于我們來說太長,通過UUID.randomUUID()來生成一個36的唯一的access_token 也不是我們想要的生存方式。故我們可以復制org.springframework.security.oauth2.provider.token.DefaultTokenServices,并對其進行一定修改即可,這里我把這個類復制出來,修改成MyTokenService,并在上面的配置文件中進行了配置。主要是修改其以下成員變量:

    private int refreshTokenValiditySeconds = 2592000;       //refresh_token 的超時時間  默認2592000秒private int accessTokenValiditySeconds = 10;             //access_token 的超時時間   默認12個小時private boolean supportRefreshToken = false;            //是否支持access_token 刷新,默認是false,在配置文件中以配置成可以支持了,private boolean reuseRefreshToken = true;               //使用refresh_token刷新之后該refresh_token是否依然使用,默認是依然使用private TokenStore tokenStore;                             //access_token的存儲方式,這個在配置文件中配

  通過修改修改其createAccessToken方法來修改access_token 的生成方式:

    private OAuth2AccessToken createAccessToken(OAuth2Authentication authentication, OAuth2RefreshToken refreshToken) {String access_tokens = UUID.randomUUID().toString().replaceAll("-","");  DefaultOAuth2AccessToken token = new DefaultOAuth2AccessToken(access_tokens);int validitySeconds = this.getAccessTokenValiditySeconds(authentication.getOAuth2Request());if(validitySeconds > 0) {token.setExpiration(new Date(System.currentTimeMillis() + (long)validitySeconds * 1000L));token.setRefreshToken(refreshToken);token.setScope(authentication.getOAuth2Request().getScope());return (OAuth2AccessToken)(this.accessTokenEnhancer != null?this.accessTokenEnhancer.enhance(token, authentication):token);}

  源碼下載:http://pan.baidu.com/s/1mhSfKFY

獲取access_token ?URL :

http://localhost:8080/AOuth/oauth/token?client_id=mobile_1&client_secret=secret_1&grant_type=password&username=aa&password=aa

這時候會返回一個access_token:

{"access_token":"4219a91f-45d5-4a07-9e8e-3acbadd0c23e","token_type":"bearer","refresh_token":"d41df9fd-3d36-4a20-b0b7-1a1883c7439d","expires_in":43199,"scope":"read write trust"}

這之后再拿著這個access_token去訪問資源:

http://localhost:8080/AOuth/admin?access_token=4219a91f-45d5-4a07-9e8e-3acbadd0c23e

刷新access_token:

http://localhost:8080/AOuth/oauth/token?client_id=mobile_1&client_secret=secret_1&grant_type=refresh_token&refresh_token=ad18fc89e1424278b675ca05bf8afbb3?

  致謝:感謝您的閱讀!

轉載于:https://www.cnblogs.com/powerwu/articles/8072927.html

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/5/166799.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息