Spring Cloud Security系列教程一:入门
本篇有一定的学习曲线,建议先花一点时间了解一下前置知识:
- Spring Security:http://docs.spring.io/spring-security/site/docs/4.2.2.RELEASE/reference/htmlsingle/
- OAuth2(重点),参考文档:http://www.ruanyifeng.com/blog/2014/05/oauth_2_0.html
- Spring Security OAuth2,参考文档:http://docs.spring.io/spring-boot/docs/1.5.2.RELEASE/reference/htmlsingle/#boot-features-security-oauth2
熟悉以上前置知识后,我们进入Spring Cloud Security的学习。在本例中,我们来使用GitHub的账号和密码来登录我们编写的应用。
准备工作
(1) 前往https://github.com/settings/developers,点击“Register a new application”按钮,添加一个应用。点击按钮后,界面如下图所示。
(2) 点击“Register application”按钮,即可出现如下图的界面。
记住这边的Client ID以及Client Secret,后面有用。
至此,准备工作就完成了。
编码
在这里,我们正式进行编码。
(1) 创建项目,并添加以下依赖:
1 | <parent> |
即:为应用添加spring-cloud-starter-oauth2、spring-cloud-starter-security两个依赖。
(2) 编写启动类:
1 |
|
如代码所示,在这里,我们使用@EnableOAuth2Sso
注解,启用了“基于OAuth2的单点登录”,做了一些安全配置;同时,还定义了两个端点,/welcome
端点返回“welcome”字符串,/user
端点返回当前登录用户的认证信息。
这里说明一下,@EnableOAuth2Sso
注解。如果WebSecurityConfigurerAdapter
类上注释了@EnableOAuth2Sso
注解,那么将会添加身份验证过滤器和身份验证入口。
- 如果只有一个
@EnableOAuth2Sso
注解没有编写在WebSecurityConfigurerAdapter
上,那么它将会为所有路径启用安全,并且会在基于HTTP Basic认证的安全链之前被添加。 - 详见
@EnableOAuth2Sso
的注释。
(3) 编写配置文件
1 | server: |
配置文件中的地址可参考该文档来配置:https://developer.github.com/v3/oauth/。
这样,代码就编写完成了。
测试
(1) 启动应用。
(2) 访问http://localhost:8080/login,将会跳转到GitHub,进行认证。
(3) 认证通过后,访问http://localhost:8080/user,可看到当前用户的信息。
(4) 访问http://localhost:8080/logout,可正常退出应用。
配套代码
(1) https://github.com/itmuch/spring-cloud-security-samples/tree/master/security-1
(2) http://git.oschina.net/itmuch/spring-cloud-security-samples/tree/master/security-1
评论系统未开启,无法评论!