在SpringBoot中優雅的使用Spring Security OAuth 2

今天爲你們帶來一個優雅的使用Spring Security OAuth2的方案,一般咱們在使用時須要去定義AuthorizationServerResourceServer之類的配置,並且總體寫起來很是Very Hard(硬邦邦),不是硬編碼就是放Redis或者JDBC,但我怎麼管理個人那麼多Client?在如今先後端分離的場景下,一般一個後端服務會提供client idclient secret給客戶端去作認證的請求,但有沒有考慮過若是有多個服務要依賴後端,難道所有采用一個client idclient secret?怎麼給他們作區分作限制?難道繼續硬編碼的加?特別是在如今很是流行的微服務上,我一個服務頗有可能對應着不少個應用。因此我在這裏給你們推薦一個我我的認爲比較優雅的解決方案 Watchdog 歡迎你們StarPR以及ISSUEShtml

not recommended

首先引入依賴java

<dependency>
    <groupId>org.yuequan</groupId>
    <artifactId>watchdog-spring-boot-starter</artifactId>
    <version>0.7.0.BETA</version>
</dependency>

而後執行項目中的Watchdog的schema.sql地址在Github點擊前往,創建所依賴的表配置好項目的DataSourcegit

而後再啓動類上面添加@EnableWatchdoggithub

@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前後端分離

詳情

能夠點擊回調地址跳轉客戶端受權,也能夠複製ClientIDClientSecret進行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...

相關文章
相關標籤/搜索