Spring Security OAuth2.0认证授权四:分布式系统认证授权 (3)

完整代码如下:

@Autowired private AuthFilterCustom authFilterCustom; @Override protected void configure(HttpSecurity http) throws Exception { http.csrf() .disable() .authorizeRequests() // .antMatchers("/r/r1").hasAuthority("p2") // .antMatchers("/r/r2").hasAuthority("p2") .antMatchers("/**").authenticated()//所有的请求必须认证通过 .anyRequest().permitAll()//其它所有请求都可以随意访问 .and() .addFilterAfter(authFilterCustom, BasicAuthenticationFilter.class)//添加过滤器 .sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.STATELESS);//禁用session } 四、其他注意事项

认证服务auth-server以及资源服务resource-server、网关服务gateway-server都要集成eureka client组件

五、测试

测试前需要将各个服务依次启动起来:

启动注册中心 register-server:https://gitee.com/kdyzm/spring-security-oauth-study/tree/v5.0.0/register-server

启动网关 gateway-server:https://gitee.com/kdyzm/spring-security-oauth-study/tree/v5.0.0/gateway-server

启动认证服务 auth-server:https://gitee.com/kdyzm/spring-security-oauth-study/tree/v5.0.0/auth-server

启动资源服务 resource-server:https://gitee.com/kdyzm/spring-security-oauth-study/tree/v5.0.0/resource-server

第一步,获取token

这里使用password模式直接获取token,POST请求如下接口:

:30000/oauth/token?client_id=c1&client_secret=secret&grant_type=password&username=zhangsan&password=123

即可获取token。

第二步,访问资源

通过网关请求资源服务的r1接口,GET请求如下接口:

:8761/r1

需要带上Header,key为Authorization,value格式如下:

Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOlsicmVzMSJdLCJ1c2VyX25hbWUiOiJ6aGFuZ3NhbiIsInNjb3BlIjpbIlJPTEVfQURNSU4iLCJST0xFX1VTRVIiLCJST0xFX0FQSSJdLCJleHAiOjE2MTAzNzI5MzUsImF1dGhvcml0aWVzIjpbInAxIiwicDIiXSwianRpIjoiOWQzMzRmZGMtOTcwZC00YmJkLWI2MmMtZDU4MDZkNTgzM2YwIiwiY2xpZW50X2lkIjoiYzEifQ.gZraRNeX-o_jKiH7XQgg3TlUQBpxUcXa2-qR_Treu8U

如果相应结果如下,则表示测试通过

访问资源r1

否则,会返回401状态码。

六、项目源代码

项目源代码:https://gitee.com/kdyzm/spring-security-oauth-study/tree/v5.0.0

我的博客原文地址:https://blog.kdyzm.cn/post/30

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zyyddg.html