上篇文章介紹了OAuth2的一般過(guò)程和原理,并且使用GitHub作為認(rèn)證服務(wù)器實(shí)戰(zhàn)Client端的代碼煮落,本文在之前代碼的基礎(chǔ)上改造成可以鑒權(quán)的oauth2 server
初步講解套路
還是以此圖為例启搂,寫好server端一定要留意上圖server中的三個(gè)模塊:
- Resource Owner:即指需要授權(quán)訪問(wèn)的資源计维,比如用戶昵稱扫责,頭像
- Authorization Server:鑒權(quán)服務(wù),核心鑒權(quán)邏輯
- Resource Server:資源服務(wù)
配合代碼中的三個(gè)注解:
-
EnableAuthorizationServer
:配置授權(quán)服務(wù) -
EnableResourceServer
:配置授權(quán)資源路徑 -
EnableOAuth2Client
:配置Client信息
實(shí)戰(zhàn)代碼
修改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啟動(dòng)Server模式碰镜,github登錄跟上篇文章的代碼一樣兢卵,就是封裝了一下,因?yàn)橐郧按a的注解ResourceServerProperties
會(huì)和spring 的EnableAuthorizationServer
沖突绪颖,加上了EnableResourceServer
秽荤,配置/api/**
底下的資源是需要權(quán)限的,重寫AuthenticationManager
這個(gè)方法很重要柠横,目的是將web登錄和oauth登錄的manager共享窃款,不然只能有一方生效,這個(gè)想了解的可以讀一讀源碼牍氛,一時(shí)解釋不太清楚晨继。
新加了UserRestController
:
@RestController
@RequestMapping("/api/users")
public class UserRestController {
@Autowired
IUserService userService;
@RequestMapping("")
public List<User> all() {
return userService.findAll();
}
}
普通業(yè)務(wù)。
最后在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
可以看出這里的字段就對(duì)應(yīng)上文做client端的字段信息紊扬。
運(yùn)行效果
網(wǎng)頁(yè)瀏覽器端沒(méi)有任何變化,可以使用admin/admin
登錄唉擂,也可以使用github登錄餐屎。這應(yīng)該和一般見(jiàn)到的網(wǎng)站一樣了,測(cè)試client端可以使用curl
:
-
curl -u client:secret http://localhost:8090/oauth/token -d "username=admin&password=admin&scope=read&grant_type=password"
:先使用password
模式獲取token玩祟,可以看到參數(shù)跟上篇文章講解里的是一樣的腹缩,獲取到的json格式如下
{"access_token":"7e7b7ced-3747-43a2-8134-c7e6b87c6451","token_type":"bearer","refresh_token":"b254c018-e5c4-42e3-bd30-269657b6262b","expires_in":43199,"scope":"read"}
- 接下來(lái)就可以用token請(qǐng)求
/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"}]}]
- 如果直接請(qǐng)求
curl http://localhost:8090/api/users
則返回鑒權(quán)失敗:{"error":"unauthorized","error_description":"Full authentication is required to access this resource"}
一般向單頁(yè)應(yīng)用或手機(jī)APP大致是這樣的流程了藏鹊。
最后胜臊,現(xiàn)在這個(gè)Demo差不多完備了,自身的用戶可以登錄伙判,第三方github等也可以登錄,手機(jī)APP等移動(dòng)端也可以登錄黑忱,完整代碼照例打了tag宴抚,github地址 v1.8。
發(fā)現(xiàn)有些新手不理解
curl
命令是如何轉(zhuǎn)化為rest
請(qǐng)求的甫煞,在這里回來(lái)補(bǔ)充一下菇曲,上文中的curl -u client:secret http://localhost:8090/oauth/token -d "username=admin&password=admin&scope=read&grant_type=password"
命令簡(jiǎn)單來(lái)說(shuō)可以換成curl -H "Authorization: Basic Y2xpZW50OnNlY3JldA==" http://localhost:8090/oauth/token -d "username=admin&password=admin&scope=read&grant_type=password"
,-H
命令是添加請(qǐng)求頭信息抚吠,key
是Authorization
常潮,value
中的Basic
是固定的代表基本認(rèn)證(Basic
后面有一個(gè)空格),后面的字符串是認(rèn)證信息比如client
+secret
字符串相加做base64
加密之后的加密串楷力。
下篇文章將記錄如何自定義上述功能喊式,spring-security-oauth2
好多功能都是一個(gè)注解都封裝好了,但是有時(shí)還是需要在自己的業(yè)務(wù)里做定制萧朝,國(guó)內(nèi)需求環(huán)境你們都懂的岔留。.