找回密码
 加入怎通
查看: 242|回复: 0

SpringSecurity(二)OAuth2认证详解(oauth2.0 spring security)

[复制链接]
我来看看 发表于 2023-03-06 17:34:41 | 显示全部楼层 |阅读模式
! ^) E6 V: f) I) m4 t! U2 q

1、OAuth2.0 简介OAuth 2.0是用于授权的行业标准协议OAuth 2.0为简化客户端开发提供了特定的授权流,包括Web应用、桌面应用、移动端应用等1.1 OAuth2.0 相关名词解释Resource owner(资源拥有者):拥有该资源的最终用户,他有访问资源的账号密码;

3 F! L4 r4 Z" F T

Resource server(资源服务器):拥有受保护资源的服务器,如果请求包含正确的访问令牌,可以访问资源;Client(客户端):访问资源的客户端,会使用访问令牌去获取资源服务器的资源,可以是浏览器、移动设备或者服务器;

+ J& n6 J b4 J( r. u

Authorization server(认证服务器):用于认证用户的服务器,如果客户端认证通过,发放访问资源服务器的令牌1.2 四种授权模式Authorization Code(授权码模式):正宗的OAuth2的授权模式,客户端先将用户导向认证服务器,登录后获取授权码,然后进行授权,最后根据授权码获取访问令牌;。

" n5 \# m7 n8 J% y' E+ P$ f% \8 |

Implicit(简化模式):和授权码模式相比,取消了获取授权码的过程,直接获取访问令牌;Resource Owner Password Credentials(密码模式):客户端直接向用户获取用户名和密码,之后向认证服务器获取访问令牌;

7 z& c3 ^# g2 g

Client Credentials(客户端模式):客户端直接通过客户端认证(比如client_id和client_secret)从认证服务器获取访问令牌1.3 、OAuth2框架Spring Security提供了OAuth 2.0 完整支持,主要包括:。

; w- f& [, A$ C; \8 o

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的客户端支持;

- R: W1 E9 F1 M o0 u& O

OAuth 2.0 JOSE - spring-security-oauth2-jose.jar:包含Spring Security对JOSE(Javascript对象签名和加密)框架的支持框架旨在提供安全地传输双方之间的权利要求的方法。

; m8 e* S) F( a) |

它由一系列规范构建: JSON Web令牌(JWT) JSON Web签名(JWS) JSON Web加密(JWE) JSON Web密钥(JWK)要使用OAuth2,需要引入spring-security-oauth2模块,通过之前源码分析,Spring 通过OAuth2ImportSelector类对Oauth2.0进行支持,当引入oauth2模块,Spring会自动启用 OAuth2 客户端配置 OAuth2ClientConfiguration。

: \9 L3 e p, L- I. I

1.4 OAuth 2.0客户端提供功能OAuth 2.0客户端功能为OAuth 2.0授权框架中定义的客户端角色提供支持 可以使用以下主要功能:授权代码授予客户凭证授权Servlet环境的WebClient扩展(用于发出受保护的资源请求)。

3 | C7 f# @0 |

HttpSecurity.oauth2Client()提供了许多用于自定义OAuth 2.0 Client的配置选项@EnableWebSecurity 6 u) e" u& N$ A! v& C0 e9 ~7 M. K5 g public class OAuth2ClientSecurityConfig extends WebSecurityConfigurerAdapter {% [) G. f. p4 e1 E$ M' Z9 K8 o% v 4 N* B4 v4 L3 `; A9 q( D' k5 ^

+ F9 d/ \0 s* D

@Override 5 V+ v. U; S) y9 N protected void configure(HttpSecurity http) throws Exception { 3 L5 Y, }1 m' q K0 _9 z9 ~ http.oauth2Client

$ e( `; t$ D9 ~( e5 O/ S) O

(), h+ o' ], V7 j$ S4 ]' K6 ^9 ?8 C .clientRegistrationRepository(this.clientRegistrationRepository()) / I% q& ]' R0 s0 }% W .authorizedClientRepository

6 p4 [$ D# N! ^3 }2 i) @ Z

(this.authorizedClientRepository())( w' j3 L9 f; p, J .authorizedClientService(this.authorizedClientService

/ u5 s4 W3 ]6 X% ?* O

()). Q& U$ D# r( \6 i .authorizationCodeGrant()9 j) k6 k# u D" F5 g .authorizationRequestRepository(this.authorizationRequestRepository

|# Z4 b. D# m7 g1 ^

()) 2 o( l' p- F; _( G, i .authorizationRequestResolver(this.authorizationRequestResolver())# `6 u7 q' U0 E0 c# m .accessTokenResponseClient

" N! V8 j$ v- N: m# k `

(this.accessTokenResponseClient()); ( L" n) K3 ?; i* I p4 J. I } # y8 }" P& ~; _* f% Y/ D1 Y }, A! N7 p- d, g" ]7 d2 y 2、OAuth 2.0 认证服务Spring Security OAuth2 实现了OAuth 2.0授权服务,简化了程序员对OAuth 2.0的实现,仅需要简单配置OAuth 2.0认证参数即可快速实现认证授权功能。

0 q0 d% Q$ V* ?- c m4 s

2.1 Spring Security OAuth2 提供的程序实现Spring Security OAuth2 中的提供者角色实际上是在授权服务和资源服务之间分配的,使用Spring Security OAuth2,您可以选择将它们拆分到两个应用程序中,并具有多个共享的资源服务授权服务。

) q5 k. V5 @+ y" b! e! d

2.1.1 授权服务对令牌的请求由Spring MVC控制器端点处理,对受保护资源的访问由标准Spring Security请求过滤器处理为了实现OAuth 2.0授权服务器,Spring Security过滤器链中需要以下端点:。

3 v4 r) B9 H6 j5 F- F' T

AuthorizationEndpoint用于服务于授权请求预设网址:/oauth/authorizeTokenEndpoint用于服务访问令牌的请求预设网址:/oauth/token2.1.2 资源服务。

5 b2 S4 E( c, C% y+ }% ^, ~! k" }

要实现OAuth 2.0资源服务器,需要以下过滤器:将OAuth2AuthenticationProcessingFilter用于加载的身份验证给定令牌的认证访问请求2.2 集成 OAuth 2.0 认证授权及资源管理。

% j- k {3 ]# X6 a* @4 G2 e/ M' b

2.2.1 项目准备引入依赖org.springframework.bootspring-boot-starter-web

" Y! w; t! G& q' W' N

org.springframework.boot

% C( M% C: @& ]/ I% e7 ` v

spring-boot-starter-securityorg.springframework.cloud

2 t w; O1 y6 i3 f

spring-cloud-starter-oauth22.2.1 配置授权服务在配置授权服务器时,必须考虑客户端用于从最终用户获取访问令牌的授予类型(例如,授权代码,用户凭据,刷新令牌)。

. S! t& K+ b: f1 @0 e, O( z

服务器的配置用于提供客户端详细信息服务和令牌服务的实现,并全局启用或禁用该机制的某些方面但是请注意,可以为每个客户端专门配置权限,使其能够使用某些授权机制和访问授权也就是说,仅因为您的提供程序配置为支持“客户端凭据”授予类型,并不意味着授权特定的客户端使用该授予类型。

! I7 O( t9 Q8 m5 N0 N! V$ O

使用@EnableAuthorizationServer注解开启Oauth2认证@EnableAuthorizationServer批注用于配置OAuth 2.0授权服务器机制以及任何@Beans实现的机制。

/ @+ i( ?- X# g+ L! c* E2 r$ U

AuthorizationServerConfigurer(有一个便捷的适配器实现,其中包含空方法)以下功能委托给由Spring创建并传递到的单独的配置器AuthorizationServerConfigurer:。

4 l" E g' }; x% N

ClientDetailsServiceConfigurer:定义客户端详细信息服务的配置程序可以初始化客户详细信息,或者您可以仅引用现有商店AuthorizationServerSecurityConfigurer:定义令牌端点上的安全约束。

' l' j2 @" q$ @

AuthorizationServerEndpointsConfigurer:定义授权和令牌端点以及令牌服务提供者配置的一个重要方面是将授权代码提供给OAuth客户端的方式(在授权代码授予中)OAuth客户端通过将最终用户定向到授权页面来获得授权码,用户可以在该页面上输入她的凭据,从而导致从提供者授权服务器重定向回带有授权码的OAuth客户端。

$ D' ]/ d e8 h( I

源码清单:@Configuration@EnableAuthorizationServer! e B3 H% Y+ x4 B5 p* }- K public class Oauth2ServerConfig extends AuthorizationServerConfigurerAdapter {/ C7 m$ L; O+ r2 R # @% U7 p, Q ~

6 o' e6 o5 F' P/ X+ U: y

@Autowired 8 `! V7 h$ ^2 C+ G private PasswordEncoder passwordEncoder; ; Q3 u# R, ]" z& `4 X/ X5 c9 ]' H* L# X* M2 } @Autowired& Z% h; G4 ~4 H$ X; Y private AuthenticationManager authenticationManager; . y8 s7 I* R: Z; F+ A( |( Q9 @9 n9 l X# S0 @1 \

# c% R8 N2 T* m; m

@Autowired 3 W) A; Y/ K6 E) H+ X( b7 A private UserService userService; ( q4 ?$ n u0 \ ?% T* n+ m - n! J$ x; o1 ^ /** ( x8 N& w3 Y: @ H O* J: T * 自定义授权服务配置 7 ]0 ?. E8 p' x * 使用密码模式需要配置 9 @! I {. l; j9 c */@Override L) _& w# f9 | public void configure(AuthorizationServerEndpointsConfigurer endpoints) { , D, N1 m, ~9 w0 N

) {$ j2 X) C! L% R. j) [

endpoints.authenticationManager(authenticationManager)) R9 H, z- ~ y8 | .userDetailsService(userService);& c* R( B/ ` L1 k, ~0 S! q/ d }; D9 A& g* r1 U1 f s0 w! c 2 H$ B* X( {+ p) i. b- S

0 ?0 E; u9 s1 M+ p5 `

/** 1 k* u# B1 ]/ x. U8 p5 @7 \ * 配置认证客户端 + ^" {- `1 d- }4 L: _, i * @param clients' H; B1 k! k7 m8 t7 I+ a * @throws Exception- u9 P ?% @- z- B/ T */) B) {. q2 Z0 L2 E/ d @Overridepublicvoidconfigure(ClientDetailsServiceConfigurer clients)

8 { v5 }- T, Q) z4 r1 d7 w d8 ^

throwsException {% _( y) r, k& {! ] //自定义客户端配置+ r4 s5 j* E/ t, n& _3 q7 p/ Y8 Z" f }3 ~# R; d) b% L3 n% T9 v 1 y. P) u) c! h /** $ `2 C9 F( N. i7 `6 N; f * 自定义授权令牌端点的安全约束* C: a0 H5 \) ] * @param security+ T# Z% {" h1 Z0 Y * @throws Exception ! h( _2 z7 ~5 Z, [0 m* k2 H' C */

% x" E+ x D: V- G) b, I/ S

@Override $ P0 s" e( C6 n. o% C public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {) [! w7 O: ?+ G/ w3 G

' d+ S% \) \8 d

//自定义安全约束//....3 G% ?) f# I' `- P/ F$ j6 k/ {# k } # f( E7 u) O& C/ w/ F% e9 C' u }$ Y: |' ?3 Q$ q, F- _ 2.2.1.1 授权服务配置AuthorizationServerEndpointsConfigurer 定义授权和令牌端点以及令牌服务endpoints.tokenStore

; K9 g/ v& [6 J3 z

(tokenStore)//自定义令牌存储策略//默认除密码模式外,所有授权模式均支持,密码模式需要显示注入authenticationManager开启.authenticationManager(authenticationManager) ( n; \9 I% W7 J1 a9 \+ L/ v

3 n- ?" }, [$ T* x4 Q

.userDetailsService(userDetailServiceImpl)//自定义用户密码加载服务.tokenGranter(tokenGranter)//定义控制授权.exceptionTranslator

7 @' t6 F7 I% Z. ^

(webResponseExceptionTranslator);//自定义异常解析2.2.1.2 客户端加载策略配置将ClientDetailsServiceConfigurer(从您的回调AuthorizationServerConfigurer)可以用来定义一个内存中或JDBC实现客户的细节服务。

& D @8 a. Y" ?0 \7 ?

客户的重要属性是:clientId:(必填)客户端IDsecret:(对于受信任的客户端是必需的)客户端密钥(如果有)scope:客户端的范围受到限制如果范围未定义或为空(默认值),则客户端不受范围的限制。

; z2 T- s0 A4 z, W& h% l5 |

authorizedGrantTypes:授权客户使用的授权类型默认值为空authorities:授予客户端的权限(常规的Spring Security权限)可以通过直接访问底层存储(例如的情况下为数据库表JdbcClientDetailsService)或通过ClientDetailsManager接口(这两种实现都ClientDetailsService可以实现)来更新正在运行的应用程序中的客户端详细信息。

* u9 Q# K; k0 P4 C

内存加载客户端配置,直接通过ClientDetailsServiceConfigurer添加客户端配置@Override " ]% c# E' O( P0 i& j2 f public void configure(ClientDetailsServiceConfigurer clients) throws Exception { 8 p% N% n' I3 A

7 b! z( ]' r' c4 ?/ m

clients.inMemory() ; X& v% u3 N5 \7 x% r .withClient("admin")//配置client_id.secret(passwordEncoder.encode("admin123456"

4 w1 m8 ~( z! q8 X) t& z' T) k1 b

))//配置client_secret.accessTokenValiditySeconds(3600)//配置访问token的有效期.refreshTokenValiditySeconds(864000

: c1 f$ `; C9 s

)//配置刷新token的有效期.redirectUris("http://www.baidu.com")//配置redirect_uri,用于授权成功后跳转.scopes("all")//配置申请的权限范围

( B0 [8 {8 x/ K, e; g, R

.authorizedGrantTypes("authorization_code","password","client_credentials","refresh_token");//配置grant_type,表示授权类型

! u5 X# r/ C! \6 b4 Q- `- ~. L, D4 F

( c# n$ Y0 o9 G8 l4 r! S$ F }8 s- L! `9 Q0 D! O" z5 C 自定义ClientDetailsService,redis+jdbc方式加载客户端缓存@Overridepublicvoidconfigure(ClientDetailsServiceConfigurer clients)

% `; g0 P; j8 T. a3 w

throws Exception { 5 G5 z' @" H* v! _ clients.withClientDetails(redisClientDetailsService); 8 h% [& `9 ~3 E5 U- G9 G redisClientDetailsService.loadAllClientToCache();

! D |$ w2 h# e: z4 P

// 2 C! b" ?8 k8 v } 9 E" _$ V8 [ m . ?% ^& J0 I4 k2 K @ServicepublicclassRedisClientDetailsServiceextendsJdbcClientDetailsService{$ ~2 ~ l. z% J7 _ //继承JdbcClientDetailsService,扩展redis缓存加载客户端,优先从缓存获取客户端配置,缓存没有再从数据库加载

7 B, F: W1 G( h1 O

2.2.1.3 令牌管理策略AuthorizationServerTokenServices定义了管理OAuth 2.0令牌所需的操作在开发过程需要注意:创建访问令牌后,必须存储身份验证,以便接受访问令牌的资源以后可以引用它。

% J( @- z' j: [! @6 c7 X! G! Q

访问令牌用于加载用于授权其创建的身份验证在创建AuthorizationServerTokenServices实现时,您可能需要考虑使用DefaultTokenServices,可以使用插入许多策略来更改访问令牌的格式和存储。

W( r9 P; Z* m& Y

默认情况下,它会通过随机值创建令牌,并处理所有其他事务(除了将令牌委派给的令牌的持久性)TokenStore默认存储是内存中的实现InMemoryTokenStore对于单个服务器,默认设置非常合适(例如,低流量,并且在发生故障的情况下不与备份服务器进行热交换)。

! Q. o$ Q. Q; @

大多数项目都可以从此处开始,并且可以在开发模式下以这种方式运行,以轻松启动没有依赖性的服务器JdbcTokenStore是JDBC版本的同样的事情,它存储在关系数据库中令牌数据如果可以在服务器之间共享数据库,请使用JDBC版本;如果只有一个,则可以扩展同一服务器的实例;如果有多个组件,则可以使用Authorization and Resources Server。

8 `# Q% f* p; U3 t

要使用,JdbcTokenStore您需要在类路径上使用“ spring-jdbc”存储的JSON Web令牌(JWT) 版本将有关授权的所有数据编码到令牌本身中(因此根本没有后端存储,这是一个很大的优势)。

2 p! Q5 T( q$ M9 \% } z- ?

一个缺点是您不能轻易地撤销访问令牌,因此通常授予它们的期限很短,并且撤销是在刷新令牌处进行的另一个缺点是,如果您在令牌中存储了大量用户凭证信息,则令牌会变得很大JwtTokenStore是不是一个真正的“存储”在这个意义上,它不坚持任何数据,但它起着翻译令牌值和认证信息相同的角色DefaultTokenServices。

" T: F; {1 F) V7 I

2.2.1.4 自定义定义UserService实现UserDetailsService@ComponentpublicclassUserServiceimplementsUserDetailsService

8 B# g0 }: ~2 I/ y9 y' L7 H

{ + Z* C- s& u+ d6 j # R" G6 o+ X0 ]* @0 L4 Q3 j @Autowiredprivate QtAdminService qtAdminService; & o9 y9 A8 A6 }, U& H; ^5 ^" F' z, Q: T; M; P$ U ) ^8 X, l6 D; Z+ B. g6 C. a/ ?/ Z' [ @Overridepublic UserDetails loadUserByUsername

( D- l& Z, B5 u# f% ]! u

(String username)throws UsernameNotFoundException {9 O' f) g1 v4 E" X String clientId = "admin";* Y) q- _5 Y& ?* |) i UserDto userDto = qtAdminService.loadUserByUsername(username); 1 r0 N0 @6 y/ _

" K( H; k. r& E$ P+ }9 I

if (userDto == null) { 5 ]0 u2 }( v/ K& Y5 u( }, v thrownew UsernameNotFoundException(MessageConstant.USERNAME_PASSWORD_ERROR); # n* |8 _" L7 D7 n: K } . j0 h& z2 ~( p* `+ ]9 S4 H" w userDto.setClientId(clientId); / c5 V1 O1 h D1 v* w SecurityUser securityUser =

6 H6 z/ t# D2 n& t8 L$ t

new SecurityUser(userDto); ( W1 Z( E, m1 Y2 |, f" J$ B if (!securityUser.isEnabled()) {! G! N# \" r5 `7 | thrownew DisabledException(MessageConstant.ACCOUNT_DISABLED); ! ^! L/ j3 e: E8 ~5 r }

+ p1 m* @8 c; D4 R

elseif (!securityUser.isAccountNonLocked()) {% \/ N& w: L' i- W0 M7 w- H thrownew LockedException(MessageConstant.ACCOUNT_LOCKED);) g8 C% ]" B, h9 r8 x }

" W6 s$ T2 R) W- M! Y

elseif (!securityUser.isAccountNonExpired()) { + g; G; h0 v5 t! `2 s0 a thrownew AccountExpiredException(MessageConstant.ACCOUNT_EXPIRED); / g; h, A- M# K7 e! j+ [; g5 l4 k }

1 W! R6 v% z* w8 h6 A9 K+ b+ E

elseif (!securityUser.isCredentialsNonExpired()) { 6 y, D# _( U, W thrownew CredentialsExpiredException(MessageConstant.CREDENTIALS_EXPIRED); * ~& h, \8 e& o3 A } ( O) y+ D2 h! I; g7 b+ I7 R2 g

/ \2 R7 o9 ]" X' D4 @) d1 l

return securityUser; 9 R% |7 z* F+ \) T, K }+ P1 d$ A/ r; |3 [ }/ w" }: J/ }8 b6 b 2.2.1.5 定义令牌端点上的安全约束在对请求授权的端点进行访问之前需要对授权信息中传递的客户端信息进行认证,客户端认证通过后才会访问授权端点根据授权参数传递方式不同,对客户端进行认证的Filter也可能不一样:。

% p% u) Z4 A7 {7 ]; F8 I# h3 U' X

请求/oauth/token的,如果配置支持allowFormAuthenticationForClients的,且url中有client_id和client_secret的会走ClientCredentialsTokenEndpointFilter

7 O$ K* [6 J, N) r0 Z- |. g4 P

请求/oauth/token的,如果没有支持allowFormAuthenticationForClients或者有支持但是url中没有client_id和client_secret的,走BasicAuthenticationFilter认证

4 c0 X" m* O5 g9 \+ M5 X2 }& `

可以AuthorizationServerSecurityConfigurer添加客户端信息验证策略@Overridepublic void configure(AuthorizationServerSecurityConfigurer security) throws Exception {& Q7 |! e0 k9 b: `0 T) V security.tokenKeyAccess(

# ^5 U! P4 R7 y; |5 w

"permitAll()")/ S: L6 r! J0 |/ s+ @. o .checkTokenAccess("isAuthenticated()") , n7 c. D- K0 }4 _# G W .addTokenEndpointAuthenticationFilter(customBasicAuthenticationFilter);

5 K+ X( _- i5 _( P' A9 Q

//添加自定义客户端验证策略 ' s' f. Z, o8 M. [ }6 W8 s6 m$ f; x# b& C : A0 j4 N+ _4 `3 D. r //客户端验证策略控制public void configure(HttpSecurity http) throws Exception {0 j: G, e- q/ a) Z this

' ]' w) P- U" S* ?- [

.frameworkEndpointHandlerMapping();2 z- h: J, l# e if (this.allowFormAuthenticationForClients) {8 |5 B0 j% O( o4 U/ z4 q this.clientCredentialsTokenEndpointFilter(http);7 E7 n/ t1 V. \, u0 b" u# A3 S; V# k } ' y- a2 ]% B4 D' u/ G* J! M: E X3 ] Iterator var2 =

; R/ F+ S( B* j

this.tokenEndpointAuthenticationFilters.iterator();1 w9 p7 C+ a9 o & P- I' s8 q; b/ X$ D while(var2.hasNext()) {5 `- g$ {2 ^1 P7 s6 Q0 R6 u6 O Filter filter = (Filter)var2.next(); - C, b, r+ W3 C. Q+ Y) X6 O http.addFilterBefore(filter, BasicAuthenticationFilter

' P7 y# l- Q* |6 _ p0 U$ K( W

.class);( G9 a/ Q) x C" Z: K } - w+ p: K9 Y B7 ^& M" E, J* I6 H' _- h0 B5 H5 u* _- ] http.exceptionHandling().accessDeniedHandler(this.accessDeniedHandler);/ O; U+ g7 ?+ f5 {% u% W$ e }% h8 H0 z5 Y, v. s $ A$ r" U& x; T* h1 @ private

+ o! S! _" l8 Y( y* @

ClientCredentialsTokenEndpointFilter clientCredentialsTokenEndpointFilter(HttpSecurity http) { # D1 J. X, }2 J( v0 V0 y% N ClientCredentialsTokenEndpointFilter clientCredentialsTokenEndpointFilter = new ClientCredentialsTokenEndpointFilter(

1 V6 u9 ?: r/ A2 h3 J9 E) I; F: n

this.frameworkEndpointHandlerMapping().getServletPath("/oauth/token")); ! D4 |5 Q a9 u clientCredentialsTokenEndpointFilter.setAuthenticationManager((AuthenticationManager)http.getSharedObject(AuthenticationManager

: y0 ^8 {: x- f

.class));: ~0 H! b7 ^( { g& g8 R OAuth2AuthenticationEntryPoint authenticationEntryPoint = new OAuth2AuthenticationEntryPoint();( r) P7 w! i. U7 c9 o9 | authenticationEntryPoint.setTypeName(

$ l" L# T4 H. p% C5 l+ J

"Form");5 j9 P, l( T. A) s8 n& f authenticationEntryPoint.setRealmName(this.realm);9 i1 S+ E. Z6 I3 t clientCredentialsTokenEndpointFilter.setAuthenticationEntryPoint(authenticationEntryPoint); 1 X% ~- ?; b; E9 J clientCredentialsTokenEndpointFilter = (ClientCredentialsTokenEndpointFilter)

4 T9 Q9 ^& j7 @

this.postProcess(clientCredentialsTokenEndpointFilter); 2 m6 e7 T' E3 K, F; B* Z http.addFilterBefore(clientCredentialsTokenEndpointFilter, BasicAuthenticationFilter

& @, l1 G& I9 U1 b% x1 k B' g

.class);return clientCredentialsTokenEndpointFilter;; ?/ z: N; M9 _& b2 u& { } j4 J3 @& G" g7 H* G+ B! ]6 p1 q2 J- K- G8 _& a8 P private ClientDetailsService clientDetailsService() {; K- d# n5 X4 E- V6 Q

! t! k# Y: @# V. n; F; j

return (ClientDetailsService)((HttpSecurity)this.getBuilder()).getSharedObject(ClientDetailsService.class

: Y& o( Z+ K/ b

);$ _6 [4 n. B) O } 5 W7 Q/ r0 C2 i6 K2 s/ I9 X7 v' S: N, l C7 @( }+ {( | private FrameworkEndpointHandlerMapping frameworkEndpointHandlerMapping() { 1 E4 S2 ~6 A; k2 \- n% H return (FrameworkEndpointHandlerMapping)((HttpSecurity)

2 Y6 z% {* `, F% _( h( d. x

this.getBuilder()).getSharedObject(FrameworkEndpointHandlerMapping.class); s$ b* ^; B1 S: J5 B+ v% } } ( r+ Y( j( C, Z5 a ]' E: l! O. J public void addTokenEndpointAuthenticationFilter(Filter filter) { * X8 f, t- i+ d0 F) F7 B

- {3 q2 S8 y2 ?! K+ T3 y4 y

this.tokenEndpointAuthenticationFilters.add(filter);6 w, b+ W. F( C1 B0 z! k }2 O% M2 u; \( L# X* y5 i 2.2.2 添加SpringSecurity配置允许认证相关路径的访问及表单登录@Configuration

l. g& x: r. s" _6 ]

@EnableWebSecurity4 g j2 v- y8 ]+ x1 [5 _/ N: j public class SecurityConfig extends WebSecurityConfigurerAdapter { & c1 ?- R- z2 A% d1 F' ~: R9 k/ N) l! P* P% J4 K4 K+ Z) N @Bean% y Y+ Q" K! N5 d6 p% ]5 S! w, K public PasswordEncoder passwordEncoder() { ' h1 C2 Q" g* v

) U7 A |, r* z2 t5 R; u8 o+ m) ~$ }

returnnewBCryptPasswordEncoder();( u2 B8 ?& r4 o1 O7 J$ S } 5 i) S6 d! z! Q/ _2 A/ J( K- Q( F1 _4 J- d8 v7 ]1 P# N @Bean# o d' k8 P! y; z/ d' m @OverridepublicAuthenticationManagerauthenticationManagerBean

7 l0 b5 F& ^9 C6 v! R) F; ^

() throwsException {, S& D/ Y. \6 n: w7 M( B* l | returnsuper.authenticationManagerBean();5 J. p7 c' \, N5 E8 { } ! @5 N! f- [0 e. `9 k - \0 L5 P8 u. F' s5 w) m @Overridepublicvoidconfigure

, @8 A8 T$ d" n) s

(HttpSecurity http) throwsException { 7 A5 ]) q1 b: B% k7 P% l8 g http.csrf() 9 f9 @' n' S( k+ y .disable(), e6 q/ A4 S2 X5 }: y3 C/ ^ L. i .authorizeRequests() @0 P4 t: ?) l; b

6 p; H: ?2 m* f7 |9 r# b

.antMatchers("/oauth/**", "/login/**", "/logout/**") 3 n/ p* v( Q, d- | .permitAll() 1 |% s' R6 f: g .anyRequest() , U( Z- o* _+ U n. l7 z% _

$ c4 r3 ?* g4 Z7 K6 s; z

.authenticated(). d! O: ^. y9 E! p3 g .and() " |2 a5 F, t; u3 H; A1 [ .formLogin(); A8 p$ C2 o5 F( d5 M( y .permitAll(); 3 o4 d4 N4 ~' G6 e7 N( `0 l }' |* q# _" G3 o4 ` }4 [* _/ N6 ~: l, Z! I$ p L 2.2.3 Oauth2 验证启动应用,进行Oauth2 认证服务进行验证

& f& Q" {9 {3 P" f

Oauth2 密码模式验证使用密码请求该地址获取访问令牌:http://localhost:10001/oauth/token使用Basic认证通过client_id和client_secret构造一个Authorization头信息;

3 |8 J0 q9 n% E" @

在body中添加以下参数信息,通过POST请求获取访问令牌; { % z2 t: y7 e8 t0 x3 w "access_token": "a690d4e6-185f-4d1d-bc62-0067bd8b6ec9", + t ~ F) i) x "token_type"

: u! G% s$ N0 {2 v$ V ?) e

: "bearer",) u5 G/ {* O( |- W' ^0 l+ x$ m "refresh_token": "55a04005-e2d9-44df-99df-01b57429d424", 6 P/ w) g( T+ W0 Q/ H3 C) p "expires_in": 3599,6 h. _$ b2 c5 ?9 |4 l! N1 Q; {

, t4 r4 M: q! T; W

"scope": "all"/ [5 }2 a4 e: j! B5 ?6 D } + N. `) F1 j) G/ C% l 2.3、Spring Security oauth2 授权认证核心源码分析OAuth2 授权认证大致可以分为两步:客户端认证Filter拦截/oauth/token请求,对授权参数传递的client_id和client_secret进行认证,认证通过继续访问/oauth/token端点;

`. s6 N8 c6 B4 g

/oauth/token端点进行授权认证。2.3.1 /oauth/token 认证核心处理流程图

7 R6 K( V/ u$ A+ A# z4 A

2.3.2 TokenEndpoint(/oauth/token) 认证源码分析@RequestMapping(0 k3 l& E2 F2 u4 G value = {"/oauth/token"},4 p6 W9 Q$ R& M" B: F method = {RequestMethod.POST} * t3 C% @7 Y6 X2 ~0 N( t$ ?2 F: X )

" ~, z% ?% K! z1 v* b

public ResponseEntity postAccessToken(Principal principal, @RequestParam Map parameters) throws HttpRequestMethodNotSupportedException { % l. {$ w5 I7 e( E

3 S7 J9 a& C( h% G) ]3 j

if (!(principal instanceof Authentication)) {) V- o% Q Y: [7 K throw new InsufficientAuthenticationException("There is no client authentication. Try adding an appropriate authentication filter."

/ @: m5 J; _* Q4 V1 n' ]3 R

); 8 d( c: u5 o, f3 n6 w a& S } else {. X. T- {) ?. s4 K //1. 获取clientId& \) [6 S( h$ ]7 q9 J# D- ] String clientId = this.getClientId(principal);6 F. l4 _/ F2 } {5 t; Y0 @* W //2. 根据客户端id加载客户端信息

/ N8 j0 n7 \7 W& M

1 t! z- }1 o5 ^3 \7 @7 A# ?3 T ClientDetails authenticatedClient = this.getClientDetailsService().loadClientByClientId(clientId); 5 N8 P0 f* u* n- Y C$ T$ \

+ r3 `8 z5 O6 [0 I! A# Q

//3. 根据客户端信息和请求参数组装TokenRequest 5 _" S) T7 [3 c TokenRequest tokenRequest = this.getOAuth2RequestFactory().createTokenRequest(parameters, authenticatedClient); - L. T( r* v1 l

8 v2 b" A( V8 S2 c4 ~

//4. 有没有传clientId验证if (clientId != null && !clientId.equals("") && !clientId.equals(tokenRequest.getClientId())) {" `. g1 t, t, z$ h5 z4 N% ]

0 T& ?( u5 J8 A) m

throw new InvalidClientException("Given client ID does not match authenticated client");3 h; s8 i/ Y: m2 Y } else

# C! L2 X4 [' G( C

{' O9 j* V2 H" U6 J5 ]6 n if (authenticatedClient != null) { ( u( p# t& |, q! b( G/ \5 Q' B //5. 授权范围scope校验this.oAuth2RequestValidator.validateScope(tokenRequest, authenticatedClient); 8 N Z C7 R' ? } " U \; ^- t4 ^4 j

/ e& A1 q) ], r7 L, t( A/ L3 S

//6. grant_type是否存在值,对应四种授权模式和刷新tokenif (!StringUtils.hasText(tokenRequest.getGrantType())) {" G+ w, Y Z8 R+ u. j5 ~5 g

( f2 J' Y' ~- h5 N; ?3 ]

throw new InvalidRequestException("Missing grant type");4 Q) j8 L3 v4 }5 C1 s: f* C$ F //是否简化模式 3 z7 y6 Q1 x. [, j5 H. P } elseif (tokenRequest.getGrantType().equals(

3 W% B4 i3 t. }" q6 k

"implicit")) {' v3 W3 G" ?6 @# V throw new InvalidGrantException("Implicit grant type not supported from token endpoint"

- p- U) M& `" X& {

); 6 f. {0 S, s7 l } else { % R. W5 s# ~, g$ @ //是否是授权码模式if (this.isAuthCodeRequest(parameters) && !tokenRequest.getScope().isEmpty()) {" {* c. }% @3 L. R% n2 I" I1 Z

6 f0 m( ?# F9 c8 b y# i: C P7 ]

this.logger.debug("Clearing scope of incoming token request");* B1 M3 w: t6 U& _5 V; I) b tokenRequest.setScope(Collections.emptySet());6 i0 W, I4 h! A" [; @ }* T" F8 W- I! b9 A" E ?3 G- A" S

1 j5 e- O5 e. f

//是否刷新令牌if (this.isRefreshTokenRequest(parameters)) {+ t! O5 |* `8 G tokenRequest.setScope(OAuth2Utils.parseParameterList((String)parameters.

/ |2 |% I. G' |2 t

get("scope"))); # }! r) I) B b1 D8 B } 4 ?6 w% y% S2 u# Q$ f1 Z //7. 授权控制,并返回AccessToken p! k! A/ J2 O8 B! Q4 j OAuth2AccessToken token = this

) X5 w, D) J( m/ }/ J+ K+ q

.getTokenGranter().grant(tokenRequest.getGrantType(), tokenRequest);" {, j# m# ^2 m' t if (token == null) { / ]6 K/ `4 G; Y5 W

& y$ [4 p7 b1 |6 K; T& W

throw new UnsupportedGrantTypeException("Unsupported grant type: " + tokenRequest.getGrantType()); 8 `! y- I. \2 t5 P" C }

$ t2 b( p1 C1 |( z' ]

else {/ s1 w/ [6 y2 P, r3 H3 x returnthis.getResponse(token); . F q4 J2 R. _$ @8 u+ ? } 2 N2 c7 u/ }% u, V* J } / n) ]0 T9 [# O. Q8 w6 ` } 6 d" k3 |/ Y5 Y8 l9 L. g }' l; l5 _ v T9 K }+ o" ]6 y' ^5 |( | 2.4 资源服务器2.4.1 资源服务器配置

+ R& m) W& R, G7 j( A2 V" q

资源服务器(可以与授权服务器或单独的应用程序相同)提供受OAuth2令牌保护的资源Spring OAuth提供了实现此保护的Spring Security身份验证过滤器您可以@EnableResourceServer在@Configuration类上将其打开,并使用进行配置(根据需要)ResourceServerConfigurer。

1 P* T) M6 G9 ^. N. f

可以配置以下功能:tokenServices:定义令牌服务(的实例ResourceServerTokenServices)的bean resourceId:资源的ID(可选,但建议使用,并且将由auth服务器验证(如果存在))。

! r- K, ?$ \1 X3 G3 S

资源服务器的其他扩展点(例如,tokenExtractor用于从传入请求中提取令牌)请求受保护资源的匹配器(默认为全部)受保护资源的访问规则(默认为普通的“已认证”)HttpSecuritySpring Security中配置程序允许的受保护资源的其他自定义

/ ^4 C$ B- n3 c, [

该@EnableResourceServer注释添加类型的过滤器OAuth2AuthenticationProcessingFilter 自动Spring Security的过滤器链 代码清单:@Configuration。

: R2 A0 A. F- {$ b

@EnableResourceServer8 j+ L% d2 R1 V) F public class Oauth2SourceConfig {0 R+ _- W+ ~4 @. w, L! w 9 ~5 l2 |8 H: T: m& W: C' E: v //配置资源url保护策略@Override7 E# H- ^- b* c public void configure(HttpSecurity http) throws Exception { # |7 ~5 z- h' A

- ]4 }. J2 k% H2 N2 o9 x

http.authorizeRequests() , F: W' r, X4 i" d1 g8 B/ r$ L0 i .anyRequest() . z. ?) w% m9 z& o5 V .authenticated() ( r9 ?3 F0 r( G1 V2 A+ F" S .and() # B* h: ~$ O" G$ [+ Y6 `% N3 U .requestMatchers

& F6 y- d6 P4 d- n( c+ {( i

() , d$ V9 V, @8 e: \9 J3 h .antMatchers("/user/**");//配置需要保护的资源路径: R- ]9 C* ]" z3 W } 1 z. ]8 D& N0 A# W! Z# t9 K4 X3 A+ T8 y //自定义资源保护令牌策略publicvoidconfigure(ResourceServerSecurityConfigurer resources)

4 x' k- O U$ [8 U* y

throwsException { 6 I* r8 s; Q6 M) @# x) f8 O4 a resources.tokenStore(tokenStore);3 C0 V9 j4 D* ~9 G* j4 u2 H }& @; H& N: [! t) w) u4 J5 P } ) @$ F% b$ q4 b' h( F# i% S2 U 2.4.2 使用令牌获取受保护资源

: W3 P, [) E) D

2.4.3 源码分析2.4.3.1 OAuth2AuthenticationProcessingFilter资源服务认证入口FilterpublicclassOAuth2AuthenticationProcessingFilter

' L+ c; ^* N' e& D1 n1 |7 {/ R

implementsFilter, InitializingBean{3 [7 y, B' Z' i% U //省略......publicvoiddoFilter(ServletRequest req, ServletResponse res, FilterChain chain)

) d' `! d# s N9 r- M

throws IOException, ServletException { d( |: ]; t$ `5 x; ^ [) C boolean debug = logger.isDebugEnabled(); + G0 }3 V) w, W2 U% F/ ~* U; A& S! k HttpServletRequest request = (HttpServletRequest)req; ; k+ Z, m# q# h+ x8 {/ X HttpServletResponse response = (HttpServletResponse)res; , Q- [6 h5 |. w/ `0 k# \% g2 { " h2 S% P; {; w- U5 }4 h

; P5 g3 S- }3 v3 B1 [& n8 w! X* O ?2 ~/ @

try {+ S# u V8 b; R$ B! A //1. 从BearerTokenExtractor 获取Authentication 信息" P9 ?; N E0 t Authentication authentication = this

4 Q; {& ?3 [+ r, q

.tokenExtractor.extract(request);) ]. w- A, X$ h if (authentication == null) { ; R& O: `) f! Q9 D) [ if (this.stateless && this

3 U, R( e& m8 W; m. ~+ b/ f

.isAuthenticated()) { S* k1 A- i5 W' `9 W y5 K+ O9 _ if (debug) { A7 A; f0 \5 l5 Q6 [+ o- I logger.debug("Clearing security context."); % ~% @, [/ G7 x3 Y7 F3 k/ N } ' w+ q2 S1 G8 F8 b8 D; B, h4 R1 s: s4 V SecurityContextHolder.clearContext(); : P0 p4 w" S- X6 V } 6 ~* B+ ^$ O! |4 o4 f! o L3 k6 R3 J/ C3 w: l: r) V

& t1 F* k0 i4 f) a

if (debug) { 8 |5 l& E0 k4 A logger.debug("No token in request, will continue chain."); $ f' L# R" O" c# _9 R }! H& _7 S, j! T! J. X } else

! N; T# g- a. v4 O

{: `7 r0 @+ s: ]1 b4 V3 O) C request.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_VALUE, authentication.getPrincipal());) T( H" |' f8 O0 b" L

3 i; C, ~2 J2 m# B7 W! y4 J6 {4 [

if (authentication instanceof AbstractAuthenticationToken) { " Z5 n- |# T: @1 W1 F& l AbstractAuthenticationToken needsDetails = (AbstractAuthenticationToken)authentication; ( d+ K* C V0 I/ ~ needsDetails.setDetails(

9 w0 Z5 z/ e& K A W

this.authenticationDetailsSource.buildDetails(request)); K% s2 d" C4 |. | } ( |! j5 k e7 a5 a. @9 p3 N //2. OAuth2AuthenticationManager 进行token认证

+ ~( E. U$ J, F6 g) _$ }! U9 m8 Z" d

7 \+ R3 n. c2 X" z) L Authentication authResult = this.authenticationManager.authenticate(authentication);9 G! g( o- t b7 ?

- Y& q4 s# D8 n$ N5 c0 ?9 E7 j

if (debug) { & U8 s& l& k" C7 ~1 N( l+ x4 H logger.debug("Authentication success: " + authResult);# ^8 r# F/ j: V& n; j }4 o# \8 O8 }. w! N //3. 将认证结果放置SecurityContextHolder上下文

s2 u/ d$ R- Y+ E: a: f

this.eventPublisher.publishAuthenticationSuccess(authResult);( X, F+ \% N% r/ Y! }, {: N4 \ SecurityContextHolder.getContext().setAuthentication(authResult); * R, H! e. u9 G0 ^, K9 R } % @9 d; s% ~/ ]- z }

, o: U& L# P/ K6 Z: U) s

catch (OAuth2Exception var9) { + }1 l* ?+ h2 ?* Y0 E SecurityContextHolder.clearContext(); $ s) M, O8 i8 }5 Z4 T+ ~/ T( d% I6 ? if (debug) { ( Y$ N/ k. X% i* N logger.debug(

2 X2 I1 Y; C/ F+ [

"Authentication request failed: " + var9); 9 V) q9 [ V4 R$ K } . n: A/ \0 s: c* P# J1 V ( @* z' n( [/ F) S9 M } J' L this.eventPublisher.publishAuthenticationFailure(

1 `* M) K9 g$ F& i; R' ^: c

new BadCredentialsException(var9.getMessage(), var9), new PreAuthenticatedAuthenticationToken("access-token"

7 Z* F- D$ }4 S$ R# ^/ Q

, "N/A")); 6 t* |2 j* N0 }! R x5 ^7 T this.authenticationEntryPoint.commence(request, response, new InsufficientAuthenticationException(var9.getMessage(), var9));; K, k* _- P9 a* N- E0 B* b# f0 A9 R. z

; O7 {& u N! Z5 O- h

return;- i2 M& o9 `4 W. V1 j } # V1 e0 w+ b0 `/ v$ }2 P! L" H, A1 ]) c chain.doFilter(request, response);; [0 e- k( d' B7 O5 X } : O( M8 c8 }, D) P) L 6 U; M: y$ f* F# \) p //省略...... 6 f5 b3 `' u* v' W1 K- ^' { } 1 j$ V3 I7 E- y; Z 2.4.3.2 BearerTokenExtractor

& }2 M) M' v G7 Z9 S

从请求 Header中获取tokenprotected String extractHeaderToken(HttpServletRequest request) { . B, A+ S" G! G; d' p% _% B Enumeration headers = request.getHeaders(

- R. g. S) A$ V" H0 h. F5 u' q

"Authorization");0 C6 ~7 i0 r8 O) D7 W1 j( z 4 B$ j) |6 ~: r0 z String value; 7 D) v7 x9 {5 {$ i do { $ A6 w2 [! X& H" }4 {1 ~ if (!headers.hasMoreElements()) { @2 g3 \% H5 P( C1 v# k5 Z9 P returnnull

* x" u! E& U0 X3 ` J: W

;$ d& W+ N" K# Y } 9 _% e. T! m( [9 e. ^0 {9 H' d1 A6 M( N2 F value = (String)headers.nextElement();3 V# U; C, a0 A D9 q2 h } while(!value.toLowerCase().startsWith("Bearer"

# [, L. X8 M% g5 S9 b

.toLowerCase())); " m8 k& [) P3 s; ], `8 S$ ?3 d$ x# E: U; _0 f$ x# ` String authHeaderValue = value.substring("Bearer".length()).trim();1 t ^0 D, {' }5 H, `8 d% `1 q request.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_TYPE,

3 _$ v- S7 o6 @

value.substring(0, "Bearer".length()).trim()); 8 R" j- V( {+ x1 l1 I! L5 B. s; I int commaIndex = authHeaderValue.indexOf(44); + m: a! x2 l, _9 B2 f. U

4 S2 X* {2 m7 x, Q) Q! p- g& @* P

if (commaIndex > 0) {1 L* Y% q! @* i, p3 v authHeaderValue = authHeaderValue.substring(0, commaIndex);7 R! r- s2 d% W }& Y3 d% S5 u% L" ?; f ' @4 _. M" \& b return

% e1 x* ~7 |5 z0 S2 T

authHeaderValue; ; I; [. d: B! k8 ^" `$ Z }# a# u" ~- v0 P5 t+ D, z8 W8 V 2.4.3.3 OAuth2AuthenticationManager资源服务认证token校验实现 程序片段:public Authentication authenticate(Authentication authentication) throws AuthenticationException {( u7 i0 G5 I% K3 P( F& y; i% Y. ~

/ z, R2 a0 o3 @6 A$ k+ b5 ~. e

if (authentication == null) {* Y, T' `( V/ N j0 X D& F. S8 I/ x* S thrownew InvalidTokenException("Invalid token (token not found)");( B& K5 z9 w l4 E E6 o4 P/ v; m }

5 E" C. S" J* s. r' p0 j- r5 e

else {# x" u% ] a1 j* |: V' n String token = (String)authentication.getPrincipal();6 R7 m- M: K4 F9 b' f: ^ //1. 从验证token存储介质获取请求传递的Access Token获取对应的验证信息

, |4 B3 t" _: V: c: Y/ `. Q& y) U

6 D$ I( F) a2 X OAuth2Authentication auth = this.tokenServices.loadAuthentication(token);0 J% |2 B6 p- E: G" `' Z if (auth == null

/ o# ^, R, x. N" S5 W B5 N

) {6 h2 |; w, ], R; U thrownew InvalidTokenException("Invalid token: " + token); 1 _8 g8 C* l+ s/ n J4 J. S/ x } else {, r1 o$ F* `! g1 p //2. 验证token并加载验证信息

3 b6 i$ r i8 z; \: Q2 f. e9 O

$ }" U) i$ m" j6 t, E Collection resourceIds = auth.getOAuth2Request().getResourceIds();! k% s V: i, E; [: T { if (this.resourceId !=

$ L! @! Y2 R9 ]( _- _

null && resourceIds != null && !resourceIds.isEmpty() && !resourceIds.contains(this.resourceId)) {8 O3 a. r% q, N/ }/ G3 L' h

7 ^! N: u4 |, i; G( I+ n

thrownew OAuth2AccessDeniedException("Invalid token does not contain resource id (" + this.resourceId +

/ |! B8 C A# N! q, D d

")");) O4 t, O; o% ^3 p } else { " p2 p' O; o' _' s this.checkClientDetails(auth); ! B5 D' E. Z# i# a/ ^# l" H- f if (authentication.getDetails()

, f7 c: g" S6 K7 Z* Z1 g: S W

instanceof OAuth2AuthenticationDetails) {! w8 f d* Q* y- H# @$ L OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails)authentication.getDetails();/ L9 I+ ?- a8 S2 N6 q1 d1 R

8 F$ \3 O3 ]# Q/ u2 g

if (!details.equals(auth.getDetails())) { 2 D% l, ]4 f3 T Y. U details.setDecodedDetails(auth.getDetails()); 5 a6 ?4 D$ i+ C- I- ^+ K } 9 v0 Y% F* v; A2 z8 X } # h% a$ W* \' O9 ^9 Y1 [3 a8 H! U3 k) T# U. U8 T auth.setDetails(authentication.getDetails()); 6 e, G4 K4 M9 d9 a7 E auth.setAuthenticated(

# B" ~& U* E/ h& Y+ I, e

true);- Z, x4 T! N% T! ?% N3 n2 @% @: Q5 z0 } return auth; 7 x+ l9 Y# A( T }4 a8 g4 I. p5 `; a/ A } & T$ V6 @1 T& F0 U$ O. a } % y, W; q$ t4 L! |$ L } / W$ H7 a H% @7 g* @ 3、OAuth2 扩展3.1 自定义异常处理3.1.1 自定义授权端点处理异常授权服务器中的错误处理使用标准的Spring MVC功能,即@ExceptionHandler端点本身中的方法。

' c, `- t) \; F4 V! X4 C

但是其原生的异常信息可能与我们实际使用的异常处理不一致,需要进行转义可以自定义WebResponseExceptionTranslator,向授权端点提供异常处理,这是更改响应异常处理的最佳方法//省略

& C! o# y- ?, G* d4 E

@Autowiredprivate WebResponseExceptionTranslator webResponseExceptionTranslator;3 X* m! p# s. I' [, Z 4 N" K6 N/ a+ x) S /**4 _7 V( T- w& a: q * 自定义授权服务配置 [ B/ G$ H/ G * 使用密码模式需要配置 ( K2 k3 r$ |) Z. d! Z */

9 p. a3 F1 d$ l# j

@Overridepublic void configure(AuthorizationServerEndpointsConfigurer endpoints) { + K4 o5 g* j' i, C endpoints.authenticationManager(authenticationManager)# f+ Y: O4 c4 ?1 x7 h. L3 M P8 I% [; Q .userDetailsService(userService)7 M$ I' Q4 V" ]' W7 ] .exceptionTranslator(webResponseExceptionTranslator);

5 I- ?6 o$ R0 q

// / X% m7 B% T: E! k3 }% t0 g! d# v9 Z/ b' }+ l }# s5 T3 _$ G- k& b- \- Z; ^ //省略/** ) p1 }$ [; N0 {2 D3 \2 f * 实现WebResponseExceptionTranslator接口,自定义授权端点异常处理 8 Q% Y" n$ O2 o* c3 K0 o9 x3 [ */@ComponentpublicclassCustomOAuth2WebResponseExceptionTranslator

A% E+ L5 m' R3 x

implementsWebResponseExceptionTranslator{4 H! G. g/ u. }' P& e& m. i private ThrowableAnalyzer throwableAnalyzer = new DefaultThrowableAnalyzer(); & \- K8 y! A( L" M 4 L' l c) s5 @' X7 M

% X$ \6 e9 s2 `* g8 e! Q

@Overridepublic ResponseEntity translate(Exception e) throws Exception { 9 U) @* ^( y% ^, Y s3 I( o g Throwable[] causeChain =

% P- A6 O" M; U- g3 o/ A

this.throwableAnalyzer.determineCauseChain(e);; [% ], F5 P6 X/ x0 X Exception ase = (OAuth2Exception)this.throwableAnalyzer.getFirstThrowableOfType( * b5 Z3 C3 \( m# r# X1 w& m# N OAuth2Exception

" a% d( y1 `1 {8 p' ^2 }' \

.class, causeChain);if (ase != null) {4 f' e7 s6 A& J returnthis.handleOAuth2Exception((OAuth2Exception)ase);% g: V- T4 B: I) P% q }- [- P' o3 V3 X1 _ t; t8 n" N ase = (AuthenticationException)

+ G; u7 k: [2 `: @

this.throwableAnalyzer.getFirstThrowableOfType( 7 }8 l; P4 k* u6 i4 R AuthenticationException.class, causeChain);

. w$ I0 G0 V8 n8 G. E, c o

if (ase != null) { $ Y6 q! S3 e# x5 w+ l6 S9 C returnthis.handleOAuth2Exception(new UnauthorizedException(e.getMessage(), e)); & T: _! }1 |4 E+ n/ ~" I. }* I3 x }5 X; Z' I& @& s- I- v ase = (AccessDeniedException)

4 b. G. h( I! K3 T( p5 }

this.throwableAnalyzer.getFirstThrowableOfType(; d0 A! X9 C5 c" f AccessDeniedException.class, causeChain);

2 t3 F7 G# H. l8 b# F% V

if (ase instanceof AccessDeniedException) { 0 o6 G B v% Z7 J1 T+ t2 f$ C+ V4 C returnthis.handleOAuth2Exception(new ForbiddenException(ase.getMessage(), ase));8 g% j/ y2 I+ e) ?7 Q! A) W }. ?. m/ [! A9 ^6 k" L# v& [ ase = (HttpRequestMethodNotSupportedException)

+ m! S* S6 X: K4 ?0 |

this.throwableAnalyzer.getFirstThrowableOfType(HttpRequestMethodNotSupportedException.class, causeChain);

5 j% F6 l) |; Z1 K

if(ase instanceof HttpRequestMethodNotSupportedException){/ e! c; x2 G L* Z) d- E s returnthis.handleOAuth2Exception(new MethodNotAllowed(ase.getMessage(), ase)); : m' e0 {/ j9 O1 \ }. x% [% r' p, e2 [/ B! V2 Y 5 `" i7 z1 `8 ~) Y# k& \

, n( Y4 @$ Q0 T! R" L0 ^; T# r

returnthis.handleOAuth2Exception(new UnsupportedResponseTypeException("服务内部错误", e));1 z' B+ D) ?+ F4 Z }! n/ r" K2 G/ P4 H/ V% r( o. B6 [ ( G9 v! {. c$ L" u! d private

, a* J! ~* U) V6 R+ Z- P

ResponseEntity handleOAuth2Exception(OAuth2Exception e) throws IOException {8 H" U4 |6 E7 k1 S7 y- k* b int status = e.getHttpErrorCode(); ! w8 O7 M# |4 y HttpHeaders headers = new HttpHeaders();% a5 R+ Z* t; i4 F headers.

0 `4 S" n/ ~, W: j

set("Cache-Control", "no-store"); / n: y# E- h& {6 d6 q8 _5 c headers.set("Pragma", "no-cache"); + P5 m+ o, ~( g& f! ?0 Y if (status == HttpStatus.UNAUTHORIZED.value() || e instanceof InsufficientScopeException) {. O6 [. a4 F$ [) t5 G3 R( D headers.

# U" k9 l2 b, C* e( [

set("WWW-Authenticate", String.format("%s %s", "Bearer", e.getSummary()));# u1 d6 ~) R0 Z2 h! [ ? } 3 n" u4 M! k6 X& l$ v CustomOauthException exception = new CustomOauthException(e.getMessage(),e);: d `8 N% y8 b. w: E' |7 A, Y ResponseEntity response = new ResponseEntity(exception, headers, HttpStatus.valueOf(status));& U) b+ P) \1 G

+ ?2 G, H2 a, t1 y2 T5 U ?3 s

return response;2 h3 I9 R: h3 D5 Y% U" v }, d( q1 h4 i. D7 ]6 a! y( o/ d! q //省略3.1.2 自定义匿名用户访问无权限资源时的异常当访问未纳入Oauth2保护资源或者访问授权端点时客户端验证失败,抛出异常,AuthenticationEntryPoint. Commence(..)就会被调用。

5 {# w1 Q" F R: i; T

这个对应的代码在ExceptionTranslationFilter中,当ExceptionTranslationFilter catch到异常后,就会间接调用AuthenticationEntryPoint。

3 j1 M# D0 `+ l' I7 |; z' L

默认使用LoginUrlAuthenticationEntryPoint处理异常,当抛出依次LoginUrlAuthenticationEntryPoint会将异常呈现给授权服务器默认的Login视图访问未纳入Oauth2资源管理的接口 当访问未纳入Oauth2资源管理的接口时,因为应用接入安全框架,因此依旧会进行权限验证,当用户无权访问时会有ExceptionTranslationFilter 拦截异常并将异常呈现到默认的登录视图提示用户登录:

* t, ?- ^; J% ?# O4 y/ A4 a6 l

调用授权端点,客户端校验失败 当调用授权端点(/oauth/token)时,根据前面的源码我们知道在授权认证前,会先通过客户端验证Filter进行客户端验证,当客户端验证失败会抛出异常并由ExceptionTranslationFilter 拦截,将异常呈现给默认的登录视图:

- Y0 P9 w0 B5 R

源码分析://顶层授权认证异常处理Point package org.springframework.security.web;; }( H1 n6 s$ \ 8 V% r; }( E$ e5 ]9 ~ import ... - A; q/ U/ s$ s* t, I% P / x0 {( d% f2 i publicinterfaceAuthenticationEntryPoint

1 P& _5 ?5 A8 E2 G8 E1 z9 X

{ % m6 O K8 v( ] voidcommence(HttpServletRequest var1, HttpServletResponse var2, AuthenticationException var3)throws

: H2 E; R9 U; Z6 U* n& Z

IOException, ServletException;6 N! L+ h( Q/ B( u, R) E } . ]! G9 `+ K w$ f7 L 当ExceptionTranslationFilter catch到异常后,就会间接调用AuthenticationEntryPoint。

1 H- G. @' p- Z, s J1 n9 M: X

package org.springframework.security.web.access; 4 }( l8 `+ j0 L9 l0 `! B0 j) Q, h+ S! j ]7 x import ... % H* J2 o1 D, O6 h publicclassExceptionTranslationFilterextends

5 |- d4 p/ ~# b% q

GenericFilterBean{& U# M" ]8 E! o //省略......public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { , `3 a/ y( M1 o3 I- O( i HttpServletRequest request = (HttpServletRequest)req;4 L5 L3 J, E+ O+ \# ~5 p& ? HttpServletResponse response = (HttpServletResponse)res;2 I1 {6 F1 H! w6 p9 U: r* } 1 n& K4 ~( @5 g/ f

4 F; X5 Y G( ?

try { ~; n5 J- n" e& z7 I chain.doFilter(request, response); 9 J9 _7 I, `& C this.logger.debug("Chain processed normally"); ! ]3 k; X1 P+ a/ I2 m }

: o, j0 @% M: K6 G. U5 Z* c

catch (IOException var9) { Y9 ~ n! A+ v# J! _ T# ] throw var9; 5 }! U% ]) V" M8 l- ] } catch (Exception var10) { + k$ F W7 r( E& I( N( L+ o Throwable[] causeChain =

% N5 A8 D) Y$ [' G* \, O

this.throwableAnalyzer.determineCauseChain(var10);" s* H) H% `# F& p; x! R ~4 I$ O RuntimeException ase = (AuthenticationException)

M i0 i5 F* {

this.throwableAnalyzer.getFirstThrowableOfType(AuthenticationException.class, causeChain);if (ase ==

|1 \& h- t n% G

null) {3 C. _% {# j/ g% M" N6 y: \1 U ase = (AccessDeniedException)this.throwableAnalyzer.getFirstThrowableOfType(AccessDeniedException

6 B5 n6 C9 L7 C) L' E7 \/ R& r: o+ f

.class, causeChain); 4 N* M$ s. L0 B' N/ L \3 ` } m8 a) N7 m$ V* d- B! d% y' E! y1 L - X3 C" R4 Y$ X2 x9 c+ W9 P6 ^ if (ase == null) {4 D: n. H8 B: f# T$ w0 b+ h if (var10 instanceof ServletException) { ' f4 L q6 k" U s' \. s m, q! A! m

- @2 Z' ~7 P8 P3 P- R

throw (ServletException)var10;6 q2 x" a i E L5 @) |5 e4 _ } 4 M) j' g; _% R0 k' A% h/ @& ]0 ], U0 t. i / c. L$ O3 r. m* A) p# l if (var10 instanceof RuntimeException) { : R7 z, \6 r: @' N

. `/ M$ r5 z0 D* A L3 U Y; i9 L

throw (RuntimeException)var10;, C' O" s, ^% H8 o" c& Y }( P; h! W7 h2 o) [/ v ! Z# P0 L5 c) } l2 x throw new RuntimeException(var10); 5 k9 {% j/ q* m( m } 4 p4 ~' r) f2 b% }; d4 W9 ~- Z) q3 p: B/ k2 _2 f" z if

/ K6 x7 {. c) j4 d2 f

(response.isCommitted()) {5 B# E/ p& U- _* |, h throw new ServletException("Unable to handle the Spring Security Exception because the response is already committed."

0 A4 w6 c) a4 m- ?! I

, var10);) G4 l6 h, B# n$ t4 R }6 [+ N3 M4 `, W- l //异常处理,间接调用AuthenticationEntryPoint.commencethis.handleSpringSecurityException(request, response, chain, (RuntimeException)ase);' ~' j2 X/ H' v }. v$ g4 b7 V) ]7 n; g5 w o$ n; H- @0 h0 u; y; Q7 |* L2 U } ' x8 z; T4 b6 z6 c J - b& k8 L% I: x" U$ b' Q( Y4 ]

7 _8 s- l! Q5 g' e) v8 `

//省略......private void handleSpringSecurityException(HttpServletRequest request, HttpServletResponse response, FilterChain chain, RuntimeException exception) throws IOException, ServletException { + d. A( {8 \# z7 g

. |! [- T7 f* p i7 _

if (exception instanceof AuthenticationException) {/ @6 O4 C6 o' t' v0 } this.logger.debug("Authentication exception occurred; redirecting to authentication entry point"

9 o3 E) d" J, g

, exception); * G j5 z* H$ I" b! _ this.sendStartAuthentication(request, response, chain, (AuthenticationException)exception);' E7 K4 u+ ~. q: |- r& o m }

" u, Z' G9 I2 s, `: x2 J, h

elseif (exception instanceof AccessDeniedException) {4 k/ V. M1 f7 S2 H& ?9 V! h Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); " l1 L- G6 w, D* F/ b+ T7 Z

7 \/ p" q" w" |. o7 S/ \9 Q

if (!this.authenticationTrustResolver.isAnonymous(authentication) && !this.authenticationTrustResolver.isRememberMe(authentication)) { 5 q4 I; ]! b/ ?- ^7 O2 |

! r% S7 M2 Y( S& q5 \

this.logger.debug("Access is denied (user is not anonymous); delegating to AccessDeniedHandler", exception); ! s$ M& N# Q' d9 J

3 u2 j3 L; j7 d" H5 \) p

this.accessDeniedHandler.handle(request, response, (AccessDeniedException)exception);( p8 u1 X" U+ Z& f! n& x8 z! ]$ @ } else { % `9 I4 v4 R/ ?2 ~0 I) i8 @

* x' i* N+ A- j6 o, O" J# ^

this.logger.debug("Access is denied (user is " + (this.authenticationTrustResolver.isAnonymous(authentication) ?

1 m& \; Q+ w" g) q4 d

"anonymous" : "not fully authenticated") + "); redirecting to authentication entry point", exception);9 X7 k( z, e, Q9 @

7 w7 p1 u: F8 I, H/ p2 `; F

this.sendStartAuthentication(request, response, chain, new InsufficientAuthenticationException(this.messages.getMessage(

5 P8 H* G' `! s- \9 d# Z

"ExceptionTranslationFilter.insufficientAuthentication", "Full authentication is required to access this resource"

3 c" I+ G2 T0 J. l

))); 0 l; ]* f3 X7 ` H5 ?/ E3 Z } 7 f/ U3 y. X x/ K% c) i8 X* ~ } 0 x: a$ K" z! n4 o- k- Q* l, e8 B( [ }# x1 o8 n; }* b ; O3 q7 n5 \7 r+ M# ]7 L+ U ////异常处理,间接调用AuthenticationEntryPoint.commenceprotected void sendStartAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, AuthenticationException reason) throws ServletException, IOException { 8 q @$ g6 }" L SecurityContextHolder.getContext().setAuthentication((Authentication)

$ q, l' c, i! v1 T

null);$ _( Z6 i( v" ^- m5 B+ O# { this.requestCache.saveRequest(request, response);& H% G+ c" D) r6 w& r. C this.logger.debug("Calling Authentication entry point."

' z% S( H8 e# V6 S. n1 R

); $ O! p0 w, J9 g this.authenticationEntryPoint.commence(request, response, reason); * N8 @) P1 ~2 B- ? }$ M$ d0 x- F$ H" N + Q" I( S* r( g$ B //省略......//默认的异常处理,会将异常呈现给默认的Login视图

/ s/ ~- ?! A) T3 u, H0 Q. n

package org.springframework.security.web.authentication;5 u, O4 A: [# F' _! N k/ } / {0 A! Q; D4 I" N- u4 y import ... ) ]" F8 ^+ k3 a- g6 J ; b) ?; \( i$ F, D; l4 P publicclassLoginUrlAuthenticationEntryPoint

5 q1 X {+ F, W9 h( l

implementsAuthenticationEntryPoint, InitializingBean {//省略...public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException { ) y. J0 Y2 |: X' ^# h String redirectUrl =

$ C0 u5 t* u% L6 ~! F* ]

null;' X/ g0 } d& _" x8 C" l, t if (this.useForward) { ' X. {2 k' I+ U, t. y! R if (this.forceHttps && "http".equals(request.getScheme())) {9 [, n! e" P7 V3 F d" L7 Y- `5 { redirectUrl =

S5 }- f/ d( w; A& h- Z

this.buildHttpsRedirectUrlForRequest(request);5 }, {9 x2 s7 D# ^ }+ h* g7 L, r9 n* h0 d, M ! U6 \. D! m5 X! D# r$ d* c! ~$ U if (redirectUrl == null) { / U$ W' u- q) }" Q- g String loginForm =

% u8 r, `" Y' L/ |% |" ?

this.determineUrlToUseForThisRequest(request, response, authException); 1 f5 T6 E1 M+ `- j# ~ if (logger.isDebugEnabled()) { * k7 r/ k) M( t2 ?, Z$ |+ n2 q0 b logger.debug(

) N& p. P! p5 H+ ~

"Server side forward to: " + loginForm); 0 F# F0 @( y8 s0 G5 U$ T8 l# J, U; \& } } o/ |* H$ H9 I( F * y$ a- V5 O4 R RequestDispatcher dispatcher = request.getRequestDispatcher(loginForm);% I: m9 W, ]/ Q6 u9 }) G3 ~$ k dispatcher.forward(request, response); ?! |% U: g! ]2 |, [& g# z' G/ y

/ {6 E7 V" D/ k x, i" E

return;# v; z& {( b, r, C } " q" x' F9 O* d7 |( q; I } else {! q1 s" o0 C, |/ ^. U redirectUrl = this.buildRedirectUrlToLoginPage(request, response, authException);( o2 u/ C& R, `& u# h4 ~# s$ P- e( T }' w7 f0 y6 B1 s, r2 X& P& q7 @! ? % j+ a2 i0 b% `

3 }" S7 h% d6 _4 v7 j

this.redirectStrategy.sendRedirect(request, response, redirectUrl); . G9 `3 \9 z( x! O D3 M# K6 [# D } 8 q! F1 J+ \. o8 N2 V! ` . {' E2 U- p& V/ a$ k5 n //省略默认的视图呈现异常肯定不符合我们实际的应用,因此需要对此类异常进行自定义处理。

4 t3 _, ]% \/ b5 a# S9 p3 Z

package com.easy.mall.exception; 2 i& \2 `- \$ e! o" m4 [& {7 J% ~+ C' e) Y* `. ]( P$ T1 ^ import ... U; h' R' L% |( D, Y ! P, }5 M* w. Y+ N3 ^& n @Component@AllArgsConstructorpublicclassCustomAuthExceptionEntryPoint

+ l2 r) L0 n8 S; j) B

implementsAuthenticationEntryPoint{; {$ K2 c/ H3 d1 } & C8 e3 L& [: E4 o @Overridepublicvoidcommence(HttpServletRequest httpServletRequest, - o8 @$ x! o& G# P, c* @; V HttpServletResponse response, AuthenticationException e)

* v/ k; |3 l* @

throws IOException, ServletException { 4 @) I# P {7 W: ^: _ response.setCharacterEncoding(StandardCharsets.UTF_8.name()); u+ j' N+ S( s1 H$ y" R% P response.setContentType(MediaType.APPLICATION_JSON_VALUE);) `7 k+ w6 ?6 B3 ?6 ?! u1 v* e CommonResult result = CommonResult.failed(); : E3 E* r9 E8 r9 [5 I result.setCode(HttpStatus.HTTP_UNAUTHORIZED); & S! _( V% b4 Q

: C& l! a* R0 R$ `6 n# s$ P$ ~

if (e != null) { " \: j; _) K7 k result.setMessage("unauthorized"); 9 N. E$ U8 D& p( I0 q. S3 \" ? result.setData(e.getMessage()); ( b' E5 r4 @; f7 l+ h }' v7 L3 L' j9 U/ [( f, K) B response.setStatus(HttpStatus.HTTP_UNAUTHORIZED);0 W- i7 n" H6 z6 J- M+ Y5 } PrintWriter printWriter = response.getWriter();0 p% N6 |8 T3 s# s) E4 C5 d printWriter.append(JSONObject.toJSONString(result)); 2 j+ S" B6 \: u } % q. C8 C/ j/ |* } }7 V( E" `( w1 [' u 1 m: S! j8 l, _$ C$ B% x, Q

6 M- A2 L: l. ~5 `! H& g

@Configuration@EnableWebSecuritypublicclassSecurityConfigextendsWebSecurityConfigurerAdapter{ # \, T3 @: _& y/ V. W# H0 `7 d6 E) z' r: y: L! i @Bean

7 }. S8 c [+ Z% L% B+ X$ U. X% i

public PasswordEncoder passwordEncoder(){; N9 ?) ^& d* P: P' u0 C7 F returnnew BCryptPasswordEncoder();, N! F. R+ m3 p0 O$ ?: g }/ j! \3 T0 ]' y1 z6 r2 e " S" [8 z' D% f' L) r v, n/ U @Bean@Override

% ]. j& C8 y/ X9 S

public AuthenticationManager authenticationManagerBean()throws Exception { ; c2 b2 U. L0 F returnsuper.authenticationManagerBean(); ' x) t! ^( q. J* j+ ]8 E3 H! B+ L }( n6 e# Y2 M) d : Y8 p* u8 M! ~7 O

) d5 O- ?' a2 n. ` ~

@Overridepublicvoidconfigure(HttpSecurity http)throws Exception { * i2 l' M/ Q8 ?" |' I2 q: b http.csrf() 1 j6 O0 R& a) e .disable() ' \& J5 D& f+ y! v. Y, U N .authorizeRequests()0 n/ S. B+ X, Y0 n E; F* | .antMatchers(

' l% E9 r7 ^/ ^* H- i3 K

"/oauth/**", "/login/**", "/logout/**") 2 y- V, H$ J: x3 g" x/ S8 P .permitAll()( I. |! E" j: K. {$ k2 p .anyRequest()! t2 I! x& C; l5 t$ ? .authenticated() 9 n4 | ]- ^. S; g$ C6 h9 H, J3 q .and() $ J( O2 W1 s- S8 i9 n) n* H .formLogin()' B9 q, ^) U4 { .permitAll();" |* i! {- }* [$ J! A

/ _7 r1 T4 F+ M! y! l1 A

//web 安全控制添加注册自定义的错误处理8 r2 u( s) i3 s# h6 x$ P+ s) B http.exceptionHandling().authenticationEntryPoint(new CustomAuthExceptionEntryPoint());9 F, A! ~3 `4 ?! u } \' p( S+ Q; `# b3 O2 i* C }: d2 B: D5 x0 S/ Y7 d6 q- Z

6 w" ]1 |, c. p, y6 I/ o2 `

自定义异常处理后的效果

0 ]5 a1 D# S, ?' o# e8 c$ \7 D

3.1.3 自定义受OAuth2令牌保护的资源认证失败异常受OAuth2令牌保护的资源无权限访问异常时,异常由原生的Oauth2authenticationentrypoint处理,但是其原生的异常信息可能与我们实际使用的异常处理不一致,需要进行转义。

+ a/ Z" ~- k4 i0 l9 @; Y

原生的异常信息响应:{0 J: V* A& b G/ u$ i "error": "invalid_token",: }( C' a( Q4 G; _5 t# p4 s "error_description": "Invalid access token: 1"6 [' x# X8 I% {8 T! v' G+ d } 9 @: S G+ a. N" l" l: y 自定义异常@Configuration

4 L4 A! D. G% e1 t

@EnableResourceServer 3 ?: h$ Y* K. K2 s7 {; e public class Oauth2SourceConfig extends ResourceServerConfigurerAdapter { # _$ a) Z$ M. x7 y: ~" _+ y) t9 p# Y" i) o. L @Override

/ l- d) l, G- w3 u3 z' p

9 b, ^, c. h; t0 E5 q( S/ b9 Y public void configure(HttpSecurity http) throws Exception { . {0 f8 i! q# m. I http.authorizeRequests()/ @; @1 e8 K5 Y' x$ k .anyRequest

) J0 H. b' K7 Y

() 8 D6 _6 Y& i% w7 {0 W* A i .authenticated() ; Z% `* k( p! u" F% `, r! F .and()* _% u' a/ H3 _# E2 L; |7 G .requestMatchers(); c F% O8 s, i0 X+ I9 h/ G( `4 P .antMatchers("/user/**"

6 f6 K) i2 C' p; y1 j: A* j6 F

);//配置需要保护的资源路径( L- ?1 S6 p6 q0 M: A) Q W% Q }/ B) e# a9 |6 n& e$ N & b( y: w7 h# {+ p& u @Overridepublicvoidconfigure(ResourceServerSecurityConfigurer resources) throws

9 ^# `# H, w; F$ G+ s

Exception {+ E0 A! l. O" R0 i( O$ X resources.authenticationEntryPoint(new CustomAuthExceptionEntryPoint());//自定义受令牌保护资源服务异常处理

^4 q, D) g# n# b- x

/ ~2 Z- Q% X- }$ O; A% P } : @' h: ?+ f$ a" ~9 r }; U+ @) P1 a) c 自定义异常处理效果 { K2 a. N: t$ A3 W8 t$ E "code": 401, # \! p+ H) `. f: e: G! \ "data": "Invalid access token: 1", ; h6 X8 b+ ^ u8 t5 `; O5 | "message": "unauthorized"

' ]: P+ H, t# ]( ?/ R

* u/ J, ~; o- y% D7 c }7 \5 A6 F! ^4 u2 P 3.1.4 自定义受OAuth2令牌保护的资源无权限访问异常//待定3.1.5 Security自定义异常分析总结根据上述一系列源码分析,我们知道Security是通过一系列Filter过滤链实现授权认证,不同情况和场景其过滤链不一样,因此当出现异常也通常由不同的异常处理器进行处理,因此需要针对不同情况进行自定义处理。

# I$ C3 S; X* d- c

附录构造Basic Auth认证头/** & m' A8 r; \3 ?) o& t7 @ * 构造Basic Auth认证头信息 - Z. x2 o% G. S3 t * $ `. D" T0 d( s, k" d5 T( _ * @return1 F1 U- ]* ], C" ? */privateString getHeader() { / |; J( M1 y, h6 |7 i String

. Q, C" L G! |, s `. m" ]

auth = APP_KEY + ":" + SECRET_KEY;+ ]# p% J' ~ y$ m$ u5 r1 b byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName(

4 b/ g9 _ h8 f0 R8 f" K2 I

"US-ASCII"))); ) m4 X' Z; z1 g; j+ S String authHeader = "Basic " + newString(encodedAuth); : N9 s! B* n& ~0 Q4 T Q return authHeader;9 ]0 O7 L* r8 v3 m* j, Z }

& G" t8 {( _6 _- a$ T5 k- g- M' n, c( {" ^ % P( J9 ~ W1 G7 g # U/ g, b+ K# Y4 _ 4 j" V X ]; j& c$ v
回复

使用道具 举报

    您需要登录后才可以回帖 登录 | 加入怎通

    本版积分规则

    QQ|手机版|小黑屋|网站地图|真牛社区 ( 苏ICP备2023040716号-2 )

    GMT+8, 2026-7-9 02:16 , Processed in 0.042878 second(s), 27 queries , Gzip On.

    免责声明:本站信息来自互联网,本站不对其内容真实性负责,如有侵权等情况请联系420897364#qq.com(把#换成@)删除。

    Powered by Discuz! X3.5

    快速回复 返回顶部 返回列表