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

本文介绍了一种使用Watchdog简化Spring Security OAuth2客户端管理的方法。通过引入特定依赖和配置,可轻松创建、区分和限制多个服务的客户端身份,适用于微服务架构。

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

not recommended

首先引入依赖

<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

详情

可以点击回调地址跳转客户端授权,也可以复制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/yuequan199...

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值