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

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

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

首先引入依赖

<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,然后你会看见如下界面

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

然后点击Create按钮

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

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

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

接着点Show

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

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

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

是不是很简单方便,如果该starter对大家有帮助,可以点个star来支持我~,我会长期的去完善它和维护它,在使用的过程中遇见任何问题都可以在Github上提问,Github的地址是https://github.com/yuequan199…

    原文作者:月泉
    原文地址: https://segmentfault.com/a/1190000017123318
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞