今天爲你們帶來一個優雅的使用Spring Security OAuth2
的方案,一般咱們在使用時須要去定義AuthorizationServer
和ResourceServer
之類的配置,並且總體寫起來很是Very Hard
(硬邦邦),不是硬編碼就是放Redis
或者JDBC
,但我怎麼管理個人那麼多Client
?在如今先後端分離的場景下,一般一個後端服務會提供client id
和client secret
給客戶端去作認證的請求,但有沒有考慮過若是有多個服務要依賴後端,難道所有采用一個client id
和client secret
?怎麼給他們作區分作限制?難道繼續硬編碼的加?特別是在如今很是流行的微服務上,我一個服務頗有可能對應着不少個應用。因此我在這裏給你們推薦一個我我的認爲比較優雅的解決方案 Watchdog 歡迎你們Star
和PR
以及ISSUES
html
首先引入依賴java
<dependency> <groupId>org.yuequan</groupId> <artifactId>watchdog-spring-boot-starter</artifactId> <version>0.7.0.BETA</version> </dependency>
而後執行項目中的Watchdog的schema.sql
地址在Github
點擊前往,創建所依賴的表配置好項目的DataSource
git
而後再啓動類上面添加@EnableWatchdog
github
@SpringBootApplication @EnableWatchDog public class WatchdogSampleApplication { public static void main(String[] args) { SpringApplication.run(WatchdogSampleApplication.class, args); } }
而後配置你的密碼加密方式和認證管理,例如:spring
@Configuration public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private PasswordEncoder passwordEncoder; @Bean public PasswordEncoder passwordEncoder(){ return new BCryptPasswordEncoder(); } @Bean @Override protected AuthenticationManager authenticationManager() throws Exception { return super.authenticationManager(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("test") .password(passwordEncoder.encode("123456")) .authorities("USER"); } }
而後啓動項目,在瀏覽器地址欄輸入http://localhost:8080/watchdog.html
,而後你會看見以下界面sql
而後點擊Create
按鈕後端
輸入你應用的名字,回調地址和Scope
你能夠不填,不填將使用默認的,而後點OK
瀏覽器
接着點Show
前後端分離
能夠點擊回調地址跳轉客戶端受權,也能夠複製ClientID
和ClientSecret
進行password
認證ide
好比:http://localhost:8080/oauth/token?username=test&password=123456&grant_type=password&scope=DEFAULT&client_id=1327ea6b-a452-48a1-a3d3-a27c5f7ca9c5&client_secret=c4b16a0a-fb0e-470a-b6c4-73ddb4ee74b3
是否是很簡單方便,若是該starter
對你們有幫助,能夠點個star來支持我~,我會長期的去完善它和維護它,在使用的過程當中碰見任何問題均可以在Github上提問,Github的地址是https://github.com/yuequan199...