查看原文
其他

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

月泉 SpringForAll社区 2020-10-17

今天为大家带来一个优雅的使用 SpringSecurityOAuth2的方案,通常我们在使用时需要去定义 AuthorizationServerResourceServer之类的配置,而且整体写起来非常 VeryHard(硬邦邦),不是硬编码就是放 Redis或者 JDBC,但我怎么管理我的那么多 Client?在现在前后端分离的场景下,通常一个后端服务会提供 client idclient secret给客户端去做认证的请求,但有没有考虑过如果有多个服务要依赖后端,难道全部采用一个 client idclient secret?怎么给他们做区分做限制?难道继续硬编码的加?特别是在现在非常流行的微服务上,我一个服务很有可能对应着很多个应用。所以我在这里给大家推荐一个我个人认为比较优雅的解决方案 Watchdog 欢迎大家 StarPR以及 ISSUES

首先引入依赖

  1. <dependency>

  2.    <groupId>org.yuequan</groupId>

  3.    <artifactId>watchdog-spring-boot-starter</artifactId>

  4.    <version>0.7.0.BETA</version>

  5. </dependency>

然后执行项目中的Watchdog的 schema.sql地址在 Github点击前往,建立所依赖的表配置好项目的DataSource

然后再启动类上面添加 @EnableWatchdog

  1. @SpringBootApplication

  2. @EnableWatchDog

  3. public class WatchdogSampleApplication {

  4.    public static void main(String[] args) {

  5.        SpringApplication.run(WatchdogSampleApplication.class, args);

  6.    }

  7. }

然后配置你的密码加密方式和认证管理,例如:

  1. @Configuration

  2. public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

  3.    @Autowired

  4.    private PasswordEncoder passwordEncoder;

  5.    @Bean

  6.    public PasswordEncoder passwordEncoder(){

  7.        return new BCryptPasswordEncoder();

  8.    }

  9.    @Bean

  10.    @Override

  11.    protected AuthenticationManager authenticationManager() throws Exception {

  12.        return super.authenticationManager();

  13.    }

  14.    @Override

  15.    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

  16.        auth.inMemoryAuthentication()

  17.                .withUser("test")

  18.                .password(passwordEncoder.encode("123456"))

  19.                .authorities("USER");

  20.    }

  21. }

然后启动项目,在浏览器地址栏输入 http://localhost:8080/watchdog.html,然后你会看见如下界面

然后点击 Create按钮

输入你应用的名字,回调地址和 Scope你可以不填,不填将使用默认的,然后点 OK

接着点 Show

可以点击回调地址跳转客户端授权,也可以复制 ClientIDClientSecret进行 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/yuequan1997/watchdog-spring-boot-starter


推荐: 【SFA官方译】:使用Spring Security保护REST API

上一篇:我最喜爱的 Cloud Studio 插件评选大赛

关注公众号

点击原文参加


    您可能也对以下帖子感兴趣

    文章有问题?点此查看未经处理的缓存