Springboot开发OAuth2认证授权与资源服务器操作
设计并开发⼀个开放平台。
⼀、设计:
⽹关可以与认证授权服务合在⼀起,也可以分开。
⼆、开发与实现:
⽤Oauth2技术对访问受保护的资源的客户端进⾏认证与授权。
Oauth2技术应⽤的关键是:
1)服务器对OAuth2客户端进⾏认证与授权。
2)Token的发放。
3)通过access_token访问受OAuth2保护的资源。
选⽤的关键技术:Springboot, Spring-security, Spring-security-oauth2。
提供⼀个简化版,⽤户、token数据保存在内存中,⽤户与客户端的认证授权服务、资源服务,都是在同⼀个⼯程中。现实项⽬中,技术架构通常上将⽤户与客户端的认证授权服务设计在⼀个⼦系统(⼯程)中,⽽资源服务设计为另⼀个⼦系统(⼯程)。
1、Spring-security对⽤户⾝份进⾏认证授权:
主要作⽤是对⽤户⾝份通过⽤户名与密码的⽅式进⾏认证并且授权。
package com.fig;
import org.springframework.beans.factory.annotation.Autowired;
import t.annotation.Bean;
import t.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.fig.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.fig.annotation.web.builders.HttpSecurity;
import org.fig.figuration.EnableWebSecurity;
import org.fig.figuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{
@Autowired
public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
//⽤户信息保存在内存中
//在鉴定⾓⾊roler时,会默认加上ROLLER_前缀
auth.inMemoryAuthentication().withUser("user").password("user").roles("USER").and()
.withUser("test").password("test").roles("TEST");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin() //登记界⾯,默认是permit All
.and()
.authorizeRequests().antMatchers("/","/home").permitAll() //不⽤⾝份认证可以访问
.and()
.authorizeRequests().anyRequest().authenticated() //其它的请求要求必须有⾝份认证
.and()
.csrf() //防⽌CSRF(跨站请求伪造)配置
.requireCsrfProtectionMatcher(new AntPathRequestMatcher("/oauth/authorize")).disable();
}
springboot和过滤器
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
配置⽤户信息,保存在内存中。也可以⾃定义将⽤户数据保存在数据库中,实现UserDetailsService接⼝,进⾏认证与授权,略。
配置访问哪些URL需要授权。必须配置authorizeRequests(),否则启动报错,说是没有启⽤security技术。
注意,在这⾥的⾝份进⾏认证与授权没有涉及到OAuth的技术:
当访问要授权的URL时,请求会被DelegatingFilterProxy拦截,如果还没有授权,请求就会被重定向到
登录界⾯。在登录成功(⾝份认证并授权)后,请求被重定向⾄之前访问的URL。
2、OAuth2的授权服务:
主要作⽤是OAuth2的客户端进⾏认证与授权。
package com.fig;
import org.springframework.beans.factory.annotation.Autowired;
import t.annotation.Bean;
import t.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.figurers.ClientDetailsServiceConfigurer;
import org.springframework.fig.figuration.AuthorizationServerConfigurerAdapter;
import org.springframework.fig.figuration.EnableAuthorizationServer;
import org.springframework.fig.figurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.fig.figurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.approval.ApprovalStore;
import org.springframework.security.oauth2.provider.approval.TokenApprovalStore;
import org.springframework.security.ken.TokenStore;
import org.springframework.security.ken.store.InMemoryTokenStore;
@Configuration
@EnableAuthorizationServer
public class AuthServerConfig extends AuthorizationServerConfigurerAdapter{
@Autowired
private TokenStore tokenStore;
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private ApprovalStore approvalStore;
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
//添加客户端信息
//使⽤内存存储OAuth客户端信息
clients.inMemory()
// client_id
.withClient("client")
// client_secret
.secret("secret")
// 该client允许的授权类型,不同的类型,则获得token的⽅式不⼀样。
.authorizedGrantTypes("authorization_code","implicit","refresh_token")
.resourceIds("resourceId")
//回调uri,在authorization_code与implicit授权⽅式时,⽤以接收服务器的返回信息
.redirectUris("localhost:8090/")
// 允许的授权范围
.
scopes("app","test");
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
//reuseRefreshTokens设置为false时,每次通过refresh_token获得access_token时,也会刷新refresh_token;也就是说,会返回全新的access_token与refresh_token。
//默认值是true,只返回新的access_token,refresh_token不变。
.authenticationManager(authenticationManager);
}
@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
.allowFormAuthenticationForClients()
.tokenKeyAccess("permitAll()")
.checkTokenAccess("isAuthenticated()");
}
@Bean
public TokenStore tokenStore() {
//token保存在内存中(也可以保存在数据库、Redis中)。
//如果保存在中间件(数据库、Redis),那么资源服务器与认证服务器可以不在同⼀个⼯程中。
//注意:如果不保存access_token,则没法通过access_token取得⽤户信息
return new InMemoryTokenStore();
}
@Bean
public ApprovalStore approvalStore() throws Exception {
TokenApprovalStore store = new TokenApprovalStore();
store.setTokenStore(tokenStore);
return store;
}
}
配置OAuth2的客户端信息:clientId、client_secret、authorization_type、redirect_url等。本例是将数据保存在内存中。也可以保存在数据库中,实现ClientDetailsService接⼝,进⾏认证与授权,略。TokenStore是access_token的存储单元,可以保存在内存、数据库、Redis中。本例是保存在内存中。
3、OAuth2的资源服务:
主要作⽤是配置资源受保护的OAuth2策略。
package com.fig;
import org.springframework.beans.factory.annotation.Autowired;
import t.annotation.Configuration;
import org.fig.annotation.web.builders.HttpSecurity;
import org.fig.http.SessionCreationPolicy;
import org.springframework.fig.figuration.EnableResourceServer;
import org.springframework.fig.figuration.ResourceServerConfigurerAdapter;
import org.springframework.fig.figurers.ResourceServerSecurityConfigurer;
import org.springframework.security.ken.TokenStore;
@Configuration
@EnableResourceServer
public class ResServerConfig extends ResourceServerConfigurerAdapter{
@Autowired
private TokenStore tokenStore;
@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources
.tokenStore(tokenStore)
.resourceId("resourceId");
}
@Override
public void configure(HttpSecurity http) throws Exception {
/*
注意:
1、必须先加上: .requestMatchers().antMatchers(...),表⽰对资源进⾏保护,也就是说,在访问前要进⾏OAuth认证。
2、接着:访问受保护的资源时,要具有哪⾥权限。
------------------------------------
否则,请求只是被Security的拦截,请求根本到不了OAuth2的。
同时,还要注意先配置:source.filter-order=3,否则通过access_token取不到⽤户信息。
------------------------------------
requestMatchers()部分说明:
Invoking requestMatchers() will not override previous invocations of ::
mvcMatcher(String)}, requestMatchers(), antMatcher(String), regexMatcher(String), and requestMatcher(RequestMatcher).
*/
http
// Since we want the protected resources to be accessible in the UI as well we need
// session creation to be allowed (it's disabled by default in 2.0.6)
//另外,如果不设置,那么在通过浏览器访问被保护的任何资源时,每次是不同的SessionID,并且将每次请求的历史都记录在OAuth2Authentication的details的中
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
.and()
.requestMatchers()
.antMatchers("/user","/res/**")
.and()
.authorizeRequests()
.antMatchers("/user","/res/**")
.authenticated();
}
}
配置哪些URL资源是受OAuth2保护的。注意,必须配置sessionManagement(),否则访问受护资源请求不会被OAuth2的ClientCredentialsTokenEndpointFilter与
OAuth2AuthenticationProcessingFilter拦截,也就是说,没有配置的话,资源没有受到OAuth2的保护。
4、受OAuth2保存的资源:
1)获取OAuth2客户端的信息
package com.banling.oauth2server.web;
import java.security.Principal;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
@RequestMapping("/user")
public Principal user(Principal principal) {
//principal在经过security拦截后,是org.springframework.security.authentication.UsernamePasswordAuthenticationToken
//在经OAuth2拦截后,是OAuth2Authentication
return principal;
}
}
2)其它受保护的资源
package com.banling.oauth2server.web;
import java.security.Principal;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* 作为OAuth2的资源服务时,不能在Controller(或者RestController)注解上写上URL,因为这样不会被识别,会报404错误。<br>
*<br> {
*<br>    "timestamp": 1544580859138,
*<br>    "status": 404,
*<br>    "error": "Not Found",
*<br>    "message": "No message available",
*<br>    "path": "/res/getMsg"
*<br> }
*<br>
*
*
*/
@RestController()//作为资源服务时,不能带上url,@RestController("/res")是错的,⽆法识别。只能在⽅法上注解全路径
public class ResController {
@RequestMapping("/res/getMsg")
public String getMsg(String msg,Principal principal) {//principal中封装了客户端(⽤户,也就是clientDetails,区别于Security的UserDetails,其实clientDetails中也封装了UserDetails),不是必须的参数,除⾮你想得到⽤户信息,才加上principal。  return "Get the msg: "+msg;
}
}
5、application.properties配置:
source.filter-order=3 必须配置,否则对受护资源请求不会被OAuth2的拦截。
6、测试
1)authorization_code⽅式获取code,然后再通过code获取access_token(和refresh_token)。
在浏览输⼊:
在登录界⾯输⼊⽤户名与密码user/user,提交。
提交后服务重定向⾄scope的授权界⾯:
授权后,在回调uri中可以得从code:
⽤postman⼯具,设置header的值,通过code获取access_token与fresh_token:
2)implict⽅式接获取access_token。
浏览器中输⼊:
可以直接获得access_token。
3)通过refresh_token获取access_token与refresh_token。
⽤postman⼯具测试,根据refresh_token获取新的access_token与fresh_token。
4)获取OAuth2客户端的信息。
可以通过get⽅式,也可以通过设置header获取。
get⽅式,看url字符串:
设置header的⽅式:
5)访问其它受保护的资源
以上为个⼈经验,希望能给⼤家⼀个参考,也希望⼤家多多⽀持。