|
# [' |9 m+ i' O8 E1 @
1、OAuth2.0 简介OAuth 2.0是用于授权的行业标准协议OAuth 2.0为简化客户端开发提供了特定的授权流,包括Web应用、桌面应用、移动端应用等1.1 OAuth2.0 相关名词解释Resource owner(资源拥有者):拥有该资源的最终用户,他有访问资源的账号密码;
% @4 A4 l: ~: T$ C% |% z/ q Resource server(资源服务器):拥有受保护资源的服务器,如果请求包含正确的访问令牌,可以访问资源;Client(客户端):访问资源的客户端,会使用访问令牌去获取资源服务器的资源,可以是浏览器、移动设备或者服务器; ! G7 y( _3 U- ^# y: E
Authorization server(认证服务器):用于认证用户的服务器,如果客户端认证通过,发放访问资源服务器的令牌1.2 四种授权模式Authorization Code(授权码模式):正宗的OAuth2的授权模式,客户端先将用户导向认证服务器,登录后获取授权码,然后进行授权,最后根据授权码获取访问令牌;。
- s$ \% x. w' _# t( d' A- P2 ` Implicit(简化模式):和授权码模式相比,取消了获取授权码的过程,直接获取访问令牌;Resource Owner Password Credentials(密码模式):客户端直接向用户获取用户名和密码,之后向认证服务器获取访问令牌; 9 i! {# f3 ~) w* H, D3 C6 t' [$ g
Client Credentials(客户端模式):客户端直接通过客户端认证(比如client_id和client_secret)从认证服务器获取访问令牌1.3 、OAuth2框架Spring Security提供了OAuth 2.0 完整支持,主要包括:。
7 [- H* y, g8 H8 q' w) D OAuth 2.0核心 - spring-security-oauth2-core.jar:包含为OAuth 2.0授权框架和OpenID Connect Core 1.0提供支持的核心类和接口;OAuth 2.0客户端 - spring-security-oauth2-client.jar:Spring Security对OAuth 2.0授权框架和OpenID Connect Core 1.0的客户端支持; , j" }9 e* N2 L- k' d# c
OAuth 2.0 JOSE - spring-security-oauth2-jose.jar:包含Spring Security对JOSE(Javascript对象签名和加密)框架的支持框架旨在提供安全地传输双方之间的权利要求的方法。 ' E) u% @: A" x- u
它由一系列规范构建: JSON Web令牌(JWT) JSON Web签名(JWS) JSON Web加密(JWE) JSON Web密钥(JWK)要使用OAuth2,需要引入spring-security-oauth2模块,通过之前源码分析,Spring 通过OAuth2ImportSelector类对Oauth2.0进行支持,当引入oauth2模块,Spring会自动启用 OAuth2 客户端配置 OAuth2ClientConfiguration。
' v! z1 ?$ \/ m/ B 1.4 OAuth 2.0客户端提供功能OAuth 2.0客户端功能为OAuth 2.0授权框架中定义的客户端角色提供支持 可以使用以下主要功能:授权代码授予客户凭证授权Servlet环境的WebClient扩展(用于发出受保护的资源请求)。
0 h8 d) H: s1 @2 S- G1 V HttpSecurity.oauth2Client()提供了许多用于自定义OAuth 2.0 Client的配置选项@EnableWebSecurity4 q* \' T9 K) S- ?+ v
public class OAuth2ClientSecurityConfig extends WebSecurityConfigurerAdapter {
! v1 l( h/ S' R
# v) e8 T/ L6 b* N, H6 }, R 。 9 f! I* H0 Q4 _ g
@Override
5 S5 s { s& a5 c# y+ Y protected void configure(HttpSecurity http) throws Exception {9 J! x" _4 T |6 O" {9 ?; t1 |
http.oauth2Client
4 r$ X& o* |6 H7 v2 {; c ()2 Q) l0 _% V$ V3 h7 {
.clientRegistrationRepository(this.clientRegistrationRepository())
& h8 }5 v7 G& Z6 O( I( M: O .authorizedClientRepository 5 {1 n5 S; ~! g, k+ P6 y. ^4 ~ {
(this.authorizedClientRepository()); g+ Z- E6 `; v' W, O3 }& K: s9 Q
.authorizedClientService(this.authorizedClientService 9 R q, A3 F4 x" Z; y7 O
())+ S, L( b" S" i1 S
.authorizationCodeGrant()
7 L4 J% r3 T5 c2 F .authorizationRequestRepository(this.authorizationRequestRepository ( q% g' y+ v) P1 O+ ~; D' S
())
7 f% W/ O( o- d& C .authorizationRequestResolver(this.authorizationRequestResolver())
4 _3 A+ Q& q! j7 T) } .accessTokenResponseClient
2 }4 n$ g# G% T5 T k5 ] (this.accessTokenResponseClient()); E- d8 f6 H8 m. C
}& w9 l5 ~$ T. R0 p" F0 ` I
}: W/ N! b: T6 h$ a! ^ u
2、OAuth 2.0 认证服务Spring Security OAuth2 实现了OAuth 2.0授权服务,简化了程序员对OAuth 2.0的实现,仅需要简单配置OAuth 2.0认证参数即可快速实现认证授权功能。 0 d2 I# B ]" q- w$ A# a" y
2.1 Spring Security OAuth2 提供的程序实现Spring Security OAuth2 中的提供者角色实际上是在授权服务和资源服务之间分配的,使用Spring Security OAuth2,您可以选择将它们拆分到两个应用程序中,并具有多个共享的资源服务授权服务。 7 h7 i* D$ ?& r( `- R+ p2 ^1 b
2.1.1 授权服务对令牌的请求由Spring MVC控制器端点处理,对受保护资源的访问由标准Spring Security请求过滤器处理为了实现OAuth 2.0授权服务器,Spring Security过滤器链中需要以下端点:。 3 J+ l4 d' _: o: A: i
AuthorizationEndpoint用于服务于授权请求预设网址:/oauth/authorizeTokenEndpoint用于服务访问令牌的请求预设网址:/oauth/token2.1.2 资源服务。 - U% @1 A+ |/ o8 H' g+ w
要实现OAuth 2.0资源服务器,需要以下过滤器:将OAuth2AuthenticationProcessingFilter用于加载的身份验证给定令牌的认证访问请求2.2 集成 OAuth 2.0 认证授权及资源管理。
/ `* A9 N0 K; V! |0 }/ ~8 d b 2.2.1 项目准备引入依赖org.springframework.bootspring-boot-starter-web 4 k. n% R" q+ C# [& R: X' N
org.springframework.boot
8 P5 g I7 i, q! O A4 w$ S1 { spring-boot-starter-securityorg.springframework.cloud 0 B( s2 M6 F9 u9 h
spring-cloud-starter-oauth22.2.1 配置授权服务在配置授权服务器时,必须考虑客户端用于从最终用户获取访问令牌的授予类型(例如,授权代码,用户凭据,刷新令牌)。 " ? M! I3 e1 `0 q
服务器的配置用于提供客户端详细信息服务和令牌服务的实现,并全局启用或禁用该机制的某些方面但是请注意,可以为每个客户端专门配置权限,使其能够使用某些授权机制和访问授权也就是说,仅因为您的提供程序配置为支持“客户端凭据”授予类型,并不意味着授权特定的客户端使用该授予类型。 $ ^& a- H! O' n) b. y: k
使用@EnableAuthorizationServer注解开启Oauth2认证@EnableAuthorizationServer批注用于配置OAuth 2.0授权服务器机制以及任何@Beans实现的机制。 # n" L. X5 o/ T8 E2 d7 }3 Q; ?
AuthorizationServerConfigurer(有一个便捷的适配器实现,其中包含空方法)以下功能委托给由Spring创建并传递到的单独的配置器AuthorizationServerConfigurer:。
1 q7 U+ F9 t( \1 d; h4 I8 X ClientDetailsServiceConfigurer:定义客户端详细信息服务的配置程序可以初始化客户详细信息,或者您可以仅引用现有商店AuthorizationServerSecurityConfigurer:定义令牌端点上的安全约束。
6 t. M3 V, ^( N+ R g AuthorizationServerEndpointsConfigurer:定义授权和令牌端点以及令牌服务提供者配置的一个重要方面是将授权代码提供给OAuth客户端的方式(在授权代码授予中)OAuth客户端通过将最终用户定向到授权页面来获得授权码,用户可以在该页面上输入她的凭据,从而导致从提供者授权服务器重定向回带有授权码的OAuth客户端。
1 ]* |, q) ]- K$ b6 N, x0 Z/ g 源码清单:@Configuration@EnableAuthorizationServer! v" @, H! i( W& }" l1 z
public class Oauth2ServerConfig extends AuthorizationServerConfigurerAdapter {, Q( T/ {3 q! b) U. Z; @/ g; R7 F! H
4 G* p: \* E4 B4 W4 K, I s* Q
, l Q5 \7 G$ l( a @Autowired. K1 b4 \# p# Y8 C" T
private PasswordEncoder passwordEncoder; e9 G- D9 k8 J7 ], z: ~
% O. b' ?- h( a1 O* H5 y# \ @Autowired
" o- B0 b5 ]% x+ v private AuthenticationManager authenticationManager;
; y, E3 ?) R" v' e7 K$ }! ^6 T: m L
- p! L4 W) f) x' Q @Autowired
8 O. C" e1 b; H" Z1 w) M private UserService userService;. d) A% f8 L, @! l) N
, i( g4 w: q+ F% h5 S3 n
/**
% P% U% H6 \6 u+ w * 自定义授权服务配置
# T' K0 Q9 W' Y% B- L: ?( U V5 V * 使用密码模式需要配置
- o6 L# n Y9 |& ~ */@Override
! I' p/ ]: X( W5 L public void configure(AuthorizationServerEndpointsConfigurer endpoints) {& M; P3 N- O" b/ N- t
! R! ?+ t. H# j2 U* [( _ P3 ]
endpoints.authenticationManager(authenticationManager)0 \4 p, ^: [( `( Y' }
.userDetailsService(userService);1 m1 s2 g* C& k: L3 g j9 z& Z: X4 @
}
5 H* K9 U4 K9 ~9 f& E
5 }+ Z+ M. d. n$ p1 U1 V+ x8 L
8 P1 L9 D- p* ^4 G$ ]0 f /**; Q' o1 D* R. F" b
* 配置认证客户端
/ E: X, j5 M% J * @param clients+ J- K3 T! D; p5 }' o( w1 w
* @throws Exception
' G" k/ X* H$ ~; e/ S4 j */
9 e* P- \2 E& d1 u @Overridepublicvoidconfigure(ClientDetailsServiceConfigurer clients)
, l1 A1 f# A- z3 W# i0 R throwsException {
$ [; ^8 x8 t0 [) M- F) j //自定义客户端配置
8 j, ~8 [, p; H2 z }
, _) m) H$ V7 v% T
% \0 B( x7 r T. R5 Z, ~' G( [ /**5 V2 _, J" I5 d, u6 v$ ]/ y8 A
* 自定义授权令牌端点的安全约束
" R$ S/ m. P) R \ Z * @param security9 E& h: O6 t+ V: O
* @throws Exception
$ u& K7 B5 h" t& j */ 1 N4 I# {7 d' Y/ Y3 ^" h6 H: U8 |2 m
@Override
/ r" a8 ^+ ?( Y. ]8 N) s public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
1 ~: J0 @2 J7 ^+ C+ U
- S8 R. Q$ I* X+ h% u //自定义安全约束//....
+ x; d( E! }/ ]: K7 { }9 r; l# o, V5 U1 W1 V# m
}
7 R& r I& g/ t& `& r5 } 2.2.1.1 授权服务配置AuthorizationServerEndpointsConfigurer 定义授权和令牌端点以及令牌服务endpoints.tokenStore 0 T4 \7 U. r/ I2 J9 n
(tokenStore)//自定义令牌存储策略//默认除密码模式外,所有授权模式均支持,密码模式需要显示注入authenticationManager开启.authenticationManager(authenticationManager)
+ L# u+ `! g/ @5 n2 e: g# J
1 A& a( k$ n+ P# Y Y5 O .userDetailsService(userDetailServiceImpl)//自定义用户密码加载服务.tokenGranter(tokenGranter)//定义控制授权.exceptionTranslator 1 c# J* h8 O: E
(webResponseExceptionTranslator);//自定义异常解析2.2.1.2 客户端加载策略配置将ClientDetailsServiceConfigurer(从您的回调AuthorizationServerConfigurer)可以用来定义一个内存中或JDBC实现客户的细节服务。
5 m+ Q' R3 s0 f6 w' K6 Q" x8 d: } 客户的重要属性是:clientId:(必填)客户端IDsecret:(对于受信任的客户端是必需的)客户端密钥(如果有)scope:客户端的范围受到限制如果范围未定义或为空(默认值),则客户端不受范围的限制。 # `* t. n1 [( d& }, i ]
authorizedGrantTypes:授权客户使用的授权类型默认值为空authorities:授予客户端的权限(常规的Spring Security权限)可以通过直接访问底层存储(例如的情况下为数据库表JdbcClientDetailsService)或通过ClientDetailsManager接口(这两种实现都ClientDetailsService可以实现)来更新正在运行的应用程序中的客户端详细信息。 0 U8 |% m# W- v2 O8 I
内存加载客户端配置,直接通过ClientDetailsServiceConfigurer添加客户端配置@Override. C+ I2 {; M/ `- @
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
) p( l. j, V! W6 U6 q
4 Y( N- Y& E" k7 G& g( X& H clients.inMemory()% A3 q+ n8 s' R2 `, }3 L
.withClient("admin")//配置client_id.secret(passwordEncoder.encode("admin123456"
# O$ r I; @3 f4 s: M D! b ))//配置client_secret.accessTokenValiditySeconds(3600)//配置访问token的有效期.refreshTokenValiditySeconds(864000
$ F% j9 Y ?, a )//配置刷新token的有效期.redirectUris("http://www.baidu.com")//配置redirect_uri,用于授权成功后跳转.scopes("all")//配置申请的权限范围
6 W$ O: F8 C5 l. ^& z8 F5 z# I I .authorizedGrantTypes("authorization_code","password","client_credentials","refresh_token");//配置grant_type,表示授权类型
" ~1 ]6 |0 ? _. B+ r' Q
/ w7 T. B/ g( w }
9 D# O$ T% z% d) U 自定义ClientDetailsService,redis+jdbc方式加载客户端缓存@Overridepublicvoidconfigure(ClientDetailsServiceConfigurer clients) 2 w1 S5 z$ }+ |8 A: e! h
throws Exception {
3 o9 @. N$ p# s8 S clients.withClientDetails(redisClientDetailsService);
) w6 @9 x0 {: w* f0 X# M5 C. v& Q; O redisClientDetailsService.loadAllClientToCache(); ) L* _* C* A7 I( C; y" W
//6 w. f! @9 g8 B+ m. x
}
; ?3 P1 H E0 }, V5 e' d7 g. D, C, b2 O# B0 k
@ServicepublicclassRedisClientDetailsServiceextendsJdbcClientDetailsService{
; s; Q" B5 A' h u0 @3 @( t //继承JdbcClientDetailsService,扩展redis缓存加载客户端,优先从缓存获取客户端配置,缓存没有再从数据库加载 , l; N) _" D" M1 |7 G" r( N/ t# p; `
2.2.1.3 令牌管理策略AuthorizationServerTokenServices定义了管理OAuth 2.0令牌所需的操作在开发过程需要注意:创建访问令牌后,必须存储身份验证,以便接受访问令牌的资源以后可以引用它。
5 `& g% c& G/ H1 H0 a& n5 X, z 访问令牌用于加载用于授权其创建的身份验证在创建AuthorizationServerTokenServices实现时,您可能需要考虑使用DefaultTokenServices,可以使用插入许多策略来更改访问令牌的格式和存储。
7 ^8 j6 }! b0 B8 i" s& |2 p 默认情况下,它会通过随机值创建令牌,并处理所有其他事务(除了将令牌委派给的令牌的持久性)TokenStore默认存储是内存中的实现InMemoryTokenStore对于单个服务器,默认设置非常合适(例如,低流量,并且在发生故障的情况下不与备份服务器进行热交换)。
. t& p$ \6 B& k& n( h5 F$ w 大多数项目都可以从此处开始,并且可以在开发模式下以这种方式运行,以轻松启动没有依赖性的服务器JdbcTokenStore是JDBC版本的同样的事情,它存储在关系数据库中令牌数据如果可以在服务器之间共享数据库,请使用JDBC版本;如果只有一个,则可以扩展同一服务器的实例;如果有多个组件,则可以使用Authorization and Resources Server。 6 p* X+ J- f) B( ^ w! Q
要使用,JdbcTokenStore您需要在类路径上使用“ spring-jdbc”存储的JSON Web令牌(JWT) 版本将有关授权的所有数据编码到令牌本身中(因此根本没有后端存储,这是一个很大的优势)。
8 a) [' J# B; ]% q 一个缺点是您不能轻易地撤销访问令牌,因此通常授予它们的期限很短,并且撤销是在刷新令牌处进行的另一个缺点是,如果您在令牌中存储了大量用户凭证信息,则令牌会变得很大JwtTokenStore是不是一个真正的“存储”在这个意义上,它不坚持任何数据,但它起着翻译令牌值和认证信息相同的角色DefaultTokenServices。 1 a; E/ _& Z# P
2.2.1.4 自定义定义UserService实现UserDetailsService@ComponentpublicclassUserServiceimplementsUserDetailsService : D# |1 P7 W' r3 a5 l8 R
{
% l3 ?7 `! x: `( @+ F. x* r
% n. T& Z. `$ L @Autowiredprivate QtAdminService qtAdminService;
2 J7 ]4 X W3 b' h/ {& h! f! N8 [& `4 V5 L l
( J* ]. j4 g( s# |6 N" } @Overridepublic UserDetails loadUserByUsername / Q' ^+ l- n# g% b: v/ h I$ ?) [
(String username)throws UsernameNotFoundException {
! L3 Q/ l! c: ? String clientId = "admin";" v* N L, O R4 R7 ~8 G( D
UserDto userDto = qtAdminService.loadUserByUsername(username);
! y7 P; N! t+ v6 W9 K* e N $ H3 X- o8 |' u9 j
if (userDto == null) {
[+ ?3 q' J, C6 ^6 m thrownew UsernameNotFoundException(MessageConstant.USERNAME_PASSWORD_ERROR);
0 L0 ]1 ]' L& ^- D4 K0 a }
1 o* Q2 q/ i" [6 a+ O2 I- Q4 R userDto.setClientId(clientId);& P7 c- P; m* W6 L0 |. X5 e; e
SecurityUser securityUser =
) Q) G8 b1 I1 ^5 d# \% M5 \) T" L+ S new SecurityUser(userDto);
) j! W. S4 n' ^! l8 Y0 r. c; H$ D if (!securityUser.isEnabled()) {
+ q6 o" _( Y' c1 P+ a5 W% O* }8 C thrownew DisabledException(MessageConstant.ACCOUNT_DISABLED);
" s) ]5 _- ]3 v" @) o' ? }
9 y# N* W( J6 S$ K l# s: O elseif (!securityUser.isAccountNonLocked()) {' \' _" G% b6 v, ^- G
thrownew LockedException(MessageConstant.ACCOUNT_LOCKED);) c) z/ X. [9 A3 J+ M
} 4 e. i) Q# S& ]) ]8 b; W
elseif (!securityUser.isAccountNonExpired()) {5 e' N# N- L L8 Z) h
thrownew AccountExpiredException(MessageConstant.ACCOUNT_EXPIRED);) e7 H$ I4 N4 e& B1 b( P& {& v
} ) U+ ^! I' D, i$ b3 i( m
elseif (!securityUser.isCredentialsNonExpired()) {% r& P# ]/ G9 Q- Y, s- l
thrownew CredentialsExpiredException(MessageConstant.CREDENTIALS_EXPIRED);
8 g6 a' e s, m! p! g$ i }
5 F: r1 M" f1 l. |) e7 R
; {# X6 } K$ K* n4 \9 L6 K& ] return securityUser;
2 b9 G2 ]" L" x- j5 a }* [- C$ G2 m5 K7 j& C
}
' z4 X+ h5 V0 D 2.2.1.5 定义令牌端点上的安全约束在对请求授权的端点进行访问之前需要对授权信息中传递的客户端信息进行认证,客户端认证通过后才会访问授权端点根据授权参数传递方式不同,对客户端进行认证的Filter也可能不一样:。
5 W9 ~ S, R: E5 `/ W 请求/oauth/token的,如果配置支持allowFormAuthenticationForClients的,且url中有client_id和client_secret的会走ClientCredentialsTokenEndpointFilter
! @+ a* z; u9 g! n2 W/ a 请求/oauth/token的,如果没有支持allowFormAuthenticationForClients或者有支持但是url中没有client_id和client_secret的,走BasicAuthenticationFilter认证 , B! \# }# e1 o5 q E
可以AuthorizationServerSecurityConfigurer添加客户端信息验证策略@Overridepublic void configure(AuthorizationServerSecurityConfigurer security) throws Exception {' W6 d% N! g# t5 k& V
security.tokenKeyAccess( . o v3 j9 S8 t; \5 i- V
"permitAll()")
2 d9 F H; @/ }( M .checkTokenAccess("isAuthenticated()")
' i( u+ ]% _$ t- j% r' C% S .addTokenEndpointAuthenticationFilter(customBasicAuthenticationFilter); . ], X9 g/ Q- X9 G+ |' N; h
//添加自定义客户端验证策略8 W- D$ d: \! ]2 n: Q
}
( S( d" N2 m3 Q! j2 q. }4 u( t* p! m j8 a P9 @6 } }0 ~8 w
//客户端验证策略控制public void configure(HttpSecurity http) throws Exception { a0 D/ ^! I: c) ~, o. R6 k0 L
this
6 f7 G, O+ G0 v- X- O+ J0 c K .frameworkEndpointHandlerMapping();
e) m. ^7 q$ `7 x. i- a' c1 |0 T if (this.allowFormAuthenticationForClients) {9 \0 T) |7 G7 o& q2 S$ G
this.clientCredentialsTokenEndpointFilter(http);
2 D7 N g. P8 G! P( P5 a }
0 w; _/ ?5 `+ h$ N( F9 N5 j
$ v1 p" ?& X" g/ ]( W- k Iterator var2 = 1 J! y' [) l" Z, H1 z0 u. g) B
this.tokenEndpointAuthenticationFilters.iterator();
' v3 a, e+ R6 Y" R7 _
( O0 x( M4 _, x while(var2.hasNext()) {3 O2 P( J# s7 r Q6 a( i
Filter filter = (Filter)var2.next();9 e3 F' B- B z" V+ H2 C
http.addFilterBefore(filter, BasicAuthenticationFilter " H% c u. P( E
.class);# V6 T3 w1 B/ \, c7 b' C
}/ |) ~, x7 g! @3 o
- K( Y7 i! N- f1 }& m2 u% E http.exceptionHandling().accessDeniedHandler(this.accessDeniedHandler);) A2 ^1 f8 Q# |
}
- t" `3 J/ ^) c8 p5 e7 ^* p. p% ?) j5 }4 _9 z
private
+ g. g% V2 x9 y$ t# ~ ClientCredentialsTokenEndpointFilter clientCredentialsTokenEndpointFilter(HttpSecurity http) {' b. N0 _/ T6 b3 E0 A
ClientCredentialsTokenEndpointFilter clientCredentialsTokenEndpointFilter = new ClientCredentialsTokenEndpointFilter( ! F# e3 ~- {! T8 d1 T
this.frameworkEndpointHandlerMapping().getServletPath("/oauth/token"));3 X4 O* V5 @% V5 L
clientCredentialsTokenEndpointFilter.setAuthenticationManager((AuthenticationManager)http.getSharedObject(AuthenticationManager ; ?, Q8 s8 x6 Q6 ~
.class));- X. o6 f! `) ?, C( n
OAuth2AuthenticationEntryPoint authenticationEntryPoint = new OAuth2AuthenticationEntryPoint();# R8 W( D6 Y0 e0 _$ ~
authenticationEntryPoint.setTypeName( 9 `5 n1 W, i3 z" S5 W
"Form");& U' x- s) v$ w5 E/ e+ `
authenticationEntryPoint.setRealmName(this.realm);
# W: G! t4 Y1 P0 Y1 j( y clientCredentialsTokenEndpointFilter.setAuthenticationEntryPoint(authenticationEntryPoint);4 F) n3 x( j" m7 Z
clientCredentialsTokenEndpointFilter = (ClientCredentialsTokenEndpointFilter)
3 ^7 Z6 r/ t' o this.postProcess(clientCredentialsTokenEndpointFilter);
+ E9 E$ |+ E, d! E. S0 x http.addFilterBefore(clientCredentialsTokenEndpointFilter, BasicAuthenticationFilter . h# @5 R0 @# O0 c0 ]& H- j
.class);return clientCredentialsTokenEndpointFilter;
9 Y5 b+ b' X% v9 }/ z }& i2 ]4 ~3 X# A2 b0 r
0 m: I" X9 q ~1 q* w* _) d0 E private ClientDetailsService clientDetailsService() {$ J$ T+ f: I# l* W
% z6 P& N0 G, y* {5 q* Z return (ClientDetailsService)((HttpSecurity)this.getBuilder()).getSharedObject(ClientDetailsService.class
1 n/ \% s2 G, `9 f );) e/ _" ?3 {1 e% J; K" Z7 r' q9 W
}" }, s% H2 N' W% }/ h; X; }
9 }4 x g) k- I6 t) x6 y/ H; l private FrameworkEndpointHandlerMapping frameworkEndpointHandlerMapping() {
9 j9 z( v; |8 @" b- G/ J( } return (FrameworkEndpointHandlerMapping)((HttpSecurity) 0 O1 `) k) }& ^5 J E6 W+ }
this.getBuilder()).getSharedObject(FrameworkEndpointHandlerMapping.class);
/ C/ ^3 e1 m7 H3 _. r3 @. g }: M' H5 _$ E- e- d6 A4 o6 r
' h" C7 t9 [1 l: [ public void addTokenEndpointAuthenticationFilter(Filter filter) {9 _" u+ t( U, B+ [" u
4 k! H( @" A, P
this.tokenEndpointAuthenticationFilters.add(filter);
+ d, X9 {/ r! }9 E% C; f2 V }1 b+ F; T( a( w/ `& N7 E3 `# r
2.2.2 添加SpringSecurity配置允许认证相关路径的访问及表单登录@Configuration
. I4 B1 \' R+ f% t+ P( E @EnableWebSecurity; c+ E1 ? r; P) W* v
public class SecurityConfig extends WebSecurityConfigurerAdapter {
' i7 h. N0 W" b7 z1 |0 S
6 u, R# g8 i9 W* T4 i @Bean
: {: W/ G" {% H6 B2 P6 w5 u public PasswordEncoder passwordEncoder() {- |' E0 y4 x1 x2 X8 c" d* y8 T
1 h& c4 q" b. _0 w R returnnewBCryptPasswordEncoder();
& [% X! a7 x/ m6 r }
4 @, S( @+ ^# e* z8 S0 \& I+ E" G c) K. `
@Bean! t( G/ e4 k8 }7 ]& d3 w
@OverridepublicAuthenticationManagerauthenticationManagerBean
o; H' j; d( j0 H$ n0 H) y () throwsException {
( U/ ]( ~' S( f# r returnsuper.authenticationManagerBean();$ m* }) v1 P, O3 l8 i; @
}" P. O( B3 Y/ z: t
* c$ V4 d8 ?) ~+ ?( y- m& N @Overridepublicvoidconfigure ; ?! b! z5 Y% d, m
(HttpSecurity http) throwsException {
. j9 d! O9 |3 ?2 M$ y+ ^# T http.csrf()9 n9 X% L4 ]. m( _2 f3 C
.disable()
' O( m7 _; V0 h* `, y .authorizeRequests()
! x$ R$ Y& Q! u/ a. v/ Z! X 4 l' b5 u P9 }4 J/ O
.antMatchers("/oauth/**", "/login/**", "/logout/**")
/ x! v7 O+ P% P. J* C( V .permitAll()8 k' g" C- J0 v0 v$ W/ i/ N
.anyRequest()
+ G) S! Z4 G: H c d& Q0 } ( ~* K1 h3 p6 P2 S. a4 V5 I# e5 T
.authenticated()5 k5 S3 Z1 z1 ?1 o7 k
.and()
* o) d8 Z v* h2 [4 T# x .formLogin()
, {, u. ]" Y; z, T9 U# S .permitAll();
4 K4 s/ T1 u6 @( P; V }
+ U: p# S. x% u$ q }/ c' G* K9 e! V: J: X, [2 U) t
2.2.3 Oauth2 验证启动应用,进行Oauth2 认证服务进行验证
; V+ N3 F9 {* X/ |, e Oauth2 密码模式验证使用密码请求该地址获取访问令牌:http://localhost:10001/oauth/token使用Basic认证通过client_id和client_secret构造一个Authorization头信息; " m. c( A2 b. D) @6 i _' N4 l) W
在body中添加以下参数信息,通过POST请求获取访问令牌; {
6 v N) C3 S, y) w "access_token": "a690d4e6-185f-4d1d-bc62-0067bd8b6ec9",
0 d0 W) P$ D. u# a+ i x "token_type" 0 a2 L% o8 i) @8 e* t$ Q% o
: "bearer",
( J: C6 _/ |6 r |# z "refresh_token": "55a04005-e2d9-44df-99df-01b57429d424",7 D& Z* V( C9 O, |1 ~
"expires_in": 3599,6 w% l! I: X8 q! P" H' {! e# n
2 j) F4 Q1 [8 C! ]
"scope": "all"
9 G! K2 f$ [$ R# k) ~5 z }& d8 V: P5 @) C4 _) d. f
2.3、Spring Security oauth2 授权认证核心源码分析OAuth2 授权认证大致可以分为两步:客户端认证Filter拦截/oauth/token请求,对授权参数传递的client_id和client_secret进行认证,认证通过继续访问/oauth/token端点; . `! g0 _ D# E* E7 ~6 B. O4 B
/oauth/token端点进行授权认证。2.3.1 /oauth/token 认证核心处理流程图 : r4 i3 b/ E0 y8 r, s2 y
2.3.2 TokenEndpoint(/oauth/token) 认证源码分析@RequestMapping(3 l* R! c7 C3 m
value = {"/oauth/token"},
9 z. D2 _" T" G method = {RequestMethod.POST}) Q1 E2 J7 M; _; e' l
)
& N: f' D, U- Z( D% {9 w) W public ResponseEntity postAccessToken(Principal principal, @RequestParam Map parameters) throws HttpRequestMethodNotSupportedException {! z8 t6 \$ j9 E) O. w" r
- l0 n# n- b0 O: D/ s" b if (!(principal instanceof Authentication)) {8 R* u r- }2 h: f
throw new InsufficientAuthenticationException("There is no client authentication. Try adding an appropriate authentication filter." $ L+ {# t; ^7 q- ]. ]# m
);3 Q: f2 F4 c& `
} else {; N4 ~3 }5 a( @6 s2 T% m
//1. 获取clientId
4 C1 h6 i! e3 B6 }9 f String clientId = this.getClientId(principal);0 Q2 k: u9 r1 C9 _, |3 i
//2. 根据客户端id加载客户端信息 0 G( }5 z8 l$ S0 I9 b# S
7 ^+ h8 N4 Q* G+ ?/ b
ClientDetails authenticatedClient = this.getClientDetailsService().loadClientByClientId(clientId);
+ f) v0 P6 X d9 f z6 o
o$ U7 {6 ^1 }- {; o //3. 根据客户端信息和请求参数组装TokenRequest4 Z/ H! m' K2 I- X& x: L; l1 _5 d/ z
TokenRequest tokenRequest = this.getOAuth2RequestFactory().createTokenRequest(parameters, authenticatedClient);
% k8 N, B4 |. l* j9 ~9 p( Q0 J : D a; I O4 [8 k5 ]9 B. ~
//4. 有没有传clientId验证if (clientId != null && !clientId.equals("") && !clientId.equals(tokenRequest.getClientId())) {' Z& {3 U( {: w. w2 e5 S/ @
6 M) a, q4 Y$ P/ y: z throw new InvalidClientException("Given client ID does not match authenticated client");3 l9 H2 ?# \) B1 }$ }
} else & b) i/ \0 N, l1 |4 I
{
% c3 O- Q" N9 R& G1 P; ^( q if (authenticatedClient != null) {1 _, {: H- B8 D
//5. 授权范围scope校验this.oAuth2RequestValidator.validateScope(tokenRequest, authenticatedClient);
" z+ v; B3 ?; t0 ?# h2 ` }
# s( }: o/ k' a5 x. ], n- V 6 R) D4 x2 J+ r3 P
//6. grant_type是否存在值,对应四种授权模式和刷新tokenif (!StringUtils.hasText(tokenRequest.getGrantType())) {
0 I1 ]1 d0 T2 s4 c/ T: U 0 m( Q% t) c$ p, m0 {1 L6 ~
throw new InvalidRequestException("Missing grant type");
$ _* Q, Y8 D9 a0 E8 C //是否简化模式3 v' |. p5 p7 [* Z7 u
} elseif (tokenRequest.getGrantType().equals( 0 q3 L! M$ F# k8 g; V
"implicit")) {6 P& C) X) [% G, T+ I+ p
throw new InvalidGrantException("Implicit grant type not supported from token endpoint" / W" C1 b; |- Q' J( j; m
);0 i2 d8 D* v _4 ~/ v, W
} else {3 K: @, n% @ i: e
//是否是授权码模式if (this.isAuthCodeRequest(parameters) && !tokenRequest.getScope().isEmpty()) {; h. F) A% d$ ]. k" A. `
1 h+ k& x4 I: d this.logger.debug("Clearing scope of incoming token request");
7 m: }* x# Z' `8 I- R tokenRequest.setScope(Collections.emptySet());7 @& K: t7 f% ^% n' M
}" b+ z8 T' V' H
7 T: `5 r1 B+ }5 e //是否刷新令牌if (this.isRefreshTokenRequest(parameters)) {) Q/ _' ?' I. g$ S* {" s
tokenRequest.setScope(OAuth2Utils.parseParameterList((String)parameters. 5 A9 ?+ k! ~/ f# W- [& f* O3 L
get("scope")));
f" m) O. d' A }/ _- Z j0 j1 T Z- X9 i" `
//7. 授权控制,并返回AccessToken
( {- y9 T9 m J+ B OAuth2AccessToken token = this
( } o; c. F# P2 u+ h! x2 p .getTokenGranter().grant(tokenRequest.getGrantType(), tokenRequest);: |5 k5 D( ]# i& ? p, M# I3 L
if (token == null) {: {& w& X j+ K- N P
2 M, u) Z' y! u2 o3 x# q2 G
throw new UnsupportedGrantTypeException("Unsupported grant type: " + tokenRequest.getGrantType());/ e7 u+ X. L$ H
}
" r/ h4 n2 ]4 ?$ b5 Z9 Z5 ` else {
6 U& o* s9 q9 U+ Y! L returnthis.getResponse(token);5 \( [, A5 W" K+ u
}
# A4 p% D b% v( ]' z6 O$ d }5 C7 u9 F2 l! c: Y+ ?6 f& \+ O
}
, I7 f9 N s" P' Z' H }
2 ?) z. x. w9 J2 ^ }
5 i6 l. S% c" q$ \2 u. H- k3 y @ 2.4 资源服务器2.4.1 资源服务器配置
0 w @0 j$ r0 ~) `$ t 资源服务器(可以与授权服务器或单独的应用程序相同)提供受OAuth2令牌保护的资源Spring OAuth提供了实现此保护的Spring Security身份验证过滤器您可以@EnableResourceServer在@Configuration类上将其打开,并使用进行配置(根据需要)ResourceServerConfigurer。
; {9 ^8 Y- V& R* k3 I1 R R: K9 h 可以配置以下功能:tokenServices:定义令牌服务(的实例ResourceServerTokenServices)的bean resourceId:资源的ID(可选,但建议使用,并且将由auth服务器验证(如果存在))。 2 }$ e( {4 x1 K4 X) z
资源服务器的其他扩展点(例如,tokenExtractor用于从传入请求中提取令牌)请求受保护资源的匹配器(默认为全部)受保护资源的访问规则(默认为普通的“已认证”)HttpSecuritySpring Security中配置程序允许的受保护资源的其他自定义 0 }! s' P9 [ k% c" u* A
该@EnableResourceServer注释添加类型的过滤器OAuth2AuthenticationProcessingFilter 自动Spring Security的过滤器链 代码清单:@Configuration。
c4 G$ a3 I+ z T. [ @EnableResourceServer1 S4 M6 D6 b! r Q8 Q4 x
public class Oauth2SourceConfig {
( E P; l2 I( Q/ t
' W9 S7 W2 e! H) I: G //配置资源url保护策略@Override- j0 _1 y+ V, [# J" @2 z# x; k
public void configure(HttpSecurity http) throws Exception {3 N( Y# l# n1 ?/ h, m$ p
" Y- a0 o. b# c, B3 B" `$ b
http.authorizeRequests()
# o5 t* ]: s' |# f# W8 w# O- I9 u .anyRequest(); _- E2 P" @# U% x- a$ {: S
.authenticated()
: X+ {; E" y8 [' P .and()2 E( i! j8 Q, z: A. k! }
.requestMatchers $ z# ]0 W9 q: W! R2 a9 {# b
()
$ M0 z4 j9 P+ o; { .antMatchers("/user/**");//配置需要保护的资源路径
& y. a) g8 t" I% v }
( H, b: @; u' w7 a7 v% S3 H3 `+ j+ l! q( m, ~+ S& C& h' N
//自定义资源保护令牌策略publicvoidconfigure(ResourceServerSecurityConfigurer resources)
, g3 [+ P: r' B8 M" Q2 X1 R0 Y. D$ G/ _ throwsException {- p: F% R& B6 H9 c- L2 i
resources.tokenStore(tokenStore);
& C% j: J" ~( U }
4 Y& J9 `6 P7 R+ _- _# x }" P3 t) _8 T: O7 V
2.4.2 使用令牌获取受保护资源
0 X" x4 {4 ?9 C/ N. t( M 2.4.3 源码分析2.4.3.1 OAuth2AuthenticationProcessingFilter资源服务认证入口FilterpublicclassOAuth2AuthenticationProcessingFilter 0 x3 C1 S4 H$ x* K# G
implementsFilter, InitializingBean{
8 F% X$ m8 h) i9 K+ A //省略......publicvoiddoFilter(ServletRequest req, ServletResponse res, FilterChain chain) 2 x7 T2 e$ Z- ]/ ? M8 ~
throws IOException, ServletException {
& G, _1 p* O2 S' `- x5 x boolean debug = logger.isDebugEnabled();
2 Y4 O6 i0 j9 r: q- Y7 m" v HttpServletRequest request = (HttpServletRequest)req;- y: x3 }/ T$ E% u+ y+ |! p% D6 v
HttpServletResponse response = (HttpServletResponse)res;
. `9 e1 {4 j; I$ _$ w2 s) f
8 ]# }9 s& N) x! b3 n
) y7 r: C3 d4 ?* i/ K0 F try {2 y0 f; \$ n1 F9 N9 T
//1. 从BearerTokenExtractor 获取Authentication 信息1 \4 D; j/ _* V: \% e- ^
Authentication authentication = this
$ U; K A4 h' O7 N7 E" x7 W .tokenExtractor.extract(request);
, y2 |& e# X# K5 Y. z0 \! r: T if (authentication == null) {
2 a6 }& i; F! X$ i5 k& ^# ] if (this.stateless && this
3 f4 r+ L5 n- P4 @ .isAuthenticated()) {: h- l4 S. D2 p7 v# a1 X3 z& N
if (debug) {, y* L( Z! q4 H& }" s. g
logger.debug("Clearing security context.");# J% u) Y% r z. `, B7 \2 p
}
0 g, r3 ~3 y# t5 t7 W9 c
1 Z1 y! o3 C% F SecurityContextHolder.clearContext();
; `6 G) R& A. Q3 a# w, u7 G }8 Y9 g Z" {" _2 w5 `1 ]/ @7 I8 W
. I) f+ v* D, M& n, l
& }! l R' F- `1 r) X7 W' Q if (debug) {
+ H4 |7 ~! H# R logger.debug("No token in request, will continue chain.");
- n% m1 p: h4 d7 W% O+ P2 [' v }4 j! f: E/ G, Q' ]
} else
: k, A* ]7 p$ L D5 E; E {" l) K3 E: t3 i6 U$ J5 n
request.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_VALUE, authentication.getPrincipal());
9 S& K3 c! n& ?2 {% A; z& d 2 r& ^9 G' `; n5 p: e
if (authentication instanceof AbstractAuthenticationToken) {
% ?8 Y( Z2 i$ \$ I( m- A: ^ AbstractAuthenticationToken needsDetails = (AbstractAuthenticationToken)authentication;7 M! v, [7 P3 U% ]# L: ]2 I* A4 a* V
needsDetails.setDetails( 3 a7 R+ j- I. F2 `
this.authenticationDetailsSource.buildDetails(request));
& s0 G" Q8 H. u4 {; j$ Y }
" A; n, K0 L5 f5 o! B E //2. OAuth2AuthenticationManager 进行token认证 " D% a3 V2 |& x' ~& V: G! N
! H3 d3 E" ~$ o
Authentication authResult = this.authenticationManager.authenticate(authentication);
- H5 P' V' h& n
* g# [1 y& g5 k* I5 S: w" M2 R if (debug) {
3 A) M1 R' S/ T* Q logger.debug("Authentication success: " + authResult);& d( Z7 t9 J7 Z5 K0 S5 k
}( R$ m2 [: K: I+ ^# @% P. y
//3. 将认证结果放置SecurityContextHolder上下文
5 m) y N/ I2 t; r this.eventPublisher.publishAuthenticationSuccess(authResult);0 Z" m) |3 l2 k0 M$ q6 v. g+ A
SecurityContextHolder.getContext().setAuthentication(authResult);! c. S% X4 X! n/ F9 m
}8 \4 m' ~" n. Z0 V3 P
} 8 q: z% x+ X2 L9 Z8 z4 Z
catch (OAuth2Exception var9) {
# r4 A% {' U2 M SecurityContextHolder.clearContext();
) I3 I+ S5 g+ m4 Z, ~: v/ p if (debug) {. K3 @' U8 u) B
logger.debug(
( J! Q$ h6 v) ?6 H "Authentication request failed: " + var9);
/ o7 E0 p( X) B- ?$ B& G+ ^: ` }
& o( N1 ]3 ]; a" q0 { P/ Y. L3 U1 j
this.eventPublisher.publishAuthenticationFailure(
. t% W- z2 N4 V# a j new BadCredentialsException(var9.getMessage(), var9), new PreAuthenticatedAuthenticationToken("access-token" - A9 Y. z7 A/ Y# B" c
, "N/A"));# p8 n* ~2 a; V7 W
this.authenticationEntryPoint.commence(request, response, new InsufficientAuthenticationException(var9.getMessage(), var9));" I _ K8 Y7 t7 G- L g
9 J: Y3 I% f( W" y2 A3 u8 o9 {
return;1 k* i- @9 j0 q3 J6 }' @: W; Z
}
9 `4 Y/ T. J) j, t6 g3 w% I7 n6 @, w2 L
chain.doFilter(request, response);
- K! a7 v4 a. ~; V1 ] }
; V; t) p' R( g% h1 N' J
8 P1 s' _5 {; U //省略......
* `6 r% m4 a1 m2 t4 @* d+ o" | } l" J1 X k! M3 M
2.4.3.2 BearerTokenExtractor & d9 A& I& ]3 t S' ~2 b
从请求 Header中获取tokenprotected String extractHeaderToken(HttpServletRequest request) {8 m* [5 v7 u1 e$ e1 g
Enumeration headers = request.getHeaders(
5 p9 A% z0 T+ u0 g# x3 W "Authorization");; t; i3 M0 v4 n
! c$ ]) z; i- X% L9 S
String value;4 k. T. K2 t& v% C; Y7 L
do {
. ]6 v7 A7 K+ D+ f O3 L5 A if (!headers.hasMoreElements()) {
2 e" w4 Y9 p5 i/ V8 E" f7 S returnnull # W1 d8 j1 h% m! U* R; o
;
0 {3 d; G [6 @" I: e1 v1 ^ }& S1 V# J# k* [. t* T% B9 P6 G( X
, n- `0 k I: g& f8 m
value = (String)headers.nextElement();
5 L# h% T4 ^5 S9 o } while(!value.toLowerCase().startsWith("Bearer"
6 m! x6 R g/ M) Y) G$ M .toLowerCase()));& l$ u! V; ]. K% D, U4 B( k1 e2 E
% b. \3 Y( d+ p4 V* q$ f! Y String authHeaderValue = value.substring("Bearer".length()).trim();8 W7 X9 z# m; l
request.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_TYPE, , b* R8 X# j8 ]" @0 U, B
value.substring(0, "Bearer".length()).trim());
, X( n0 }3 D* l- S3 s4 h! x int commaIndex = authHeaderValue.indexOf(44);. }9 k: P0 ?- o/ q3 W( r
9 e) G& o$ l8 E
if (commaIndex > 0) {& ]% E2 y. ^' @+ C
authHeaderValue = authHeaderValue.substring(0, commaIndex);8 @8 T$ V; g$ v3 `& ]- A; W
}1 E4 N7 `7 q; e8 s
& a+ e: {4 M; v5 u6 p6 M: s% B
return ; i/ \& c6 ]- \( a' J% ^
authHeaderValue;: G+ m7 V. b3 S- t
}
+ h8 \! l& H$ ]: B, l( Q1 V 2.4.3.3 OAuth2AuthenticationManager资源服务认证token校验实现 程序片段:public Authentication authenticate(Authentication authentication) throws AuthenticationException {6 h: i% V" D1 f+ M8 u5 Z
; N" J) }2 X4 W8 ?( G if (authentication == null) {
% c% s! h) M, R! |. ? thrownew InvalidTokenException("Invalid token (token not found)");
2 Z# e7 \& Y0 [) P5 q( F }
3 t* T9 B$ J3 K$ B! H) z else {
/ c2 p% o$ Q" j String token = (String)authentication.getPrincipal();
! ~ O$ x9 j- f$ K7 B' a //1. 从验证token存储介质获取请求传递的Access Token获取对应的验证信息 / E# L5 P& e6 g+ n4 C6 E
( N8 ~3 @1 ^# E4 X, W: W
OAuth2Authentication auth = this.tokenServices.loadAuthentication(token);. W d! p. |% ]' k
if (auth == null 3 J7 T% L' Z% e+ c/ |9 t
) {7 C2 P% {* l. ]0 r3 G1 D1 Y
thrownew InvalidTokenException("Invalid token: " + token); ~( b/ j/ j- }8 j: f
} else {
# v6 V; G( c( n- r6 a" R //2. 验证token并加载验证信息
& s2 f6 ~# P2 M; w( ] ' s, y8 H4 R- C7 J# s" K
Collection resourceIds = auth.getOAuth2Request().getResourceIds();3 g& o* p# C7 c* b9 N" ~
if (this.resourceId !=
: ?9 A4 y7 z+ ^% p" u/ b' N null && resourceIds != null && !resourceIds.isEmpty() && !resourceIds.contains(this.resourceId)) {
+ F+ C3 \6 h( G8 Z, m
9 K/ H1 o8 a0 P0 T# x thrownew OAuth2AccessDeniedException("Invalid token does not contain resource id (" + this.resourceId +
9 S- M" I8 ?( T/ ^$ Q5 P9 a ")");
3 |' n' e, F0 Q- s# X7 f } else {' o" t# H" c" y c$ }
this.checkClientDetails(auth);4 w7 O8 Z2 z2 L! r
if (authentication.getDetails()
. w7 ^3 E$ b% f$ E X instanceof OAuth2AuthenticationDetails) {
$ K2 V# u8 {) C3 _* C, _' h OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails)authentication.getDetails();
4 @3 v9 y' t0 X' e& [ 1 k$ w9 @! F0 U$ j8 b# F# Q D4 d
if (!details.equals(auth.getDetails())) {- B5 Q; |1 \# M, g% j8 I |
details.setDecodedDetails(auth.getDetails());- c) c; H, n$ y) Q# y
}5 T! |2 V& w2 ~! @+ m& t" x# m6 u8 i
}5 z* e* J' }2 q( V2 N7 B
% y* q; s2 z# t0 E: Y, U/ j
auth.setDetails(authentication.getDetails());
1 j5 a& F9 Y! Q5 T+ }) ] auth.setAuthenticated(
8 b) c% [ u: {# r: l true);( K8 J- z- z+ A( l7 v. ~
return auth;
7 N1 r3 X: J E6 c* F }( D* ]' t Y; D0 S6 Y
}3 o% A9 }7 l! ]! z3 G% M
}4 u. j1 N4 n2 j1 s* x7 i! b
}
$ C) D. N( t& O' @6 ?% y 3、OAuth2 扩展3.1 自定义异常处理3.1.1 自定义授权端点处理异常授权服务器中的错误处理使用标准的Spring MVC功能,即@ExceptionHandler端点本身中的方法。
1 P0 f. S6 H3 B' T2 \0 V1 D9 O 但是其原生的异常信息可能与我们实际使用的异常处理不一致,需要进行转义可以自定义WebResponseExceptionTranslator,向授权端点提供异常处理,这是更改响应异常处理的最佳方法//省略 ; j& Q8 {$ D1 {. I. J8 h) g0 p
@Autowiredprivate WebResponseExceptionTranslator webResponseExceptionTranslator;8 `& u) V! M1 [3 P
+ x2 P7 f; P, E. @
/**8 `" i, z6 H T% h
* 自定义授权服务配置2 p5 C) U6 a) ~# r" m: j R
* 使用密码模式需要配置5 ?! C; P/ g6 h. f9 n9 T/ X
*/ & w3 F3 |! Y7 E1 V; Z- }
@Overridepublic void configure(AuthorizationServerEndpointsConfigurer endpoints) {
S: _! ~0 m+ c0 F endpoints.authenticationManager(authenticationManager)% N; k# n* L9 b: x" B
.userDetailsService(userService)
' h1 [4 \" n9 j% p/ j7 U& |! C; B .exceptionTranslator(webResponseExceptionTranslator);
& g2 I0 k2 Z* ^# T //' H( E/ R1 l" h
9 \/ d M% ]+ V' J
}! B3 [* n# U) n
//省略/**7 o- g$ A G9 B" p3 ^6 s! F. T
* 实现WebResponseExceptionTranslator接口,自定义授权端点异常处理
$ X8 K3 n% ~1 M; Q1 S */@ComponentpublicclassCustomOAuth2WebResponseExceptionTranslator 7 g0 f) @+ A- z! P7 a
implementsWebResponseExceptionTranslator{
/ I. U7 B- Y1 k, c! z+ f. I) b4 B private ThrowableAnalyzer throwableAnalyzer = new DefaultThrowableAnalyzer();
. i' }. y' w* |. i6 l( [1 k
9 i" g/ b O* O
+ H% l9 ^3 ^5 |! ]% M' q0 g( ] @Overridepublic ResponseEntity translate(Exception e) throws Exception {, i/ N; c% c3 [. D8 Y
Throwable[] causeChain = & V, K6 ?4 S2 U4 ?2 V
this.throwableAnalyzer.determineCauseChain(e);
, L7 n7 L! ^; S, { Exception ase = (OAuth2Exception)this.throwableAnalyzer.getFirstThrowableOfType(
1 o1 W/ `/ ~: n3 A OAuth2Exception
P/ S" X9 V: K3 m9 t7 a .class, causeChain);if (ase != null) {
: p5 o A4 W" X+ A3 H returnthis.handleOAuth2Exception((OAuth2Exception)ase);
9 a4 q- c: k, B% q( C }
$ `- j0 p/ x% ^: | ase = (AuthenticationException)
9 \$ u6 ~( L u3 r5 o3 h this.throwableAnalyzer.getFirstThrowableOfType(! y4 L& }, U2 |% V$ g; v
AuthenticationException.class, causeChain);
: B# K& `5 r5 a3 ] if (ase != null) {% e4 q0 g& }. q N! \
returnthis.handleOAuth2Exception(new UnauthorizedException(e.getMessage(), e));" c+ m3 J9 I2 t. z2 Z; q @6 t
}
1 K2 p% s, Z% C- }4 Z) n% g4 Y+ V ase = (AccessDeniedException) ; {: z6 [5 A, o" P; x
this.throwableAnalyzer.getFirstThrowableOfType(
1 b0 ^0 l/ q) e) @6 G AccessDeniedException.class, causeChain); ! I( Y! w+ e' A1 v% J4 g1 {! Y3 r9 o
if (ase instanceof AccessDeniedException) {
9 ~7 I# e+ G1 r9 q returnthis.handleOAuth2Exception(new ForbiddenException(ase.getMessage(), ase));& @7 E( B/ s6 _& h- h, C$ t
}
6 ]( R# Q( J+ H ase = (HttpRequestMethodNotSupportedException) 8 D% ~" ?% h2 |
this.throwableAnalyzer.getFirstThrowableOfType(HttpRequestMethodNotSupportedException.class, causeChain); ! a3 |3 s5 ]3 _# @8 k
if(ase instanceof HttpRequestMethodNotSupportedException){# V7 {- |8 y/ X0 \1 l2 L
returnthis.handleOAuth2Exception(new MethodNotAllowed(ase.getMessage(), ase));
1 t9 u: S: O- T8 r7 b0 ^7 b }/ M2 Y5 \: k/ q
$ }+ I$ w- l- a! T) t
3 ~' ?" Z8 [9 U8 L& ?0 u# a
returnthis.handleOAuth2Exception(new UnsupportedResponseTypeException("服务内部错误", e));
. Z. y5 v9 t: S- L }/ e! H. n5 l7 _$ n# Z
! w# s; }9 l- E( M. M* ^, e
private
- V" K% Q; _7 l5 W" c# ~5 f ResponseEntity handleOAuth2Exception(OAuth2Exception e) throws IOException { H" f1 s) f( m; N5 l: {9 m
int status = e.getHttpErrorCode();
, l- t' V7 n" [$ N9 \ HttpHeaders headers = new HttpHeaders();1 [. p, W+ j( ]' `' z9 `
headers.
, K2 C; [/ L! }0 i) U6 Z set("Cache-Control", "no-store");5 P5 X1 Y, I: u" u2 ?) g% n) v$ x
headers.set("Pragma", "no-cache");) ]! v1 q& X! w+ G6 O) o7 z
if (status == HttpStatus.UNAUTHORIZED.value() || e instanceof InsufficientScopeException) {3 e7 \) ~: c6 u
headers. 6 I. U3 n6 B8 V% g1 ]
set("WWW-Authenticate", String.format("%s %s", "Bearer", e.getSummary()));
8 y/ E! n/ }' H }/ `# {; P# S( r( l4 [7 C* L
CustomOauthException exception = new CustomOauthException(e.getMessage(),e);
) l0 @+ A+ D) o( @7 l ResponseEntity response = new ResponseEntity(exception, headers, HttpStatus.valueOf(status));& N1 ]& I/ f; a; I4 ]5 Z: E
$ R# K, I9 v, u/ J/ Q
return response;
$ q- H+ R5 f4 Q$ o }: S2 `1 I& T) h. E8 J* {
//省略3.1.2 自定义匿名用户访问无权限资源时的异常当访问未纳入Oauth2保护资源或者访问授权端点时客户端验证失败,抛出异常,AuthenticationEntryPoint. Commence(..)就会被调用。
: B" y1 e! T) e: [9 W1 L" [ 这个对应的代码在ExceptionTranslationFilter中,当ExceptionTranslationFilter catch到异常后,就会间接调用AuthenticationEntryPoint。 9 o3 S9 m* ~$ m- t$ N7 b
默认使用LoginUrlAuthenticationEntryPoint处理异常,当抛出依次LoginUrlAuthenticationEntryPoint会将异常呈现给授权服务器默认的Login视图访问未纳入Oauth2资源管理的接口 当访问未纳入Oauth2资源管理的接口时,因为应用接入安全框架,因此依旧会进行权限验证,当用户无权访问时会有ExceptionTranslationFilter 拦截异常并将异常呈现到默认的登录视图提示用户登录: 3 p7 F- ]% e; n+ }2 z/ N% M. _7 R& ]
调用授权端点,客户端校验失败 当调用授权端点(/oauth/token)时,根据前面的源码我们知道在授权认证前,会先通过客户端验证Filter进行客户端验证,当客户端验证失败会抛出异常并由ExceptionTranslationFilter 拦截,将异常呈现给默认的登录视图: ' D3 b+ r5 S1 O7 j- g9 ]
源码分析://顶层授权认证异常处理Point package org.springframework.security.web;7 O* k* p* @- B) Z0 Z9 N
- @7 Y2 ?% `( h6 s7 z
import ...
- b( J, C; t% f- T* `8 v: ?+ g) G* ~8 o4 w# ~% {3 o% G9 w
publicinterfaceAuthenticationEntryPoint
" t0 r) M. X7 G! K0 {4 t# j! b {
+ y" V$ W2 }$ H% v voidcommence(HttpServletRequest var1, HttpServletResponse var2, AuthenticationException var3)throws / H; |2 d7 U: V
IOException, ServletException;/ r; y; h, v( t. u6 k
}
6 T+ f4 a5 G' l+ k' e% F; { 当ExceptionTranslationFilter catch到异常后,就会间接调用AuthenticationEntryPoint。 0 J* h2 T/ ?4 A5 ~
package org.springframework.security.web.access;
' A2 p; |+ [+ H( A8 j; n. b. S: q) E% L! w' s6 |
import ...; `) }- w& h H1 J) B1 d/ x
publicclassExceptionTranslationFilterextends
' e9 r9 d, l! k" l GenericFilterBean{- E4 M5 H" j% o! A
//省略......public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {2 l1 J" z. d, e, X& ]3 Y4 k
HttpServletRequest request = (HttpServletRequest)req;/ @3 j9 J. c$ h# p) z M/ d0 Y$ J( w: Q
HttpServletResponse response = (HttpServletResponse)res;
: h1 `7 S1 m. `$ |* g
% {5 u& u5 E2 t- ?! o- u 5 {# u+ y+ t- u' z1 g, t: ~
try {4 ^0 f% c$ {) O3 u* A
chain.doFilter(request, response);9 _- ^& q+ }5 O# H
this.logger.debug("Chain processed normally");
2 R2 C/ j* A8 F) k# a1 k$ {# K } % O0 ^3 W# W3 ^! V
catch (IOException var9) {
7 Y% q4 O$ h/ G$ h throw var9;* h. o' S- h4 g& u2 l V" x. H
} catch (Exception var10) {
' f; F, i9 `4 R% u Throwable[] causeChain = & M" C# T2 w% M/ x
this.throwableAnalyzer.determineCauseChain(var10);
, d+ @4 _$ ?4 \$ i g) w RuntimeException ase = (AuthenticationException) 1 U' k+ f5 c: B
this.throwableAnalyzer.getFirstThrowableOfType(AuthenticationException.class, causeChain);if (ase ==
. w7 ?' n/ e+ m4 M1 N) \$ z5 ]5 w null) {0 q4 R* X# t1 G/ j
ase = (AccessDeniedException)this.throwableAnalyzer.getFirstThrowableOfType(AccessDeniedException , t+ X/ T* L7 u9 i; e
.class, causeChain);
3 q1 V" H" r8 d6 ? }6 W1 n. d5 e# H9 i# m" @
$ s5 f6 ]! P e2 F. i3 h% n$ S; Q if (ase == null) {! D" w# y- V4 g7 d) m# A( P' n
if (var10 instanceof ServletException) {
, g7 m' X9 F6 A/ V& p
9 O- u) k9 s) A2 c& @. i! f throw (ServletException)var10;
3 j% z5 L7 k4 c4 ~/ B, k$ @5 }/ [: r" C }
" ?! d2 J, w* |6 p8 n) t
5 r L9 R: P! u D3 U/ K3 r if (var10 instanceof RuntimeException) {8 O$ [( Y2 a+ J7 ^: g: e
& C: g# z4 A; r$ \9 f" F+ Z throw (RuntimeException)var10;
$ a$ Q+ P& `3 O* ~ }
% A( W: H; L, K* F% E8 Q i: Z0 n$ P# |
throw new RuntimeException(var10);
) s% ^. L& U0 T/ V) Z6 ] } Z, v- T2 i0 ?
6 g3 y/ R1 ?8 C7 x/ K) I3 v if 9 \% J: q& i6 k/ a8 E$ \
(response.isCommitted()) {' W& l( X b4 }" }
throw new ServletException("Unable to handle the Spring Security Exception because the response is already committed."
; W5 w: o, r" R! [ , var10);8 q4 Y" U1 c5 u. k5 K2 ] _
}
' I, |# p1 k& V) A //异常处理,间接调用AuthenticationEntryPoint.commencethis.handleSpringSecurityException(request, response, chain, (RuntimeException)ase);2 P2 f+ l) T6 u1 Q9 n5 g2 z% Z
}, f9 L, ^/ r: s! k& A1 ]
3 r; g+ \ h% }. C7 l
}
5 ?, K* R8 d- a; v8 |+ x: f9 s& q
1 ]5 V' I- n+ ~5 X0 o/ ~5 q ; u; U: O' o8 [( m9 i
//省略......private void handleSpringSecurityException(HttpServletRequest request, HttpServletResponse response, FilterChain chain, RuntimeException exception) throws IOException, ServletException {
/ {1 P: Z2 i* n5 h1 y" k / x& j* Y1 z5 y; c2 c4 e# W
if (exception instanceof AuthenticationException) {
4 l' a7 ]5 e% {7 O( L" l+ ` this.logger.debug("Authentication exception occurred; redirecting to authentication entry point" ' n2 p) p% y$ z+ f* e1 B5 D) n5 t
, exception);
& H7 [ o4 ~: x5 q% c this.sendStartAuthentication(request, response, chain, (AuthenticationException)exception);0 J6 H+ `) @. }" L/ `
} - n& B8 M( }# h5 T
elseif (exception instanceof AccessDeniedException) {+ F N0 }3 l. e' V0 k' L- R! U
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
/ r# d# P4 k/ b- S
C9 q3 u; `4 y% L+ ` if (!this.authenticationTrustResolver.isAnonymous(authentication) && !this.authenticationTrustResolver.isRememberMe(authentication)) {- S {$ e f' N4 |4 Q5 g
9 n' w0 d& F- B X [ this.logger.debug("Access is denied (user is not anonymous); delegating to AccessDeniedHandler", exception);5 F, W( i& U: W6 n
$ g7 `$ @- J) a5 [ this.accessDeniedHandler.handle(request, response, (AccessDeniedException)exception);
_1 d6 T# u9 S R$ d9 S. n } else {. J. D2 ]( a @% }# Y5 R
4 u5 R! o7 g, c8 X9 a
this.logger.debug("Access is denied (user is " + (this.authenticationTrustResolver.isAnonymous(authentication) ?
8 H8 i0 _( r- k+ g "anonymous" : "not fully authenticated") + "); redirecting to authentication entry point", exception);; V$ g3 _5 |' @& V4 |7 P
7 Q3 b9 h% I5 J7 t5 \- m% r+ q/ J: r this.sendStartAuthentication(request, response, chain, new InsufficientAuthenticationException(this.messages.getMessage( 0 x; y$ t# j6 f3 b
"ExceptionTranslationFilter.insufficientAuthentication", "Full authentication is required to access this resource" 3 w6 q; l! @3 b5 b
)));# x5 [' X) j# y: ^4 [
}
+ _, U( ^7 H/ C3 M/ W }
% d% X, Z& Q' d R) L2 h5 G; e
$ Q2 Q% X8 l# ~3 y }5 O6 C( w, l9 X+ @0 j& n- S, w
2 {3 S0 r3 F( `! a5 }) h; x% C: J
////异常处理,间接调用AuthenticationEntryPoint.commenceprotected void sendStartAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, AuthenticationException reason) throws ServletException, IOException { _4 d' D o2 O! s+ N) V: K4 B! r
SecurityContextHolder.getContext().setAuthentication((Authentication) ( J( t2 y- `# ~9 m% c% E9 E+ X4 G# g
null);( v+ L( Y( v8 }( b
this.requestCache.saveRequest(request, response);
, C. f; Q ^5 j+ p. D4 G1 m this.logger.debug("Calling Authentication entry point." " v' K* A M/ E3 W/ }1 R
);
# a' T0 n; z; @. A1 s+ P5 V$ _ this.authenticationEntryPoint.commence(request, response, reason); f: h9 y9 M$ {8 w
}% x1 g. \1 \( M9 m$ g6 l
8 \/ N0 b" {8 e0 x6 T3 J
//省略......//默认的异常处理,会将异常呈现给默认的Login视图 7 M# Y7 G/ M, |3 P b
package org.springframework.security.web.authentication;
. x1 m, E: C) `; D- Q
+ d! i+ p0 E) s6 w9 c import ...2 z! g& g' {. m- M4 \* F
2 Y. I( M1 s& ]; m, {5 a( ?3 Q1 } publicclassLoginUrlAuthenticationEntryPoint / E ?! T) n. L; b: F$ Y
implementsAuthenticationEntryPoint, InitializingBean {//省略...public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
8 @: [$ C+ x* ?6 E9 p& b String redirectUrl = ; F, d t4 ~/ m
null;' J" e% }7 U4 n- D% l
if (this.useForward) {
8 L% k; ?/ J$ g( j4 C \+ U Q if (this.forceHttps && "http".equals(request.getScheme())) {
_5 m/ K; g/ G; R# i# D0 U" H& f4 I redirectUrl = ; F( [ o7 ^5 E0 D: Y
this.buildHttpsRedirectUrlForRequest(request);# U$ i( i3 k/ m2 G
}& v* j. q y% i$ D) D8 A
* V N/ i4 J$ E. I6 ?$ i
if (redirectUrl == null) {! h8 g' f2 z, b8 T7 Z8 ^
String loginForm = + J1 e6 S. @: G" w/ H6 n$ L8 H9 w
this.determineUrlToUseForThisRequest(request, response, authException);
3 _! [8 q' x( C if (logger.isDebugEnabled()) {- r: Z2 h/ q; K
logger.debug(
9 J E( y! v- l6 t" e1 x "Server side forward to: " + loginForm);
2 b0 E2 y" [) H( f }7 a3 z; N( o+ v: t0 }5 K
8 s/ B( p0 R! W( ~& I/ b) r RequestDispatcher dispatcher = request.getRequestDispatcher(loginForm);
# X% n( K: V3 n c" M' | dispatcher.forward(request, response);
8 H5 e! A& L& `# H' h 0 a* z# v; X% |! i" {# `, `5 R
return;; }7 S. f: @6 r& s) J+ N) ~8 m
}
& C) L9 E, _ P1 r } else {
9 {2 M7 ]. j/ q; i5 s/ f: N redirectUrl = this.buildRedirectUrlToLoginPage(request, response, authException);
. M5 k" @* `: R: e7 P* l1 l! T }
5 @% C. s9 y( Q! a" S3 F, m* Z: z" g- P4 M) R" h: F
! I' P( t3 h1 T' q3 q; p0 E this.redirectStrategy.sendRedirect(request, response, redirectUrl);) h& s% A+ X% \1 _% Z, z. G
}
" t$ B. k/ |9 k `' m, |! n- ]% n* e( k
//省略默认的视图呈现异常肯定不符合我们实际的应用,因此需要对此类异常进行自定义处理。 4 Z' o2 [( `$ b: T1 [/ S+ Q4 Z
package com.easy.mall.exception;
9 s8 R: [. J, i3 J% {. t6 v
0 Y7 {- ~6 _3 i! e a import ...( V5 E- e+ ]+ e& @! Q9 m
6 y; z+ K5 I) E/ k+ ]- K( I @Component@AllArgsConstructorpublicclassCustomAuthExceptionEntryPoint
9 J6 S5 c) ?; S/ o/ k" Z implementsAuthenticationEntryPoint{$ [+ D! r$ L2 Q% k" X6 N. |0 a
O# I- H" M3 U% u( V r @Overridepublicvoidcommence(HttpServletRequest httpServletRequest,5 g# T2 q% V# p' u
HttpServletResponse response, AuthenticationException e) 1 H% q" I, p* Z3 j' Y7 {
throws IOException, ServletException {4 p3 Z$ g. V/ p! R
response.setCharacterEncoding(StandardCharsets.UTF_8.name());+ x9 T5 c$ k. ]
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
4 @* @) g# M9 Q2 S* ^( e CommonResult result = CommonResult.failed();4 c7 z, m1 x0 E( B# e2 D% Z' H
result.setCode(HttpStatus.HTTP_UNAUTHORIZED);
! i3 `# ~6 X r. ^. I
' l& i: F& T# I if (e != null) {! t, `4 E! P2 v2 L
result.setMessage("unauthorized");
; ]) W) j2 E9 ]& w result.setData(e.getMessage());
' ~. o0 [; d5 p& b }/ t" _: W/ T9 `* z
response.setStatus(HttpStatus.HTTP_UNAUTHORIZED);
( ~* n; l' S0 |2 `# Q2 s PrintWriter printWriter = response.getWriter();- C* L) @* G5 s8 G6 s! j& C
printWriter.append(JSONObject.toJSONString(result));
6 W: n( P8 {& r2 e }
5 h1 M8 p$ `) h) k( U# I }
2 W9 M, ~- n; u' k+ E' F+ K7 D7 y' t4 t) M, I3 F
9 G! g+ a. V5 R% M3 Q4 T( ` @Configuration@EnableWebSecuritypublicclassSecurityConfigextendsWebSecurityConfigurerAdapter{. ? e3 g2 x$ v) K/ T# |
1 \' j {# `/ ]4 F$ L2 U% i
@Bean
2 X9 p" e' r( D) U& M+ M. A public PasswordEncoder passwordEncoder(){
4 m7 P2 \& V0 q9 {9 v" K4 k4 m returnnew BCryptPasswordEncoder();( F& l) Q. G8 ?. z
}2 k. I8 Z8 @: M+ P
* r$ Z+ U7 g; ^9 e/ |
@Bean@Override
8 Q' m& G. F) B. X public AuthenticationManager authenticationManagerBean()throws Exception {
1 Z" K# @' e4 W3 A2 R/ n returnsuper.authenticationManagerBean();
1 E8 V- b5 _4 y% h' h% V- f }1 h' [+ @9 Z. G/ K& V7 c5 X+ d! T* @
0 d( w" a) C& \, t
+ d5 M1 X7 K, `; g3 K" ~7 E2 K) g1 g @Overridepublicvoidconfigure(HttpSecurity http)throws Exception {
6 u" d! O; o- B( y6 p; [ http.csrf()
/ F6 G& q, r7 m, f .disable()
9 I: k& _: F( Z! ?! _; D .authorizeRequests()
4 F, e' ~/ I/ a( z7 l .antMatchers(
" B+ i5 [7 P* f9 E! g "/oauth/**", "/login/**", "/logout/**"); f7 w: {/ @. U+ @
.permitAll()' b' g5 Q; z5 [
.anyRequest()
5 P, @- x8 O6 A3 f6 B .authenticated()
3 Q3 x( B. `$ b4 g& N! M4 a5 L .and()1 H7 R4 x" h* W: I, L$ m% h- }
.formLogin()6 W" }, W- O' a: e0 V! ~
.permitAll();* |: q* P& X8 k6 y' b |
3 w( }5 B: ]; v0 [2 K6 ]: p //web 安全控制添加注册自定义的错误处理$ h7 E1 g9 T; q7 a% o Y
http.exceptionHandling().authenticationEntryPoint(new CustomAuthExceptionEntryPoint());1 k$ ~4 y6 J- C
}! ?( G i( \# ]2 p, ?. K3 @
}/ i9 Y- u/ J+ J s* R
$ N8 m, k h) ~* I8 n
自定义异常处理后的效果 
0 ]3 k4 Y4 P F 3.1.3 自定义受OAuth2令牌保护的资源认证失败异常受OAuth2令牌保护的资源无权限访问异常时,异常由原生的Oauth2authenticationentrypoint处理,但是其原生的异常信息可能与我们实际使用的异常处理不一致,需要进行转义。
4 N/ l$ J+ o+ I7 T' e 原生的异常信息响应:{
2 a9 w$ B7 e8 t5 G& Y "error": "invalid_token",2 I* `: Q# X( l, `; f) `
"error_description": "Invalid access token: 1"
. Q7 T- T6 ]3 n5 w& y4 w& Y }" p+ N6 }0 A; V/ E
自定义异常@Configuration # p0 W2 }5 O6 {( w0 H0 u
@EnableResourceServer
* f" w5 {+ ?8 { public class Oauth2SourceConfig extends ResourceServerConfigurerAdapter {
, K$ X# _2 l% {" R [7 w( i/ x! t( X- M+ E
@Override ( ?. L' x: t5 x0 T2 ~
$ e( t1 l6 f2 Q1 V% j2 y
public void configure(HttpSecurity http) throws Exception {
% n+ s8 Q6 h5 ` http.authorizeRequests()
5 h7 I0 U+ K' x7 J+ ^; L .anyRequest
$ s& l/ r/ b5 r ()0 i, B3 A, _& L4 G" m2 i
.authenticated()
. V* z( V6 {3 M3 J; v$ T) Y' g# G9 j .and()
* H% S5 _4 W+ g# D9 r3 ?+ } .requestMatchers()% z/ u9 u2 @, m
.antMatchers("/user/**" / h& U' a) A+ }' c
);//配置需要保护的资源路径$ W) }( o9 z, U3 {- n
}
4 K7 o! d' V1 R& E8 I7 R8 ?3 ~* E
: D- ?# b$ g" x$ f @Overridepublicvoidconfigure(ResourceServerSecurityConfigurer resources) throws * T- K5 N- [; e& h; F+ N4 T" T0 f6 q
Exception {
, g: `- f8 F% n) T$ X5 T resources.authenticationEntryPoint(new CustomAuthExceptionEntryPoint());//自定义受令牌保护资源服务异常处理 ; i u9 A$ W4 X, |/ {1 S/ x
' S; I+ ]+ I" J# o9 `' V
}
& `! `: r7 T& ^, T8 v+ c/ ` }8 a$ }) _3 i; @' f7 K" Z# c
自定义异常处理效果 {* k- m0 n2 S' x, Z, A
"code": 401,( U. Y6 \/ U. }
"data": "Invalid access token: 1",
8 W1 c8 m* I8 I' e "message": "unauthorized" ( E; _' L+ B$ w% c
& p- r6 A6 x8 C
}; D8 v1 Y/ `& s, K
3.1.4 自定义受OAuth2令牌保护的资源无权限访问异常//待定3.1.5 Security自定义异常分析总结根据上述一系列源码分析,我们知道Security是通过一系列Filter过滤链实现授权认证,不同情况和场景其过滤链不一样,因此当出现异常也通常由不同的异常处理器进行处理,因此需要针对不同情况进行自定义处理。
5 y3 z* S. _) j+ Q! ? 附录构造Basic Auth认证头/**# j5 `* m0 z. j, Q8 l9 {; L2 T7 y" M
* 构造Basic Auth认证头信息
1 m8 Y/ L3 P& Q1 b7 j9 q" E *
+ q3 u1 R6 V( A4 |4 f+ d3 ~ * @return! S) e" q9 d8 e
*/privateString getHeader() {) I- j% H. o4 L. t9 T& q
String
, L4 e l6 b2 T3 F9 W auth = APP_KEY + ":" + SECRET_KEY;3 a" [# Q! j' o# W: \
byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName( ! l5 C% {* g7 E& l# _. d
"US-ASCII")));
2 {. x/ ^/ x" k' C5 ] String authHeader = "Basic " + newString(encodedAuth);8 j- B. F: z& t/ V
return authHeader;
! y5 J. r8 S( M( B }
/ t3 q) d J a
j3 b4 e% }0 X( O" | E0 ~- s/ D
1 b9 T& |4 \2 [2 y# E8 N! I
4 V7 I- P1 z, ^+ d
: H- v1 p9 ]! W |