Spring Cloud Security 為構(gòu)建安全的SpringBoot應(yīng)用提供了一系列解決方案省容,結(jié)合Oauth2可以實(shí)現(xiàn)單點(diǎn)登錄、令牌中繼燎字、令牌交換等功能腥椒,本文將對(duì)其結(jié)合Oauth2入門使用進(jìn)行詳細(xì)介紹。
OAuth 2.0是用于授權(quán)的行業(yè)標(biāo)準(zhǔn)協(xié)議候衍。OAuth 2.0為簡(jiǎn)化客戶端開發(fā)提供了特定的授權(quán)流寞酿,包括Web應(yīng)用、桌面應(yīng)用脱柱、移動(dòng)端應(yīng)用等。
Resource owner(資源擁有者):擁有該資源的最終用戶拉馋,他有訪問資源的賬號(hào)密碼榨为;
Resource server(資源服務(wù)器):擁有受保護(hù)資源的服務(wù)器,如果請(qǐng)求包含正確的訪問令牌煌茴,可以訪問資源随闺;
Client(客戶端):訪問資源的客戶端,會(huì)使用訪問令牌去獲取資源服務(wù)器的資源蔓腐,可以是瀏覽器矩乐、移動(dòng)設(shè)備或者服務(wù)器;
Authorization server(認(rèn)證服務(wù)器):用于認(rèn)證用戶的服務(wù)器回论,如果客戶端認(rèn)證通過散罕,發(fā)放訪問資源服務(wù)器的令牌。
Authorization Code(授權(quán)碼模式):正宗的OAuth2的授權(quán)模式傀蓉,客戶端先將用戶導(dǎo)向認(rèn)證服務(wù)器欧漱,登錄后獲取授權(quán)碼,然后進(jìn)行授權(quán)葬燎,最后根據(jù)授權(quán)碼獲取訪問令牌误甚;
Implicit(簡(jiǎn)化模式):和授權(quán)碼模式相比缚甩,取消了獲取授權(quán)碼的過程,直接獲取訪問令牌窑邦;
Resource Owner Password Credentials(密碼模式):客戶端直接向用戶獲取用戶名和密碼擅威,之后向認(rèn)證服務(wù)器獲取訪問令牌;
Client Credentials(客戶端模式):客戶端直接通過客戶端認(rèn)證(比如client_id和client_secret)從認(rèn)證服務(wù)器獲取訪問令牌冈钦。
(A)客戶端將用戶導(dǎo)向認(rèn)證服務(wù)器郊丛;
(B)用戶在認(rèn)證服務(wù)器進(jìn)行登錄并授權(quán);
(C)認(rèn)證服務(wù)器返回授權(quán)碼給客戶端派继;
(D)客戶端通過授權(quán)碼和跳轉(zhuǎn)地址向認(rèn)證服務(wù)器獲取訪問令牌宾袜;
(E)認(rèn)證服務(wù)器發(fā)放訪問令牌(有需要帶上刷新令牌)。
(A)客戶端從用戶獲取用戶名和密碼驾窟;
(B)客戶端通過用戶的用戶名和密碼訪問認(rèn)證服務(wù)器庆猫;
(C)認(rèn)證服務(wù)器返回訪問令牌(有需要帶上刷新令牌)。
這里我們創(chuàng)建一個(gè)oauth2-server模塊作為認(rèn)證服務(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>Copy to clipboardErrorCopied
在application.yml中進(jìn)行配置:
server:
? port: 9401
spring:
? application:
? ? name: oauth2-serviceCopy to clipboardErrorCopied
添加UserService實(shí)現(xiàn)UserDetailsService接口月培,用于加載用戶信息:
/**
* Created by macro on 2019/9/30.
*/@ServicepublicclassUserServiceimplementsUserDetailsService{privateList<User>userList;@AutowiredprivatePasswordEncoderpasswordEncoder;@PostConstructpublicvoidinitData(){Stringpassword=passwordEncoder.encode("123456");userList=newArrayList<>();userList.add(newUser("macro",password,AuthorityUtils.commaSeparatedStringToAuthorityList("admin")));userList.add(newUser("andy",password,AuthorityUtils.commaSeparatedStringToAuthorityList("client")));userList.add(newUser("mark",password,AuthorityUtils.commaSeparatedStringToAuthorityList("client")));}@OverridepublicUserDetailsloadUserByUsername(Stringusername)throwsUsernameNotFoundException{List<User>findUserList=userList.stream().filter(user->user.getUsername().equals(username)).collect(Collectors.toList());if(!CollectionUtils.isEmpty(findUserList)){returnfindUserList.get(0);}else{thrownewUsernameNotFoundException("用戶名或密碼錯(cuò)誤");}}}Copy to clipboardErrorCopied
添加認(rèn)證服務(wù)器配置,使用@EnableAuthorizationServer注解開啟:
/**
* 認(rèn)證服務(wù)器配置
* Created by macro on 2019/9/30.
*/@Configuration@EnableAuthorizationServerpublicclassAuthorizationServerConfigextendsAuthorizationServerConfigurerAdapter{@AutowiredprivatePasswordEncoderpasswordEncoder;@AutowiredprivateAuthenticationManagerauthenticationManager;@AutowiredprivateUserServiceuserService;/**
? ? * 使用密碼模式需要配置
? ? */@Overridepublicvoidconfigure(AuthorizationServerEndpointsConfigurerendpoints){endpoints.authenticationManager(authenticationManager).userDetailsService(userService);}@Overridepublicvoidconfigure(ClientDetailsServiceConfigurerclients)throwsException{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")//配置申請(qǐng)的權(quán)限范圍.authorizedGrantTypes("authorization_code","password");//配置grant_type杉畜,表示授權(quán)類型}}Copy to clipboardErrorCopied
添加資源服務(wù)器配置,使用@EnableResourceServer注解開啟:
/**
* 資源服務(wù)器配置
* Created by macro on 2019/9/30.
*/@Configuration@EnableResourceServerpublicclassResourceServerConfigextendsResourceServerConfigurerAdapter{@Overridepublicvoidconfigure(HttpSecurityhttp)throwsException{http.authorizeRequests().anyRequest().authenticated().and().requestMatchers().antMatchers("/user/**");//配置需要保護(hù)的資源路徑}}Copy to clipboardErrorCopied
添加SpringSecurity配置衷恭,允許認(rèn)證相關(guān)路徑的訪問及表單登錄:
/**
* SpringSecurity配置
* Created by macro on 2019/10/8.
*/@Configuration@EnableWebSecuritypublicclassSecurityConfigextendsWebSecurityConfigurerAdapter{@BeanpublicPasswordEncoderpasswordEncoder(){returnnewBCryptPasswordEncoder();}@Bean@OverridepublicAuthenticationManagerauthenticationManagerBean()throwsException{returnsuper.authenticationManagerBean();}@Overridepublicvoidconfigure(HttpSecurityhttp)throwsException{http.csrf().disable().authorizeRequests().antMatchers("/oauth/**","/login/**","/logout/**").permitAll().anyRequest().authenticated().and().formLogin().permitAll();}}Copy to clipboardErrorCopied
添加需要登錄的接口用于測(cè)試:
/**
* Created by macro on 2019/9/30.
*/@RestController@RequestMapping("/user")publicclassUserController{@GetMapping("/getCurrentUser")publicObjectgetCurrentUser(Authenticationauthentication){returnauthentication.getPrincipal();}}Copy to clipboardErrorCopied
啟動(dòng)oauth2-server服務(wù)此叠;
在瀏覽器訪問該地址進(jìn)行登錄授權(quán):http://localhost:9401/oauth/authorize?response_type=code&client_id=admin&redirect_uri=http://www.baidu.com&scope=all&state=normal
輸入賬號(hào)密碼進(jìn)行登錄操作:
登錄后進(jìn)行授權(quán)操作:
之后會(huì)瀏覽器會(huì)帶著授權(quán)碼跳轉(zhuǎn)到我們指定的路徑:
https://www.baidu.com/?code=eTsADY&state=normalCopy to clipboardErrorCopied
使用授權(quán)碼請(qǐng)求該地址獲取訪問令牌:http://localhost:9401/oauth/token
使用Basic認(rèn)證通過client_id和client_secret構(gòu)造一個(gè)Authorization頭信息;
在body中添加以下參數(shù)信息随珠,通過POST請(qǐng)求獲取訪問令牌灭袁;
在請(qǐng)求頭中添加訪問令牌,訪問需要登錄認(rèn)證的接口進(jìn)行測(cè)試窗看,發(fā)現(xiàn)已經(jīng)可以成功訪問:http://localhost:9401/user/getCurrentUser
使用密碼請(qǐng)求該地址獲取訪問令牌:http://localhost:9401/oauth/token
使用Basic認(rèn)證通過client_id和client_secret構(gòu)造一個(gè)Authorization頭信息茸歧;
在body中添加以下參數(shù)信息,通過POST請(qǐng)求獲取訪問令牌显沈;
springcloud-learning
└── oauth2-server -- oauth2認(rèn)證測(cè)試服務(wù)