上篇文章介绍了OAuth2的一般过程和原理,并且使用GitHub作为认证服务器实战Client端的代码,本文在之前代码的基础上改造成可以鉴权的oauth2 server
初步讲解套路
还是以此图为例,写好server端一定要留意上图server中的三个模块:
- Resource Owner:即指需要授权访问的资源,比如用户昵称,头像
- Authorization Server:鉴权服务,核心鉴权逻辑
- Resource Server:资源服务
配合代码中的三个注解:
-
EnableAuthorizationServer
:配置授权服务 -
EnableResourceServer
:配置授权资源路径 -
EnableOAuth2Client
:配置Client信息
实战代码
修改WebSecurityConfig
:
@Configuration
@EnableOAuth2Client
@EnableAuthorizationServer
@Order(6)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserService userService;
@Autowired
OAuth2ClientContext oauth2ClientContext;
@Override
protected void configure(AuthenticationManagerBuilder auth)
throws Exception {
// Configure spring security's authenticationManager with custom
// user details service
auth.userDetailsService(this.userService);
}
@Override
@Bean // share AuthenticationManager for web and oauth
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/user/**").authenticated()
.anyRequest().permitAll()
.and().exceptionHandling()
.authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/login"))
.and()
.formLogin().loginPage("/login").loginProcessingUrl("/login.do").defaultSuccessUrl("/user/info")
.failureUrl("/login?err=1")
.permitAll()
.and().logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/")
.permitAll()
.and().addFilterBefore(githubFilter(), BasicAuthenticationFilter.class)
;
}
private Filter githubFilter() {
OAuth2ClientAuthenticationProcessingFilter githubFilter = new OAuth2ClientAuthenticationProcessingFilter("/login/github");
OAuth2RestTemplate githubTemplate = new OAuth2RestTemplate(githubClient().getClient(), oauth2ClientContext);
githubFilter.setRestTemplate(githubTemplate);
githubFilter.setTokenServices(new UserInfoTokenServices(githubClient().getResource().getUserInfoUri(), githubClient().getClient().getClientId()));
return githubFilter;
}
@Bean
@ConfigurationProperties("github")
public ClientResources githubClient() {
return new ClientResources();
}
@Bean
public FilterRegistrationBean oauth2ClientFilterRegistration(
OAuth2ClientContextFilter filter) {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(filter);
registration.setOrder(-100);
return registration;
}
@Configuration
@EnableResourceServer
protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http.antMatcher("/api/**").authorizeRequests().anyRequest().authenticated();
}
}
}
...
// client resource
public class ClientResources {
@NestedConfigurationProperty
private AuthorizationCodeResourceDetails client = new AuthorizationCodeResourceDetails();
@NestedConfigurationProperty
private ResourceServerProperties resource = new ResourceServerProperties();
public AuthorizationCodeResourceDetails getClient() {
return client;
}
public ResourceServerProperties getResource() {
return resource;
}
}
主要就加了@EnableAuthorizationServer
注解告诉spring启动Server模式,github登录跟上篇文章的代码一样,就是封装了一下,因为以前代码的注解ResourceServerProperties
会和spring 的EnableAuthorizationServer
冲突,加上了EnableResourceServer
,配置/api/**
底下的资源是需要权限的,重写AuthenticationManager
这个方法很重要,目的是将web登录和oauth登录的manager共享,不然只能有一方生效,这个想了解的可以读一读源码,一时解释不太清楚。
新加了UserRestController
:
@RestController
@RequestMapping("/api/users")
public class UserRestController {
@Autowired
IUserService userService;
@RequestMapping("")
public List<User> all() {
return userService.findAll();
}
}
普通业务。
最后在application-dev.yml
配置client信息,:
security:
oauth2:
client:
client-id: client
client-secret: secret
scope: read,write
auto-approve-scopes: '.*'
grant-type: password
basic:
enabled: false
可以看出这里的字段就对应上文做client端的字段信息。
运行效果
网页浏览器端没有任何变化,可以使用admin/admin
登录,也可以使用github登录。这应该和一般见到的网站一样了,测试client端可以使用curl
:
-
curl -u client:secret http://localhost:8090/oauth/token -d "username=admin&password=admin&scope=read&grant_type=password"
:先使用password
模式获取token,可以看到参数跟上篇文章讲解里的是一样的,获取到的json格式如下
{"access_token":"7e7b7ced-3747-43a2-8134-c7e6b87c6451","token_type":"bearer","refresh_token":"b254c018-e5c4-42e3-bd30-269657b6262b","expires_in":43199,"scope":"read"}
- 接下来就可以用token请求
/api
资源了:curl http://localhost:8090/api/users -H "Authorization: bearer 7e7b7ced-3747-43a2-8134-c7e6b87c6451"
,获取的User列表json:
[{"id":1,"username":"admin","password":"admin","role":"ROLE_ADMIN","enabled":true,"accountNonExpired":true,"accountNonLocked":true,"credentialsNonExpired":true,"authorities":[{"authority":"ROLE_ADMIN"}]}]
- 如果直接请求
curl http://localhost:8090/api/users
则返回鉴权失败:{"error":"unauthorized","error_description":"Full authentication is required to access this resource"}
一般向单页应用或手机APP大致是这样的流程了。
最后,现在这个Demo差不多完备了,自身的用户可以登录,第三方github等也可以登录,手机APP等移动端也可以登录,完整代码照例打了tag,github地址 v1.8。
发现有些新手不理解
curl
命令是如何转化为rest
请求的,在这里回来补充一下,上文中的curl -u client:secret http://localhost:8090/oauth/token -d "username=admin&password=admin&scope=read&grant_type=password"
命令简单来说可以换成curl -H "Authorization: Basic Y2xpZW50OnNlY3JldA==" http://localhost:8090/oauth/token -d "username=admin&password=admin&scope=read&grant_type=password"
,-H
命令是添加请求头信息,key
是Authorization
,value
中的Basic
是固定的代表基本认证(Basic
后面有一个空格),后面的字符串是认证信息比如client
+secret
字符串相加做base64
加密之后的加密串。
下篇文章将记录如何自定义上述功能,spring-security-oauth2
好多功能都是一个注解都封装好了,但是有时还是需要在自己的业务里做定制,国内需求环境你们都懂的。.