javascript
SpringSecruity整合Oauth2 详解(一)
文章目錄
- 一、創建項目添加依賴
- 二、添加application.properties
- 三、配置授權服務器
- 四、配置資源服務器
- 五、配置Spring Security
- 五、測試驗證
前言:上一章Oauth2 詳解介紹了Oauth2是干什么的,使用場景,運行原理以及授權模式。
這一章我們主要以密碼模式舉例
密碼模式:
第一步:用戶訪問用頁面時,輸入第三方認證所需要的信息(QQ/微信賬號密碼)
第二步:應用頁面那種這個信息去認證服務器授權
第三步:認證服務器授權通過,拿到token,訪問真正的資源頁面
一、創建項目添加依賴
創建Springboot Web項目 添加依賴
<?xml version="1.0" encoding="UTF-8"?> <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/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.sl</groupId><artifactId>spring-boot-security-oauth2</artifactId><version>1.0-SNAPSHOT</version><properties><java.version>1.8</java.version></properties><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.1.6.RELEASE</version><relativePath/> <!-- lookup parent from repository --></parent><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId><exclusions><exclusion><groupId>io.lettuce</groupId><artifactId>lettuce-core</artifactId></exclusion></exclusions></dependency><dependency><groupId>org.springframework.security.oauth</groupId><artifactId>spring-security-oauth2</artifactId><version>2.3.3.RELEASE</version></dependency><dependency><groupId>redis.clients</groupId><artifactId>jedis</artifactId></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build> </project>在依賴中添加了redis,因為redis有過期功能,很適合令牌存儲。
二、添加application.properties
spring.redis.database=0 spring.redis.host=localhost spring.redis.port=6379 spring.redis.jedis.pool.max-active=8 spring.redis.jedis.pool.max-idle=8 spring.redis.jedis.pool.max-wait=-1ms spring.redis.jedis.pool.min-idle=0三、配置授權服務器
授權范圍器和資源服務器可以是同一臺服務器,也可是不同服務器,這里是同一臺服務器
/*** @author shuliangzhao* @Title: AuthorizationServerConfig* @ProjectName spring-boot-learn* @Description: TODO* @date 2019/9/4 20:24*/ @Configuration @EnableAuthorizationServer public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {@Autowiredprivate AuthenticationManager authenticationManager;@Autowiredprivate RedisConnectionFactory redisConnectionFactory;@Autowiredprivate UserDetailsService userDetailsService;@Beanpublic PasswordEncoder passwordEncoder() {return new BCryptPasswordEncoder();}@Overridepublic void configure(ClientDetailsServiceConfigurer clients) throws Exception {clients.inMemory().withClient("password").authorizedGrantTypes("password","refresh_token")//表示授權模式支持password和refresh_token.accessTokenValiditySeconds(1800).resourceIds("rid")//配置資源id.scopes("all").secret("$2a$10$yjMPY5kUmnK2YRGt5zeaD.eaPHa7.wYxgLPb9pzmJBzDi1spupgty");//配置加密后的密碼}@Overridepublic void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {endpoints.tokenStore(new RedisTokenStore(redisConnectionFactory)).authenticationManager(authenticationManager).allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST).userDetailsService(userDetailsService);}@Overridepublic void configure(AuthorizationServerSecurityConfigurer security) throws Exception {//表示支持client_id和client_secretsecurity.allowFormAuthenticationForClients();}public static void main(String[] args) {String encode = new BCryptPasswordEncoder().encode("123");System.out.println(encode);}}自定義類AuthorizationServerConfig 繼承AuthorizationServerConfigurerAdapter ,完成對授權服務器的配置,然后通過直接@EnableAuthorizationServer開發授權服務器。
四、配置資源服務器
資源服務器
/*** @author shuliangzhao* @Title: ResourceServer* @ProjectName spring-boot-learn* @Description: TODO* @date 2019/9/4 20:37*/ @Configuration @EnableResourceServer public class ResourceServer extends ResourceServerConfigurerAdapter{@Overridepublic void configure(ResourceServerSecurityConfigurer resources) throws Exception {//配置資源id,這里的資源id和授權服務器的資源id一致。資源僅基于令牌認證resources.resourceId("rid").stateless(true);}@Overridepublic void configure(HttpSecurity http) throws Exception {http.authorizeRequests().antMatchers("/admin/**").hasRole("admin").antMatchers("/user/**").hasRole("user").anyRequest().authenticated();}}自定義類ResourceServer 繼承ResourceServerConfigurerAdapter,添加注解EnableResourceServer開啟資源服務器
五、配置Spring Security
/*** @author shuliangzhao* @Title: WebSecurityConfig* @ProjectName spring-boot-learn* @Description: TODO* @date 2019/9/4 20:41*/ @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter {@Bean@Overridepublic AuthenticationManager authenticationManagerBean() throws Exception {return super.authenticationManagerBean();}@Beanprotected UserDetailsService userDetailsService() {return super.userDetailsService();}@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {auth.inMemoryAuthentication().withUser("admin").password("$2a$10$yjMPY5kUmnK2YRGt5zeaD.eaPHa7.wYxgLPb9pzmJBzDi1spupgty").roles("admin").and().withUser("zhao").password("$2a$10$yjMPY5kUmnK2YRGt5zeaD.eaPHa7.wYxgLPb9pzmJBzDi1spupgty").roles("user");}@Overrideprotected void configure(HttpSecurity http) throws Exception {http.antMatcher("/oauth/**").authorizeRequests().antMatchers("/oauth/**").permitAll().and().csrf().disable();} }敲黑板:Spring security配置和資源服務器配置中,一共涉及了兩個HttpSecurity,其中Spring Security中的配置優先級高于資源服務器的配置,即請求地址先經過SpringSecurity的HttSecurity
五、測試驗證
@RestController public class Oauth2Controller {@GetMapping("/admin/hello")public String admin() {return "hello admin";}@GetMapping("/user/hello")public String user() {return "hello user";}@GetMapping("/hello")public String hello() {return "hello";} }所有配置完成后我們啟動項目,授權發送一個post請求獲取token
http://localhost:8080/oauth/token?username=zhao&password=123&grant_type=password&client_id=password&scope=all&client_secret=123
請求地址中參數包括用戶名,密碼,授權模式,客戶端id,scope以及客戶端密碼。返回信息:
返回結果又access_token,token_type,refresh_token,expires_in以及scope,其中access_token是獲取其它資源的令牌。refresh_tokn是刷新令牌,expires_in是過期時間。
刷新token的鏈接:
http://localhost:8080/oauth/token?grant_type=refresh_token&refresh_token=df8093e4-0c20-4157-8f1c-f0d071c75dff&client_id=password&client_secret=123
返回結果:
獲取訪問資源
http://localhost:8080/user/hello?access_token=9ff75b32-ece9-479f-bfea-c8deb42c172f
返回結果
hello user
總結
以上是生活随笔為你收集整理的SpringSecruity整合Oauth2 详解(一)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: OAuth 2.0 简介
- 下一篇: mybatis批量插入(insert)和