由于公司項目需要,進行SpringBoot集成Spring Security oauth2,幾乎搜尋網上所有大神的案例,苦苦不能理解,不能完全OK。
以下是借鑒各大神的代碼,終于demo完工,請欣賞
?
oauth2 定義了下面四種授權方式:
- 授權碼模式(authorization code)
- 簡化模式(implicit)
- 密碼模式(resource owner password credentials)
- 客戶端模式(client credentials)
具體每個模式的業務邏輯,請找百度君
以下是參數:
* response_type:表示授權類型,必選項,此處的值固定為"code"* client_id:表示客戶端的ID,必選項* redirect_uri:表示重定向URI,可選項* scope:表示申請的權限范圍,可選項* state:表示客戶端的當前狀態,可以指定任意值,認證服務器會原封不動地返回這個值。
先貼出項目結構:
直接貼代碼:
SpringBoot項目入口,服務啟動
package com.mingtong.demo_client;import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication public class DemoClientApplication {public static void main(String[] args) {SpringApplication.run(DemoClientApplication.class, args);} }
控制器Controller,獲取資源,后面可以改造JDBC獲取數據庫,或者遠程調用
@RestController @RequestMapping("/api") public class DemoController {@RequestMapping("/blog/{id}")public String getBlogById(@PathVariable long id) {return "this is blog "+id;} }
Oauth2認證服務
@Configuration @EnableAuthorizationServer public class OAuth2ServerConfig extends AuthorizationServerConfigurerAdapter {@Overridepublic void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {oauthServer.realm("oauth2-resources") //code授權添加.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()") //allow check token .allowFormAuthenticationForClients();}/*** 注入authenticationManager* 來支持 password grant type*/@Autowiredprivate AuthenticationManager authenticationManager;@Overridepublic void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {endpoints.authenticationManager(authenticationManager)//允許 GET、POST 請求獲取 token,即訪問端點:oauth/token .allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST);}@Overridepublic void configure(ClientDetailsServiceConfigurer clients) throws Exception {clients.inMemory().withClient("demoApp").secret("demoAppSecret").redirectUris("http://baidu.com")//code授權添加.authorizedGrantTypes("authorization_code","client_credentials", "password", "refresh_token").scopes("all").resourceIds("oauth2-resource").accessTokenValiditySeconds(1200).refreshTokenValiditySeconds(50000);}}
資源服務器:
@Configuration @EnableResourceServer public class ResourceServerConfig extends ResourceServerConfigurerAdapter {@Overridepublic void configure(HttpSecurity http) throws Exception {http.requestMatchers().antMatchers("/api/**").and() .authorizeRequests().antMatchers("/api/**").authenticated();}}
SpringSecurity配置
@EnableGlobalMethodSecurity(prePostEnabled = true) @EnableWebSecurity public class SecurityConfiguration extends WebSecurityConfigurerAdapter {@Overridepublic void configure(HttpSecurity http) throws Exception {http.csrf().disable();http.requestMatchers().antMatchers("/oauth/**","/login/**","/logout/**").and().authorizeRequests().antMatchers("/oauth/**").authenticated().and().formLogin().permitAll();}//配置內存模式的用戶 @Bean@Overrideprotected UserDetailsService userDetailsService(){InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();manager.createUser(User.withUsername("demoUser1").password("123456").authorities("USER").build());manager.createUser(User.withUsername("demoUser2").password("123456").authorities("USER").build());return manager;}/*** 需要配置這個支持password模式*/@Override@Beanpublic AuthenticationManager authenticationManagerBean() throws Exception {return super.authenticationManagerBean();} }
POM文件
<dependency><groupId>org.springframework.security.oauth</groupId><artifactId>spring-security-oauth2</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency>
【密碼授權模式-client】 密碼模式需要參數:username,password,grant_type,client_id,client_secret http://localhost:8080/oauth/token?username=demoUser1&password=123456&grant_type=password&client_id=demoApp&client_secret=demoAppSecret【客戶端授權模式-password】 客戶端模式需要參數:grant_type,client_id,client_secret http://localhost:8080/oauth/token?grant_type=client_credentials&client_id=demoApp&client_secret=demoAppSecret【授權碼模式-code】 獲取code http://localhost:8080/oauth/authorize?response_type=code&client_id=demoApp&redirect_uri=http://baidu.com
通過code換token http://localhost:8080/oauth/token?grant_type=authorization_code&code=Filepd&client_id=demoApp&client_secret=demoAppSecret&redirect_uri=http://baidu.com
祝君好運!
?