电脑知识|欧美黑人一区二区三区|软件|欧美黑人一级爽快片淫片高清|系统|欧美黑人狂野猛交老妇|数据库|服务器|编程开发|网络运营|知识问答|技术教程文章 - 好吧啦网

您的位置:首頁技術文章
文章詳情頁

Springboot開發OAuth2認證授權與資源服務器操作

瀏覽:78日期:2023-03-02 11:38:04

設計并開發一個開放平臺。

一、設計:

Springboot開發OAuth2認證授權與資源服務器操作

網關可以 與認證授權服務合在一起,也可以分開。

二、開發與實現:

用Oauth2技術對訪問受保護的資源的客戶端進行認證與授權。

Oauth2技術應用的關鍵是:

1)服務器對OAuth2客戶端進行認證與授權。

2)Token的發放。

3)通過access_token訪問受OAuth2保護的資源。

選用的關鍵技術:Springboot, Spring-security, Spring-security-oauth2。

提供一個簡化版,用戶、token數據保存在內存中,用戶與客戶端的認證授權服務、資源服務,都是在同一個工程中。現實項目中,技術架構通常上將用戶與客戶端的認證授權服務設計在一個子系統(工程)中,而資源服務設計為另一個子系統(工程)。

1、Spring-security對用戶身份進行認證授權:

主要作用是對用戶身份通過用戶名與密碼的方式進行認證并且授權。

package com.banling.oauth2server.config; import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.security.authentication.AuthenticationManager;import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;import org.springframework.security.config.annotation.web.builders.HttpSecurity;import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;import org.springframework.security.web.util.matcher.AntPathRequestMatcher; @Configuration@EnableWebSecuritypublic class SecurityConfig extends WebSecurityConfigurerAdapter{@Autowired public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception { //用戶信息保存在內存中//在鑒定角色roler時,會默認加上ROLLER_前綴auth.inMemoryAuthentication().withUser('user').password('user').roles('USER').and().withUser('test').password('test').roles('TEST'); }@Override protected void configure(HttpSecurity http) throws Exception {http.formLogin() //登記界面,默認是permit All.and().authorizeRequests().antMatchers('/','/home').permitAll() //不用身份認證可以訪問.and().authorizeRequests().anyRequest().authenticated() //其它的請求要求必須有身份認證.and().csrf() //防止CSRF(跨站請求偽造)配置.requireCsrfProtectionMatcher(new AntPathRequestMatcher('/oauth/authorize')).disable(); }@Override @Bean public AuthenticationManager authenticationManagerBean() throws Exception {return super.authenticationManagerBean(); }}

配置用戶信息,保存在內存中。也可以自定義將用戶數據保存在數據庫中,實現UserDetailsService接口,進行認證與授權,略。

配置訪問哪些URL需要授權。必須配置authorizeRequests(),否則啟動報錯,說是沒有啟用security技術。

注意,在這里的身份進行認證與授權沒有涉及到OAuth的技術:

當訪問要授權的URL時,請求會被DelegatingFilterProxy攔截,如果還沒有授權,請求就會被重定向到登錄界面。在登錄成功(身份認證并授權)后,請求被重定向至之前訪問的URL。

2、OAuth2的授權服務:

主要作用是OAuth2的客戶端進行認證與授權。

package com.banling.oauth2server.config; import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.security.authentication.AuthenticationManager;import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;import org.springframework.security.oauth2.provider.approval.ApprovalStore;import org.springframework.security.oauth2.provider.approval.TokenApprovalStore;import org.springframework.security.oauth2.provider.token.TokenStore;import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore; @Configuration@EnableAuthorizationServerpublic class AuthServerConfig extends AuthorizationServerConfigurerAdapter{@Autowiredprivate TokenStore tokenStore;@Autowired private AuthenticationManager authenticationManager;@Autowiredprivate ApprovalStore approvalStore;@Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception {//添加客戶端信息//使用內存存儲OAuth客戶端信息clients.inMemory()// client_id.withClient('client')// client_secret.secret('secret')// 該client允許的授權類型,不同的類型,則獲得token的方式不一樣。.authorizedGrantTypes('authorization_code','implicit','refresh_token').resourceIds('resourceId')//回調uri,在authorization_code與implicit授權方式時,用以接收服務器的返回信息.redirectUris('http://localhost:8090/')// 允許的授權范圍.scopes('app','test'); }@Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {//reuseRefreshTokens設置為false時,每次通過refresh_token獲得access_token時,也會刷新refresh_token;也就是說,會返回全新的access_token與refresh_token。//默認值是true,只返回新的access_token,refresh_token不變。endpoints.tokenStore(tokenStore).approvalStore(approvalStore).reuseRefreshTokens(false).authenticationManager(authenticationManager); }@Override public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {security.realm('OAuth2-Sample').allowFormAuthenticationForClients().tokenKeyAccess('permitAll()').checkTokenAccess('isAuthenticated()'); }@Beanpublic TokenStore tokenStore() {//token保存在內存中(也可以保存在數據庫、Redis中)。//如果保存在中間件(數據庫、Redis),那么資源服務器與認證服務器可以不在同一個工程中。//注意:如果不保存access_token,則沒法通過access_token取得用戶信息return new InMemoryTokenStore();}@Beanpublic ApprovalStore approvalStore() throws Exception {TokenApprovalStore store = new TokenApprovalStore();store.setTokenStore(tokenStore);return store;}}

配置OAuth2的客戶端信息:clientId、client_secret、authorization_type、redirect_url等。本例是將數據保存在內存中。也可以保存在數據庫中,實現ClientDetailsService接口,進行認證與授權,略。

TokenStore是access_token的存儲單元,可以保存在內存、數據庫、Redis中。本例是保存在內存中。

3、OAuth2的資源服務:

主要作用是配置資源受保護的OAuth2策略。

package com.banling.oauth2server.config; import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Configuration;import org.springframework.security.config.annotation.web.builders.HttpSecurity;import org.springframework.security.config.http.SessionCreationPolicy;import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;import org.springframework.security.oauth2.provider.token.TokenStore; @Configuration@EnableResourceServerpublic class ResServerConfig extends ResourceServerConfigurerAdapter{@Autowiredprivate TokenStore tokenStore; @Override public void configure(ResourceServerSecurityConfigurer resources) throws Exception {resources.tokenStore(tokenStore).resourceId('resourceId'); } @Override public void configure(HttpSecurity http) throws Exception {/* 注意: 1、必須先加上: .requestMatchers().antMatchers(...),表示對資源進行保護,也就是說,在訪問前要進行OAuth認證。 2、接著:訪問受保護的資源時,要具有哪里權限。 ------------------------------------ 否則,請求只是被Security的攔截器攔截,請求根本到不了OAuth2的攔截器。 同時,還要注意先配置:security.oauth2.resource.filter-order=3,否則通過access_token取不到用戶信息。 ------------------------------------ requestMatchers()部分說明: Invoking requestMatchers() will not override previous invocations of :: mvcMatcher(String)}, requestMatchers(), antMatcher(String), regexMatcher(String), and requestMatcher(RequestMatcher). */http// Since we want the protected resources to be accessible in the UI as well we need // session creation to be allowed (it’s disabled by default in 2.0.6)//另外,如果不設置,那么在通過瀏覽器訪問被保護的任何資源時,每次是不同的SessionID,并且將每次請求的歷史都記錄在OAuth2Authentication的details的中.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED).and() .requestMatchers() .antMatchers('/user','/res/**') .and() .authorizeRequests() .antMatchers('/user','/res/**') .authenticated(); }}

配置哪些URL資源是受OAuth2保護的。注意,必須配置sessionManagement(),否則訪問受護資源請求不會被OAuth2的攔截器ClientCredentialsTokenEndpointFilter與OAuth2AuthenticationProcessingFilter攔截,也就是說,沒有配置的話,資源沒有受到OAuth2的保護。

4、受OAuth2保存的資源:

1)獲取OAuth2客戶端的信息

package com.banling.oauth2server.web; import java.security.Principal; import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController; @RestControllerpublic class UserController { @RequestMapping('/user')public Principal user(Principal principal) {//principal在經過security攔截后,是org.springframework.security.authentication.UsernamePasswordAuthenticationToken//在經OAuth2攔截后,是OAuth2Authentication return principal;}}

2)其它受保護的資源

package com.banling.oauth2server.web;import java.security.Principal; import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController; /** * 作為OAuth2的資源服務時,不能在Controller(或者RestController)注解上寫上URL,因為這樣不會被識別,會報404錯誤。<br> *<br> { *<br> 'timestamp': 1544580859138, *<br> 'status': 404, *<br> 'error': 'Not Found', *<br> 'message': 'No message available', *<br> 'path': '/res/getMsg' *<br> } *<br> * * */@RestController()//作為資源服務時,不能帶上url,@RestController('/res')是錯的,無法識別。只能在方法上注解全路徑public class ResController {@RequestMapping('/res/getMsg')public String getMsg(String msg,Principal principal) {//principal中封裝了客戶端(用戶,也就是clientDetails,區別于Security的UserDetails,其實clientDetails中也封裝了UserDetails),不是必須的參數,除非你想得到用戶信息,才加上principal。return 'Get the msg: '+msg;}}5、application.properties配置:

security.oauth2.resource.filter-order=3 必須配置,否則對受護資源請求不會被OAuth2的攔截器攔截。

6、測試

1)authorization_code方式獲取code,然后再通過code獲取access_token(和refresh_token)。

在瀏覽輸入:

http://localhost:8080/oauth/authorize?client_id=client&response_type=code&redirect_uri=http://localhost:8090/

在登錄界面輸入用戶名與密碼user/user,提交。

提交后服務重定向 至scope的授權界面:

Springboot開發OAuth2認證授權與資源服務器操作

授權后,在回調uri中可以得從code:

Springboot開發OAuth2認證授權與資源服務器操作

用postman工具,設置header的值,通過code獲取access_token與fresh_token:

Springboot開發OAuth2認證授權與資源服務器操作

2)implict方式接獲取access_token。

瀏覽器中輸入:

http://localhost:8080/oauth/authorize?client_id=client&response_type=token&redirect_uri=http://localhost:8090/

可以直接獲得access_token。

Springboot開發OAuth2認證授權與資源服務器操作

3)通過refresh_token獲取access_token與refresh_token。

用postman工具測試,根據refresh_token獲取新的access_token與fresh_token。

Springboot開發OAuth2認證授權與資源服務器操作

4)獲取OAuth2客戶端的信息。

可以通過get方式,也可以通過設置header獲取。

get方式,看url字符串:

Springboot開發OAuth2認證授權與資源服務器操作

設置header的方式:

Springboot開發OAuth2認證授權與資源服務器操作

5)訪問其它受保護的資源

Springboot開發OAuth2認證授權與資源服務器操作

github上的源碼: https://github.com/banat020/OAuth2-server

以上為個人經驗,希望能給大家一個參考,也希望大家多多支持好吧啦網。

標簽: Spring
相關文章:
主站蜘蛛池模板: 找培训机构_找学习课程_励普教育 | 德国进口电锅炉_商用电热水器_壁挂炉_电采暖器_电热锅炉[德国宝] | 纯化水设备-纯水设备-超纯水设备-[大鹏水处理]纯水设备一站式服务商-东莞市大鹏水处理科技有限公司 | 东莞市海宝机械有限公司-不锈钢分选机-硅胶橡胶-生活垃圾-涡电流-静电-金属-矿石分选机 | 科普仪器菏泽市教育教学仪器总厂| 仪器仪表网 - 永久免费的b2b电子商务平台 | 连栋温室大棚建造厂家-智能玻璃温室-薄膜温室_青州市亿诚农业科技 | 淬火设备-钎焊机-熔炼炉-中频炉-锻造炉-感应加热电源-退火机-热处理设备-优造节能 | 杜甫仪器官网|实验室平行反应器|升降水浴锅|台式低温循环泵 | 包塑丝_高铁绑丝_地暖绑丝_涂塑丝_塑料皮铁丝_河北创筹金属丝网制品有限公司 | KBX-220倾斜开关|KBW-220P/L跑偏开关|拉绳开关|DHJY-I隔爆打滑开关|溜槽堵塞开关|欠速开关|声光报警器-山东卓信有限公司 | 无轨电动平车_轨道平车_蓄电池电动平车★尽在新乡百特智能转运设备有限公司 | arch电源_SINPRO_开关电源_模块电源_医疗电源-东佑源 | 防弹玻璃厂家_防爆炸玻璃_电磁屏蔽玻璃-四川大硅特玻科技有限公司 | 组织研磨机-高通量组织研磨仪-实验室多样品组织研磨机-东方天净 传递窗_超净|洁净工作台_高效过滤器-传递窗厂家广州梓净公司 | 领袖户外_深度旅游、摄影旅游、小团慢旅行、驴友网 | 恒温水槽与水浴锅-上海熙浩实业有限公司| 广州昊至泉水上乐园设备有限公司 | 彼得逊采泥器-定深式采泥器-电动土壤采样器-土壤样品风干机-常州索奥仪器制造有限公司 | 高铝轻质保温砖_刚玉莫来石砖厂家_轻质耐火砖价格 | 防火卷帘门价格-聊城一维工贸特级防火卷帘门厂家▲ | 聚氨酯复合板保温板厂家_廊坊华宇创新科技有限公司 | 步进驱动器「一体化」步进电机品牌厂家-一体式步进驱动 | bng防爆挠性连接管-定做金属防爆挠性管-依客思防爆科技 | uv固化机-丝印uv机-工业烤箱-五金蚀刻机-分拣输送机 - 保定市丰辉机械设备制造有限公司 | 阜阳成人高考_阜阳成考报名时间_安徽省成人高考网 | 小型玉石雕刻机_家用玉雕机_小型万能雕刻机_凡刻雕刻机官网 | 海外整合营销-独立站营销-社交媒体运营_广州甲壳虫跨境网络服务 焊管生产线_焊管机组_轧辊模具_焊管设备_焊管设备厂家_石家庄翔昱机械 | 冷却塔风机厂家_静音冷却塔风机_冷却塔电机维修更换维修-广东特菱节能空调设备有限公司 | 中式装修设计_室内中式装修_【云臻轩】中式设计机构 | 地图标注|微信高德百度地图标注|地图标记-做地图[ZuoMap.com] | 华溶溶出仪-Memmert稳定箱-上海协烁仪器科技有限公司 | 便携式高压氧舱-微压氧舱-核生化洗消系统-公众洗消站-洗消帐篷-北京利盟救援 | 旋片真空泵_真空泵_水环真空泵_真空机组-深圳恒才机电设备有限公司 | 浙江筋膜枪-按摩仪厂家-制造商-肩颈按摩仪哪家好-温州市合喜电子科技有限公司 | 电采暖锅炉_超低温空气源热泵_空气源热水器-鑫鲁禹电锅炉空气能热泵厂家 | 渣油泵,KCB齿轮泵,不锈钢齿轮泵,重油泵,煤焦油泵,泊头市泰邦泵阀制造有限公司 | 地图标注|微信高德百度地图标注|地图标记-做地图[ZuoMap.com] | 不锈钢水管-不锈钢燃气管-卫生级不锈钢管件-不锈钢食品级水管-广东双兴新材料集团有限公司 | 视频直播 -摄影摄像-视频拍摄-直播分发| 动库网动库商城-体育用品专卖店:羽毛球,乒乓球拍,网球,户外装备,运动鞋,运动包,运动服饰专卖店-正品运动品网上商城动库商城网 - 动库商城 |