日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

Spring Cloud Security:Oauth2使用入门

發(fā)布時間:2024/10/6 javascript 38 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Spring Cloud Security:Oauth2使用入门 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

摘要


Spring Cloud Security 為構(gòu)建安全的SpringBoot應(yīng)用提供了一系列解決方案,結(jié)合Oauth2可以實現(xiàn)單點登錄、令牌中繼、令牌交換等功能,本文將對其結(jié)合Oauth2入門使用進行詳細介紹。

OAuth2 簡介


OAuth 2.0是用于授權(quán)的行業(yè)標準協(xié)議。OAuth 2.0為簡化客戶端開發(fā)提供了特定的授權(quán)流,包括Web應(yīng)用、桌面應(yīng)用、移動端應(yīng)用等。

OAuth2 相關(guān)名詞解釋


  • Resource owner(資源擁有者):擁有該資源的最終用戶,他有訪問資源的賬號密碼;
  • Resource server(資源服務(wù)器):擁有受保護資源的服務(wù)器,如果請求包含正確的訪問令牌,可以訪問資源;
  • Client(客戶端):訪問資源的客戶端,會使用訪問令牌去獲取資源服務(wù)器的資源,可以是瀏覽器、移動設(shè)備或者服務(wù)器;
  • Authorization server(認證服務(wù)器):用于認證用戶的服務(wù)器,如果客戶端認證通過,發(fā)放訪問資源服務(wù)器的令牌。

四種授權(quán)模式


  • Authorization Code(授權(quán)碼模式):正宗的OAuth2的授權(quán)模式,客戶端先將用戶導向認證服務(wù)器,登錄后獲取授權(quán)碼,然后進行授權(quán),最后根據(jù)授權(quán)碼獲取訪問令牌;
  • Implicit(簡化模式):和授權(quán)碼模式相比,取消了獲取授權(quán)碼的過程,直接獲取訪問令牌;
  • Resource Owner Password Credentials(密碼模式):客戶端直接向用戶獲取用戶名和密碼,之后向認證服務(wù)器獲取訪問令牌;
  • Client Credentials(客戶端模式):客戶端直接通過客戶端認證(比如client_id和client_secret)從認證服務(wù)器獲取訪問令牌。

兩種常用的授權(quán)模式

授權(quán)碼模式

  • (A)客戶端將用戶導向認證服務(wù)器;
  • (B)用戶在認證服務(wù)器進行登錄并授權(quán);
  • ?認證服務(wù)器返回授權(quán)碼給客戶端;
  • (D)客戶端通過授權(quán)碼和跳轉(zhuǎn)地址向認證服務(wù)器獲取訪問令牌;
  • (E)認證服務(wù)器發(fā)放訪問令牌(有需要帶上刷新令牌)。
授權(quán)碼模式

  • (A)客戶端從用戶獲取用戶名和密碼;
  • (B)客戶端通過用戶的用戶名和密碼訪問認證服務(wù)器;
  • ?認證服務(wù)器返回訪問令牌(有需要帶上刷新令牌)。

Oauth2的使用


創(chuàng)建oauth2-server模塊

這里我們創(chuàng)建一個oauth2-server模塊作為認證服務(wù)器來使用。

  • 在pom.xml中添加相關(guān)依賴:
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-oauth2</artifactId> </dependency> <dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-security</artifactId> </dependency> <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId> </dependency>
  • 在application.yml中進行配置:
server:port: 9401 spring:application:name: oauth2-service
  • 添加UserService實現(xiàn)UserDetailsService接口,用于加載用戶信息:
/*** Created by macro on 2019/9/30.*/ @Service public class UserService implements UserDetailsService {private List<User> userList;@Autowiredprivate PasswordEncoder passwordEncoder;@PostConstructpublic void initData() {String password = passwordEncoder.encode("123456");userList = new ArrayList<>();userList.add(new User("macro", password, AuthorityUtils.commaSeparatedStringToAuthorityList("admin")));userList.add(new User("andy", password, AuthorityUtils.commaSeparatedStringToAuthorityList("client")));userList.add(new User("mark", password, AuthorityUtils.commaSeparatedStringToAuthorityList("client")));}@Overridepublic UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {List<User> findUserList = userList.stream().filter(user -> user.getUsername().equals(username)).collect(Collectors.toList());if (!CollectionUtils.isEmpty(findUserList)) {return findUserList.get(0);} else {throw new UsernameNotFoundException("用戶名或密碼錯誤");}} }
  • 添加認證服務(wù)器配置,使用@EnableAuthorizationServer注解開啟:
/*** 認證服務(wù)器配置* Created by macro on 2019/9/30.*/ @Configuration @EnableAuthorizationServer public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {@Autowiredprivate PasswordEncoder passwordEncoder;@Autowiredprivate AuthenticationManager authenticationManager;@Autowiredprivate UserService userService;/*** 使用密碼模式需要配置*/@Overridepublic void configure(AuthorizationServerEndpointsConfigurer endpoints) {endpoints.authenticationManager(authenticationManager).userDetailsService(userService);}@Overridepublic void configure(ClientDetailsServiceConfigurer clients) throws Exception {clients.inMemory().withClient("admin")//配置client_id.secret(passwordEncoder.encode("admin123456"))//配置client_secret.accessTokenValiditySeconds(3600)//配置訪問token的有效期.refreshTokenValiditySeconds(864000)//配置刷新token的有效期.redirectUris("http://www.baidu.com")//配置redirect_uri,用于授權(quán)成功后跳轉(zhuǎn).scopes("all")//配置申請的權(quán)限范圍.authorizedGrantTypes("authorization_code","password");//配置grant_type,表示授權(quán)類型} }
  • 添加資源服務(wù)器配置,使用@EnableResourceServer注解開啟
/*** 資源服務(wù)器配置* Created by macro on 2019/9/30.*/ @Configuration @EnableResourceServer public class ResourceServerConfig extends ResourceServerConfigurerAdapter {@Overridepublic void configure(HttpSecurity http) throws Exception {http.authorizeRequests().anyRequest().authenticated().and().requestMatchers().antMatchers("/user/**");//配置需要保護的資源路徑} }
  • 添加SpringSecurity配置,允許認證相關(guān)路徑的訪問及表單登錄:
/*** SpringSecurity配置* Created by macro on 2019/10/8.*/ @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter {@Beanpublic PasswordEncoder passwordEncoder() {return new BCryptPasswordEncoder();}@Bean@Overridepublic AuthenticationManager authenticationManagerBean() throws Exception {return super.authenticationManagerBean();}@Overridepublic void configure(HttpSecurity http) throws Exception {http.csrf().disable().authorizeRequests().antMatchers("/oauth/**", "/login/**", "/logout/**").permitAll().anyRequest().authenticated().and().formLogin().permitAll();} }
  • 添加需要登錄的接口用于測試:
/*** Created by macro on 2019/9/30.*/ @RestController @RequestMapping("/user") public class UserController {@GetMapping("/getCurrentUser")public Object getCurrentUser(Authentication authentication) {return authentication.getPrincipal();} }
授權(quán)碼模式使用
  • 啟動oauth2-server服務(wù);
  • 在瀏覽器訪問該地址進行登錄授權(quán):http://localhost:9401/oauth/authorize?response_type=code&client_id=admin&redirect_uri=http://www.baidu.com&scope=all&state=norma
  • 輸入賬號密碼進行登錄操作:
  • 登錄后進行授權(quán)操作:
  • 之后會瀏覽器會帶著授權(quán)碼跳轉(zhuǎn)到我們指定的路徑:

https://www.baidu.com/?code=eTsADY&state=normal

  • 使用授權(quán)碼請求該地址獲取訪問令牌:http://localhost:9401/oauth/token
  • 使用Basic認證通過client_id和client_secret構(gòu)造一個Authorization頭信息;
  • 在body中添加以下參數(shù)信息,通過POST請求獲取訪問令牌;
  • 在請求頭中添加訪問令牌,訪問需要登錄認證的接口進行測試,發(fā)現(xiàn)已經(jīng)可以成功訪問:http://localhost:9401/user/getCurrentUser
密碼模式使用
  • 使用密碼請求該地址獲取訪問令牌:http://localhost:9401/oauth/token
  • 使用Basic認證通過client_id和client_secret構(gòu)造一個Authorization頭信息;
  • 在body中添加以下參數(shù)信息,通過POST請求獲取訪問令牌;

使用到的模塊


springcloud-learning └── oauth2-server -- oauth2認證測試服務(wù)

項目源碼地址


https://github.com/macrozheng/springcloud-learning

總結(jié)

以上是生活随笔為你收集整理的Spring Cloud Security:Oauth2使用入门的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。