今天爲大家帶來一個優雅的使用Spring Security OAuth2
的方案,通常我們在使用時需要去定義AuthorizationServer
和ResourceServer
之類的配置,而且整體寫起來非常Very Hard
(硬邦邦),不是硬編碼就是放Redis
或者JDBC
,但我怎麼管理我的那麼多Client
?在現在前後端分離的場景下,通常一個後端服務會提供client id
和client secret
給客戶端去做認證的請求,但有沒有考慮過如果有多個服務要依賴後端,難道全部採用一個client id
和client secret
?怎麼給他們做區分做限制?難道繼續硬編碼的加?特別是在現在非常流行的微服務上,我一個服務很有可能對應着很多個應用。所以我在這裏給大家推薦一個我個人認爲比較優雅的解決方案 Watchdog 歡迎大家Star
和PR
以及ISSUES
首先引入依賴
<dependency>
<groupId>org.yuequan</groupId>
<artifactId>watchdog-spring-boot-starter</artifactId>
<version>0.7.0.BETA</version>
</dependency>
然後執行項目中的Watchdog的schema.sql
地址在Github
點擊前往,建立所依賴的表配置好項目的DataSource
然後再啓動類上面添加@EnableWatchdog
@SpringBootApplication
@EnableWatchDog
public class WatchdogSampleApplication {
public static void main(String[] args) {
SpringApplication.run(WatchdogSampleApplication.class, args);
}
}
然後配置你的密碼加密方式和認證管理,例如:
@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
,然後你會看見如下界面
然後點擊Create
按鈕
輸入你應用的名字,回調地址和Scope
你可以不填,不填將使用默認的,然後點OK
接着點Show
可以點擊回調地址跳轉客戶端授權,也可以複製ClientID
和ClientSecret
進行password
認證
比如: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...