今天为大家带来一个优雅的使用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…