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

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

[复制链接]
我来看看 发表于 2023-03-06 17:34:41 | 显示全部楼层 |阅读模式
- |1 F2 k H% `* R

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

* O! p0 R7 k5 b# F

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

0 g* Z: x# R6 B5 j

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

- Y0 t2 F( D# i1 z

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

' h+ F2 T& Y% a

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

0 J& [: Z, u2 X' o; t: g

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

3 ]4 B' _- c$ \2 Q, @4 d& F, d

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

) n5 ^9 |/ i: K4 c1 C; F7 d

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

5 @( D! m8 d; ~- T

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

% V; A! U+ \! r. [+ @

HttpSecurity.oauth2Client()提供了许多用于自定义OAuth 2.0 Client的配置选项@EnableWebSecurity 7 ^/ c' X# h" J4 ?+ t4 i public class OAuth2ClientSecurityConfig extends WebSecurityConfigurerAdapter { . X {+ P# z) r- K 9 R+ l, r- s: p p# y

+ u& i+ U* ~7 c# \. n/ i, ^

@Override $ T- R, r" t/ J/ S" a7 n protected void configure(HttpSecurity http) throws Exception {) h" a t3 x/ ]4 {1 I3 B" n$ K; z: x http.oauth2Client

# ]( l! P0 E7 T R, z2 C+ e: \

() , U- F5 P3 R4 Z9 f+ U# l( k2 `, v5 u .clientRegistrationRepository(this.clientRegistrationRepository()) ; N, ?# @7 I7 k/ }+ b. m. r9 W .authorizedClientRepository

2 S0 T! A- T9 j, j) p* P0 ]

(this.authorizedClientRepository())# Z/ X" j0 |$ i, T. _ .authorizedClientService(this.authorizedClientService

9 u1 m8 e M5 g( ~

())4 J( U% u4 w% |1 } .authorizationCodeGrant()3 X6 d) C9 F o% ?$ c* D .authorizationRequestRepository(this.authorizationRequestRepository

i! t& p' j8 A( o

()) ( Y" y; w/ A* w, z .authorizationRequestResolver(this.authorizationRequestResolver()) 1 J, i6 \/ S' h+ V* C& m$ {' o .accessTokenResponseClient

+ s' P4 x: T* h, l

(this.accessTokenResponseClient()); 1 t T7 e0 v" h5 \) v( B" {7 E# l }' O! g" l# @+ r8 Y6 i4 p- M9 O. f }( m+ q$ @) a, A& W6 L+ p: M 2、OAuth 2.0 认证服务Spring Security OAuth2 实现了OAuth 2.0授权服务,简化了程序员对OAuth 2.0的实现,仅需要简单配置OAuth 2.0认证参数即可快速实现认证授权功能。

: R& w/ [( K6 H, j' n& G

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

' F2 u8 A" n+ q# |

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

0 X( }1 m% ] Q+ s

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

# {) x9 C( \: A2 @8 V- w

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

7 ^% z8 v% C5 r2 r3 H

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

1 I! E6 M9 g8 j/ ?' p

org.springframework.boot

( i9 P& K, _$ e0 G) n3 g1 R

spring-boot-starter-securityorg.springframework.cloud

& o |2 G5 O4 U* S

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

/ N1 F0 r9 b$ T, v0 G5 S3 d

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

, i C( s6 P' M

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

6 v5 B1 p! R c& j0 `0 F0 l

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

9 x# I& W: U) j, X* O( l

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

0 M; s2 r7 |1 R* }4 L

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

3 V2 n9 k- Y6 o3 n8 R$ x

源码清单:@Configuration@EnableAuthorizationServer D' `- X1 F7 p& t2 h public class Oauth2ServerConfig extends AuthorizationServerConfigurerAdapter { ) f+ |8 o( f1 M/ c9 ^- o# a/ y: j2 E 6 K7 l# t# r4 v2 V$ X3 H2 e2 N5 w

% L7 `8 @7 E0 ]/ E5 b, ?

@Autowired , \; V4 p1 a- X private PasswordEncoder passwordEncoder; 8 n( k. X$ u( g J4 i% d4 c/ i. U1 F9 p% J3 ], d @Autowired & K& e5 i" V5 j5 R% \ private AuthenticationManager authenticationManager;4 ~, O( T% b1 R! T* }3 { c( w2 f3 f p/ f, \5 S6 o1 q; p. H

2 F1 g) P7 t2 A) w7 J; M1 a# t Y9 `

@Autowired & h1 x5 u0 u8 t1 ~& K+ C private UserService userService; 1 |$ q- x! ?' T6 [# Q - e8 R9 r k1 d5 w /** , t) H# t! I9 i, V; z: V * 自定义授权服务配置* I% D) O! W% a- L$ y6 K; W * 使用密码模式需要配置 $ V+ z1 x0 k6 c3 d */@Override % \& \1 V" J) I. O public void configure(AuthorizationServerEndpointsConfigurer endpoints) {% M+ H/ q. [/ @1 O* S4 j: _7 ? N

% ~ [1 F8 A5 `

endpoints.authenticationManager(authenticationManager) # F8 R: y: O0 W4 [4 Y; | .userDetailsService(userService);3 N* M! @# u1 h/ O }: x T5 j& x, L& _ ( y4 _, }, K7 f* @" k, v+ @! J

! o; m3 f$ f6 \- A; J( F8 I4 x

/** 9 u! J& u; _- f; k- y9 V# S4 f$ K) W * 配置认证客户端0 } V D" n5 F. J * @param clients' D3 w c. C) p6 J7 R * @throws Exception: w1 q$ s. d; _ */ 5 B- [/ O: J8 y* p" ^: {; k: e0 U @Overridepublicvoidconfigure(ClientDetailsServiceConfigurer clients)

5 d9 g' m( P; B( s2 o( S( N) u

throwsException { ; g7 \' V, @' ]" G9 h3 E) Z //自定义客户端配置& h! y, f/ g `$ p; h } - k/ H; H: `- Z! w. V- ^% A5 f, W( u/ C0 d0 y, N9 b( q /** o3 O: {- `, J * 自定义授权令牌端点的安全约束9 G) ~2 g. a& u( c) Z7 K * @param security3 j" F# R9 X" ]9 d& z3 J* T! [ * @throws Exception 5 v0 ~% V2 Q+ ~ */

$ |* q, n* O$ o4 y( q# |

@Override ' @: P5 F$ K" E; v# [ public void configure(AuthorizationServerSecurityConfigurer security) throws Exception { ! X5 Y" A5 `& ?$ \/ b5 }- q# o+ y

( p+ N# G, H8 w( Z! {9 [6 G

//自定义安全约束//....7 q* f. l. s1 r! y8 c }1 F1 |% A8 y Y) s }8 ~: b m$ B# E/ w 2.2.1.1 授权服务配置AuthorizationServerEndpointsConfigurer 定义授权和令牌端点以及令牌服务endpoints.tokenStore

; Q, c8 [! ~" ^) c( O- k

(tokenStore)//自定义令牌存储策略//默认除密码模式外,所有授权模式均支持,密码模式需要显示注入authenticationManager开启.authenticationManager(authenticationManager)& Q) V, g' U# r) \5 |9 a% q

7 b( F" s& f# f$ q1 a _

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

1 U; m3 f4 _1 Z6 G) j

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

: I/ b7 H8 G6 Y( C

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

. Z0 c5 g* m) ^ n" S) h. c9 z

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

4 y! ?9 B& R0 Y, g. E6 L

内存加载客户端配置,直接通过ClientDetailsServiceConfigurer添加客户端配置@Override 2 d6 f @( r4 A5 m! M9 _ public void configure(ClientDetailsServiceConfigurer clients) throws Exception {: Z* g( Y: \" h3 G+ [) Q

: \" T s* W3 C/ C8 {) o! W

clients.inMemory() - T7 `8 P$ h. I2 ~0 S .withClient("admin")//配置client_id.secret(passwordEncoder.encode("admin123456"

4 ?; N. b! U- J6 t" [

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

3 q, `* {; O1 L: _

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

4 N; x& a3 c8 r. [( k: Q: i& i3 }

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

) X. F1 B t/ L

- V) [9 {5 Y \* Z: j }5 {* x! O+ G7 C# i; n 自定义ClientDetailsService,redis+jdbc方式加载客户端缓存@Overridepublicvoidconfigure(ClientDetailsServiceConfigurer clients)

, k0 y' f( t6 V3 ^- T

throws Exception {, o7 K8 ^5 g2 ~2 I( T, Y6 `6 V clients.withClientDetails(redisClientDetailsService); 5 F: [2 w& f7 d7 I \ redisClientDetailsService.loadAllClientToCache();

% k& m2 I: a! d4 I: b# t5 f

//2 r3 |9 w. L' I4 N$ K# ?+ c% Z4 p7 d3 p8 a }7 C2 m. O; ?. L* q0 f8 W6 ^' Q2 E 0 V& e' @! X2 b- Y @ServicepublicclassRedisClientDetailsServiceextendsJdbcClientDetailsService{ " g. G* M2 Z% k8 L x/ G //继承JdbcClientDetailsService,扩展redis缓存加载客户端,优先从缓存获取客户端配置,缓存没有再从数据库加载

: X5 O$ M2 \3 Z8 l* d# Z' m5 H

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

/ v) h7 |& ]. O) I$ ^ l& x- |& |

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

1 N/ j5 h: |! R8 f# X7 z# h; Q

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

4 p" q: Q- \0 W' i7 S3 H/ o5 d

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

/ W3 e" K8 i+ x9 r9 ~+ Y

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

* T1 ^4 V' }0 v% h2 l5 ~7 z

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

+ V2 l. A7 S5 a" v' C9 O, L

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

0 C9 q- C t9 @! o5 J

{$ c# G& J# k1 Q- x! b6 _3 D1 _2 X3 t 3 s# {) f8 i. @ @Autowiredprivate QtAdminService qtAdminService; 6 E8 P6 X% t( `/ r7 q& A# X. L5 K& i6 m- Y" a5 Z, ~ ! H! z! Q$ E, F/ g4 m2 Q @Overridepublic UserDetails loadUserByUsername

$ P0 A/ [: U9 P" c( [' p- T( [

(String username)throws UsernameNotFoundException {! {% d: X' d# G# g String clientId = "admin";! S: X" a) g6 p2 B UserDto userDto = qtAdminService.loadUserByUsername(username);8 ^% H' y# ^0 K; r1 i2 {* @2 s

* W- V$ o: V- V

if (userDto == null) {/ s3 b" D4 v0 ], M; O4 l thrownew UsernameNotFoundException(MessageConstant.USERNAME_PASSWORD_ERROR);# B8 h* E" ~( \) } }) c3 v% X# ~- r4 w& R- G2 e6 e3 y userDto.setClientId(clientId);: y. m9 v- |. P2 U, k7 @ SecurityUser securityUser =

( l' O, g) G& I! Y% V% ^# u6 T; c

new SecurityUser(userDto); & Y) v* }% f: H0 {3 y0 z if (!securityUser.isEnabled()) {, c& S9 @ g1 T9 e# o thrownew DisabledException(MessageConstant.ACCOUNT_DISABLED);! L1 v) |( D& U$ K- U& O* d3 C. ?2 S }

$ K) }' {' }7 Z5 F9 \- w+ L- N/ a

elseif (!securityUser.isAccountNonLocked()) {" B8 Z9 g5 \. F( F$ l* d thrownew LockedException(MessageConstant.ACCOUNT_LOCKED);8 S: p* W" o4 w, c* f. a }

$ c. ~2 e8 u5 u2 C# S, o# a

elseif (!securityUser.isAccountNonExpired()) {0 G# W6 U" J- s thrownew AccountExpiredException(MessageConstant.ACCOUNT_EXPIRED); 5 C; n8 ~. X7 F2 z }

5 t: Q6 e: [% Y8 q

elseif (!securityUser.isCredentialsNonExpired()) {8 t( K, L J3 w: F thrownew CredentialsExpiredException(MessageConstant.CREDENTIALS_EXPIRED); # ` r0 d0 n+ j } : o: p* w. j2 Y! {! K2 ]

; r$ S5 d/ [' Y/ X- z5 O

return securityUser;5 G1 m( E5 j6 o; H: V' l } 6 i6 ~' E5 r; L0 u/ s+ Z% i# [8 O } ) ]2 [4 c; o4 `: |. I 2.2.1.5 定义令牌端点上的安全约束在对请求授权的端点进行访问之前需要对授权信息中传递的客户端信息进行认证,客户端认证通过后才会访问授权端点根据授权参数传递方式不同,对客户端进行认证的Filter也可能不一样:。

8 z0 ]( T2 V, x U" C$ L1 |" R

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

$ s, J) ]$ R5 r' g

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

; l8 _& @ r, Y8 I; y

可以AuthorizationServerSecurityConfigurer添加客户端信息验证策略@Overridepublic void configure(AuthorizationServerSecurityConfigurer security) throws Exception { 4 d- Q; u3 p' A security.tokenKeyAccess(

: w0 H1 I. A+ ~2 j8 B

"permitAll()")2 ~! L; @- L, s .checkTokenAccess("isAuthenticated()") |4 F' r8 t9 h9 E- n2 g- ^9 J* ? .addTokenEndpointAuthenticationFilter(customBasicAuthenticationFilter);

% L6 ~' x; k3 X

//添加自定义客户端验证策略 / m8 H# Z# Y7 A' b$ {% R }0 T) M, b! V* v+ O4 P! z % ]! c; c% G$ Q, Y! H) } //客户端验证策略控制public void configure(HttpSecurity http) throws Exception { ; M" T7 F8 u5 H5 q this

5 \# ~% n% d1 w! [

.frameworkEndpointHandlerMapping(); 4 u6 D, u3 ?8 n) g/ @' C; w- T if (this.allowFormAuthenticationForClients) { ! g; q2 i( k) Z2 ~, [" a A this.clientCredentialsTokenEndpointFilter(http); 6 D7 V- Y. _4 _/ I) e3 ^( k: R }# z q# H5 j% P0 y. X% Y 2 w2 x5 S* W+ c' e: ^; c Iterator var2 =

/ ^/ V; D, Q. _; d! R* F

this.tokenEndpointAuthenticationFilters.iterator();* W' J) ?6 X8 o! |2 D3 c ' ?* E" }: Q- v while(var2.hasNext()) { 7 g2 Y) }; R0 p, d. B' Y/ m2 G% v5 [ Filter filter = (Filter)var2.next(); 3 \. Z2 N" S+ Z- ?3 N4 R$ x http.addFilterBefore(filter, BasicAuthenticationFilter

( ], Q6 Y% I4 [

.class); 7 F% p8 Z7 K( I3 z6 g9 r- W3 [ }* g: R% ~. d4 D# }- h 7 D% F0 {$ t# D) Y http.exceptionHandling().accessDeniedHandler(this.accessDeniedHandler);/ }3 Y2 }- o7 S) D8 y; @8 C0 T } 8 b* Z- H5 m- x! h* G$ V$ o* l1 M$ d, |! p# X private

. b2 Z8 G$ g5 Z' E. o

ClientCredentialsTokenEndpointFilter clientCredentialsTokenEndpointFilter(HttpSecurity http) { ; }0 \( i* P; \# ^1 h$ G ClientCredentialsTokenEndpointFilter clientCredentialsTokenEndpointFilter = new ClientCredentialsTokenEndpointFilter(

2 C; d; s, g7 o& E2 X

this.frameworkEndpointHandlerMapping().getServletPath("/oauth/token")); ! B ^% y' b8 ~7 s8 C9 g& u# m clientCredentialsTokenEndpointFilter.setAuthenticationManager((AuthenticationManager)http.getSharedObject(AuthenticationManager

! Y! Q {6 W( I/ d. n' b; h

.class));* m3 e2 b6 o: ^; I' F0 F OAuth2AuthenticationEntryPoint authenticationEntryPoint = new OAuth2AuthenticationEntryPoint(); - t$ h! ~4 o! ]: s2 L& f' Y authenticationEntryPoint.setTypeName(

% |2 N; {5 r) F! Z

"Form"); ) e' d/ E; w4 Q6 b authenticationEntryPoint.setRealmName(this.realm);% b* k7 @3 i: F8 U- T clientCredentialsTokenEndpointFilter.setAuthenticationEntryPoint(authenticationEntryPoint); " I% S! y& D. ]9 F& M clientCredentialsTokenEndpointFilter = (ClientCredentialsTokenEndpointFilter)

% Q2 u& Q4 I! w

this.postProcess(clientCredentialsTokenEndpointFilter);$ y! F/ D8 K! z/ S+ n* Y http.addFilterBefore(clientCredentialsTokenEndpointFilter, BasicAuthenticationFilter

5 P2 x+ e# V% F, J

.class);return clientCredentialsTokenEndpointFilter;0 `9 a8 ^- L U* l5 E- n9 q' C } , p! N0 E( A9 a6 U3 _9 D3 } ^( V0 @ private ClientDetailsService clientDetailsService() { ( \6 m# k1 u0 @ P, j/ U% O$ v

* M0 y" j6 [' a: O' k

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

" I1 a1 V, S* b3 P( {0 ]: Z0 [! V

);8 O3 x2 p$ ~0 |2 O } - m, d! t) O2 p7 n( y7 H2 J' L9 ^ 3 s4 c; }! \8 p3 O, Z private FrameworkEndpointHandlerMapping frameworkEndpointHandlerMapping() {- M: `, R1 W- O+ d, k& }; [3 V* Q3 R return (FrameworkEndpointHandlerMapping)((HttpSecurity)

3 m8 `% u- {# ~$ P, d1 k4 k

this.getBuilder()).getSharedObject(FrameworkEndpointHandlerMapping.class);( g+ X( K( _ ]4 l }3 p: F# ?0 b7 R) D# a $ p' e% }' d9 U/ I) ^% [- p public void addTokenEndpointAuthenticationFilter(Filter filter) { % v0 u, U8 G- C: R8 _1 {5 o

/ U1 ?& o# `; o4 e; o

this.tokenEndpointAuthenticationFilters.add(filter); 7 X, ~% x$ ]0 A. z" E }. A; J' G! ]; g 2.2.2 添加SpringSecurity配置允许认证相关路径的访问及表单登录@Configuration

1 k4 W) i* L3 X8 u5 l

@EnableWebSecurity5 j* T( C- c5 ~& `" j6 B% \ public class SecurityConfig extends WebSecurityConfigurerAdapter {! r1 M9 s8 |; ^. s* m$ o " A2 ?! Y# x; z- E: I @Bean : e2 w7 j1 ]) ?6 P, R6 s' R public PasswordEncoder passwordEncoder() {! q, \- ^ p+ ?) H. _

. w1 L) ?3 P; g4 b: T' g

returnnewBCryptPasswordEncoder(); / I; i( v# A# J) Z: g0 G* P6 ]7 y } * ~9 t' D+ [8 n P5 r% h" D9 S) p, R2 k3 M# E5 `$ V- ?9 }+ _ @Bean# P- F" u2 l9 X" S4 \ @OverridepublicAuthenticationManagerauthenticationManagerBean

; @, r6 l: s" z7 n4 C/ B8 ^5 P

() throwsException { ; v; c0 W w, V( P returnsuper.authenticationManagerBean();1 t/ q6 `' T6 R* z }3 i b1 K& g8 t" f 5 s+ E$ }, Q8 b @Overridepublicvoidconfigure

4 l& w7 K" ^; }

(HttpSecurity http) throwsException {. P' F" n& ]2 ^1 B9 R http.csrf(); u5 e" ^! U6 b1 |/ w) {" b .disable() 2 v R; t: f, [% v# U6 X6 B( N .authorizeRequests() 6 L) l/ r3 n* I6 g

# ]; @" D+ U4 A# X

.antMatchers("/oauth/**", "/login/**", "/logout/**") + z! Z( `! |- l X* | .permitAll() 6 q# J4 n1 c9 c .anyRequest() ( w: b9 o+ _2 t5 x* A( u

) p. k- _) ~4 s( J9 [4 `/ [

.authenticated()& A0 ^' R7 L, @; |0 `# l; W* _ .and() . ], Q7 ~9 Z- H$ }5 o8 J .formLogin() ) r' p+ N, i5 a* V6 u .permitAll();, f) z5 A6 k3 T M- S( M' M7 @( Z } . e; C, s7 a9 x5 @8 U& k } # Q* L8 z) M' X8 C a( h3 Q 2.2.3 Oauth2 验证启动应用,进行Oauth2 认证服务进行验证

) m% r/ `5 d D% g3 R, Z: y

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

6 P" l& ` L+ _ K# |; c1 G: q

在body中添加以下参数信息,通过POST请求获取访问令牌; { 6 _# ?8 p% x9 W# ~ Q, y "access_token": "a690d4e6-185f-4d1d-bc62-0067bd8b6ec9", % L$ f0 G7 f; X8 r0 e# F3 H "token_type"

( h* z, J, J& u' Y8 h: Q

: "bearer", , N( w1 J+ `% x, W: V: q- l1 K9 i "refresh_token": "55a04005-e2d9-44df-99df-01b57429d424", 0 o2 f' h6 f9 \+ I' O "expires_in": 3599, * \4 _8 i& }. p

0 O& g4 n9 o" s0 b/ e1 A2 m8 k& C- S

"scope": "all" 1 _* R5 G7 z3 g9 @ W0 p, C }! J! G- K" B5 A2 C( h9 s' |% | 2.3、Spring Security oauth2 授权认证核心源码分析OAuth2 授权认证大致可以分为两步:客户端认证Filter拦截/oauth/token请求,对授权参数传递的client_id和client_secret进行认证,认证通过继续访问/oauth/token端点;

\8 ^5 O9 K8 G8 r% b

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

1 r. W3 V( G# R+ L, P! x

2.3.2 TokenEndpoint(/oauth/token) 认证源码分析@RequestMapping( , X& q1 x- v. ~, x$ W5 K% [ value = {"/oauth/token"},* @, `& m2 E- i method = {RequestMethod.POST}. X0 w% |8 o; w )

* l/ H' Z: }1 y( j p

public ResponseEntity postAccessToken(Principal principal, @RequestParam Map parameters) throws HttpRequestMethodNotSupportedException { ; W! D: D. N1 i1 h ^- m- }3 m1 \

' H7 h' ^! i% ?# p% z _! C

if (!(principal instanceof Authentication)) {' `& a0 {. B5 w throw new InsufficientAuthenticationException("There is no client authentication. Try adding an appropriate authentication filter."

6 ^* C/ X6 R5 b) Y; u

); 4 k; i/ | H3 Z& ^, n% q, w( r } else {! R2 ~. ?( ~0 I //1. 获取clientId & O- _9 w% B1 @3 |8 a+ A String clientId = this.getClientId(principal); 0 M+ J. i3 \* v8 J //2. 根据客户端id加载客户端信息

7 K3 ?( H/ { R1 _

! X2 A4 P$ j* D9 Q6 x# ] ClientDetails authenticatedClient = this.getClientDetailsService().loadClientByClientId(clientId); " b: B5 L. v! q) J

6 c" M2 u- q) A5 g& K

//3. 根据客户端信息和请求参数组装TokenRequest 2 K9 @+ Y9 Y o7 f; N TokenRequest tokenRequest = this.getOAuth2RequestFactory().createTokenRequest(parameters, authenticatedClient);! S! q! w9 R* J, H9 }# g

+ S/ V% f% `( u

//4. 有没有传clientId验证if (clientId != null && !clientId.equals("") && !clientId.equals(tokenRequest.getClientId())) { D0 G( {: V/ K% o' r' m' r

( [. A/ m H8 `( u' V" b" R

throw new InvalidClientException("Given client ID does not match authenticated client"); : X- v; u% n+ }; f" _) o } else

' k5 b. c) ~& {+ k: l

{ " Q8 w8 W: ]# Y* E8 C if (authenticatedClient != null) { 5 K" @" E% }. F //5. 授权范围scope校验this.oAuth2RequestValidator.validateScope(tokenRequest, authenticatedClient); 6 H; D# i: b' ^' v5 l } S2 R. U! L) D9 Q

0 @/ O/ N; F2 r

//6. grant_type是否存在值,对应四种授权模式和刷新tokenif (!StringUtils.hasText(tokenRequest.getGrantType())) { ], H) H" w( d, f2 L& Y* U

& h, G2 x7 n6 o1 k! l7 i* O

throw new InvalidRequestException("Missing grant type"); 5 v j% U" c7 V% W2 t4 m9 L //是否简化模式 8 B: g2 q, E0 y } elseif (tokenRequest.getGrantType().equals(

* X7 |0 r: d/ g% }

"implicit")) { 8 i( O+ n- ~/ z$ s throw new InvalidGrantException("Implicit grant type not supported from token endpoint"

6 T7 {8 D/ d) e9 f# m

); , @# R) U# q* X5 k7 R } else { ' M2 X7 }! i/ }; A //是否是授权码模式if (this.isAuthCodeRequest(parameters) && !tokenRequest.getScope().isEmpty()) {0 \0 a; V- d* [ W1 ? ^

7 l- k% |: [8 r% Q

this.logger.debug("Clearing scope of incoming token request");9 S, @; p9 y! t9 Z3 _9 s, y& v/ D% y tokenRequest.setScope(Collections.emptySet());: w4 T- [7 P4 N8 t } & P4 k2 p8 k% C! C6 G. w

# V$ U: C/ y; J5 L/ `

//是否刷新令牌if (this.isRefreshTokenRequest(parameters)) {- K& [2 t L" e, K4 }/ P# A) k. ^/ X tokenRequest.setScope(OAuth2Utils.parseParameterList((String)parameters.

( ?7 a# }/ r1 ?3 C, [

get("scope")));0 C' a! }) u- D9 G } ; Z+ P0 ~3 {; @3 v/ r- C" } //7. 授权控制,并返回AccessToken) W: T. m& l" p! I OAuth2AccessToken token = this

; I. Z% l5 e' |0 J! Q

.getTokenGranter().grant(tokenRequest.getGrantType(), tokenRequest); + V) q- s* k9 Q if (token == null) {/ Z* k2 I% z# u( Y7 j5 I. @0 @

/ e+ p5 C' g+ j# J* a& j

throw new UnsupportedGrantTypeException("Unsupported grant type: " + tokenRequest.getGrantType()); 3 p# ^! u2 F f% I: r* V }

# H7 Y2 t6 G6 O) J0 R; |

else { ' v' p& I6 j( c7 S! Q6 f$ f! t9 N returnthis.getResponse(token); ( n: n/ W& @ J: z$ z! v9 K } - B* N1 U. G: {% O: T7 d }1 i) ^9 K, n/ _, h } 7 W6 e6 k. U- Q' m* Y0 S7 a }, V( ]5 H6 q! M4 Y b* Q( ^ }# X! N- `& v* _9 m" j# w 2.4 资源服务器2.4.1 资源服务器配置

* W& o# d/ x V) A

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

6 T6 ?/ ]4 c& u( f) Q

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

7 Q& y& U7 z; j# C5 Y

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

" k1 o9 T- h1 [6 |% C' u

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

& N1 U2 \6 l4 w( S# A! j8 m, Y

@EnableResourceServer2 f! _7 M5 { M- q6 l public class Oauth2SourceConfig { * E1 X( I, C/ {- y1 e! V; R9 a* n3 L. ^/ r0 I! C4 Z, O/ C6 G# O2 c //配置资源url保护策略@Override 1 q4 z4 P, t- {& |, I# Y public void configure(HttpSecurity http) throws Exception { 3 Z# n4 a: J6 Y

" x' F! v" o2 U! y- S+ v

http.authorizeRequests()$ D/ k' }3 y$ | .anyRequest()7 W5 f1 k- k3 g; ]) K1 [" `! } .authenticated()5 W- g( H( e0 u; P2 c .and() : p1 {% j2 A+ [7 F: P% { .requestMatchers

( ]; e# d5 Q4 S- e$ C

()2 q. e9 W' A. n9 q/ I .antMatchers("/user/**");//配置需要保护的资源路径3 B3 M7 ]) D3 F5 U$ @ }* ^7 g3 u% C1 R k: F : C4 K: k; ^1 |( J1 c$ q2 \' Z+ O //自定义资源保护令牌策略publicvoidconfigure(ResourceServerSecurityConfigurer resources)

+ s c4 `1 h) J1 e2 W5 ^9 u

throwsException {1 e6 ]% m- l$ B resources.tokenStore(tokenStore); / o- f- @1 [9 G& r1 V7 g4 e }# B4 {4 \0 l7 o: L } / `) T9 i* @$ Z( H$ J 2.4.2 使用令牌获取受保护资源

4 I6 z! _6 _) }! E

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

9 G; B% D9 ], }$ Z4 J

implementsFilter, InitializingBean{# J; H% ^+ N5 f1 K) A //省略......publicvoiddoFilter(ServletRequest req, ServletResponse res, FilterChain chain)

6 s6 O# n2 S& R$ v

throws IOException, ServletException { " K6 L+ L. G8 H* p boolean debug = logger.isDebugEnabled();1 f% ]+ E* q& _% M HttpServletRequest request = (HttpServletRequest)req; ! P" W3 ?, i! { S" E& b HttpServletResponse response = (HttpServletResponse)res; 4 p0 y7 L; `# z ; Q' s" d! D n) j# M/ o, g

" r& L) j4 i2 e6 D1 _% R. g

try { & m+ c* Z2 Q* ]8 E8 P* U //1. 从BearerTokenExtractor 获取Authentication 信息% |; l6 R2 [ i* O Authentication authentication = this

- T' Q/ e5 P' F6 _% E* L$ l

.tokenExtractor.extract(request);1 E5 \4 b# Y; m9 h* l if (authentication == null) { _$ Q: x) n- _8 \/ C" T+ b if (this.stateless && this

' A9 ]5 ]$ T5 w# h! p# e6 U: Q

.isAuthenticated()) {/ s' L1 E& H0 L( Y4 u- [/ @8 j if (debug) { # {/ b% z! I/ v$ [0 f logger.debug("Clearing security context.");0 x! q2 X- B# i: t } 8 ^' p% b. Z8 n- a / I+ t' B: U" ~: @) x. Z% T5 z }3 b% s SecurityContextHolder.clearContext();- }/ F) y. y; C- j! H }4 U x) d: B# ?/ i4 N / |. E$ l- t- A0 e0 T1 |& L6 R

+ g* ~9 |7 K" w' j9 `

if (debug) {2 X2 i5 f8 }5 V- c* P logger.debug("No token in request, will continue chain."); : x L A: z9 s } ( q0 C/ l! y/ I/ |0 B. G } else

& |8 X/ {8 B: F5 `7 N

{. u. {6 G" m+ m1 j j request.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_VALUE, authentication.getPrincipal()); - L+ |( o3 { g" A/ y) {8 C

9 D" E# L- {' x% _( b

if (authentication instanceof AbstractAuthenticationToken) { 5 F$ ?- w- Y. \( u AbstractAuthenticationToken needsDetails = (AbstractAuthenticationToken)authentication; # W8 `$ z5 Q# ]( T! U; B' O/ u1 u needsDetails.setDetails(

+ i7 X2 \. E" X2 }7 M5 j

this.authenticationDetailsSource.buildDetails(request)); 9 Y8 w/ R; q8 {! X5 D2 Y) L } 5 l' w, _3 v! |& q) t" N //2. OAuth2AuthenticationManager 进行token认证

4 \, V3 V; c% `2 _* z) R) S

3 N# p" N G9 O3 R Authentication authResult = this.authenticationManager.authenticate(authentication); . _0 t0 C! k2 u1 ~# F

! M i9 R" S& M @

if (debug) { [" Y/ N/ t' D4 C# c logger.debug("Authentication success: " + authResult); + u* B) m$ r( Z: j- d. q" R } $ P! z1 _, R$ X& d* | //3. 将认证结果放置SecurityContextHolder上下文

, w7 z( I) K8 t7 s7 V5 t r

this.eventPublisher.publishAuthenticationSuccess(authResult);% l: H3 @+ x' Q& K, c- v! D8 ?) Q SecurityContextHolder.getContext().setAuthentication(authResult);. f1 o1 R0 U$ y2 _' p } % A$ C v* U$ G; S! e8 Q }

L" |6 F; {+ S7 A; o1 i5 E5 d

catch (OAuth2Exception var9) {0 E/ M$ E' z" j" g SecurityContextHolder.clearContext();& B* ?* g2 {& a2 D- a if (debug) { ' ]9 {2 X# i$ ~ F/ ^; g logger.debug(

# L% @4 k4 W7 _" m! D) i

"Authentication request failed: " + var9); 4 r$ G5 ^' T( M& q" ?9 D } ( _9 m. F6 _8 e+ e. a* ` . m$ K9 _* v4 Z; K this.eventPublisher.publishAuthenticationFailure(

. R, i) V& E# B1 J. a$ t

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

1 m) A9 }$ Q, ?: w* v

, "N/A"));2 w& a, x! ~, K- W6 S% W- F% B this.authenticationEntryPoint.commence(request, response, new InsufficientAuthenticationException(var9.getMessage(), var9));3 |( I3 `5 {4 \: A/ B) y

2 b9 D8 Z' F Q! m0 |. ]3 D

return; 6 W5 [4 T( _& _# u$ e' B }8 m: X5 v- N! ~8 G- B8 T! j " A* W) P' b" ~9 H# S chain.doFilter(request, response); 7 X5 e2 |/ L# W# i/ f/ L7 P* \ }0 J0 t9 O5 j& |( [. [ - p1 z: W& n5 n/ b) m$ Q, j //省略....../ |" G+ v- _ D } # ]6 H, f! E3 b" J7 G8 [+ \ 2.4.3.2 BearerTokenExtractor

' N2 t3 U3 ]: ?2 Q2 y" S% G6 c' D

从请求 Header中获取tokenprotected String extractHeaderToken(HttpServletRequest request) {- y, X5 R6 S$ t Enumeration headers = request.getHeaders(

( x) z# Y( l& \% f9 i% i4 g

"Authorization"); 5 [1 J9 @0 [4 L0 M. P/ f q+ S5 W, U7 a, }" I2 F String value; ) q2 q( Y; y2 z/ `3 b& c+ v# J do { % C; p/ z' ?( \$ s1 d if (!headers.hasMoreElements()) { q+ S, ?7 A6 y- D P returnnull

! D/ h; e2 Z! W1 @ T8 g% z1 n

; 8 i8 c9 k; t$ d" _( z( ?* k } 7 g( l( _# g2 M# x* v8 U 4 J- {- f( ~! M E1 S value = (String)headers.nextElement(); , G/ P' p% ^1 ^& a" R } while(!value.toLowerCase().startsWith("Bearer"

" Y2 k) E( f8 P$ D& m1 v* H0 }

.toLowerCase()));5 j1 j" K* y; `. z9 c - U& h G4 Z+ Z: q: x' d String authHeaderValue = value.substring("Bearer".length()).trim(); - ?. |% E& |, U7 b request.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_TYPE,

/ {5 }5 U5 p4 v9 S& Q/ F! G# z

value.substring(0, "Bearer".length()).trim()); 9 r! V8 H8 Z2 O3 S int commaIndex = authHeaderValue.indexOf(44); 2 K7 D( H- ~ l# u% y

! ~$ E( t* e# p( s- j

if (commaIndex > 0) { 6 L; t0 e# @0 i: o8 H: e& k1 y authHeaderValue = authHeaderValue.substring(0, commaIndex);* @' e6 T1 @- A) [* Z( j } 3 I! S; m6 K4 ?$ _+ q5 _4 H, ~, v/ }$ ] return

7 k/ S, M3 Z7 A- k* x

authHeaderValue;* T+ ?0 C( k3 F) B% r3 Q! e7 F } ! v8 v# \" f, R O& ~4 ^7 j! Q 2.4.3.3 OAuth2AuthenticationManager资源服务认证token校验实现 程序片段:public Authentication authenticate(Authentication authentication) throws AuthenticationException { : i% {' R& i9 n) F! j8 p

: B4 Z2 s J. g8 Q; ^* Q0 r0 v

if (authentication == null) {5 Q% B# q# l3 Y% X, e thrownew InvalidTokenException("Invalid token (token not found)");' K" U' `# v9 T: o }

, |( q2 B% k! o- p; C' ?" t( i

else { 0 A4 \7 _3 K$ b String token = (String)authentication.getPrincipal(); : c! q6 |) f/ V9 z9 u! P6 X4 V //1. 从验证token存储介质获取请求传递的Access Token获取对应的验证信息

0 G$ e' ]: I: }0 C9 r

! @9 v/ N" b$ B1 X OAuth2Authentication auth = this.tokenServices.loadAuthentication(token); . P4 W+ ]9 B# I; z if (auth == null

! [& O0 N& c- ?. O- D

) { # k# J# `5 t R5 u; h/ K1 k thrownew InvalidTokenException("Invalid token: " + token); , p" I! k. u/ f# c } else {8 S! M5 A- i$ n7 C+ Z* x9 N# N //2. 验证token并加载验证信息

; P9 t* f- j; m! m- e

$ X0 X1 H3 }; Y/ z9 t- V+ _ Collection resourceIds = auth.getOAuth2Request().getResourceIds();: S: w s# Y! ?* q g8 d if (this.resourceId !=

7 |7 V2 |. j2 w p

null && resourceIds != null && !resourceIds.isEmpty() && !resourceIds.contains(this.resourceId)) { / k: m, L* d) O6 W! H

3 Z4 |6 l( b, ?

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

( w+ Q3 N5 O$ o6 r) I i

")"); 8 p1 D z" \' B. c0 q } else { % x; y* L6 }8 |3 s5 k# O this.checkClientDetails(auth); " r/ ]$ z) l7 V6 S V if (authentication.getDetails()

8 O2 j/ x! _9 ?/ x# z$ O1 @* i8 [

instanceof OAuth2AuthenticationDetails) { ) G% E6 K: C( }7 j" ~) h$ r( u9 q OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails)authentication.getDetails(); * P3 W+ Y7 G$ E( g

) `1 v/ {8 f: X o/ U/ o& P

if (!details.equals(auth.getDetails())) {( o$ s$ d+ J ]' H: `; ? details.setDecodedDetails(auth.getDetails());% p+ }% b4 H0 N) B5 H ]4 Y }! K% \3 Z# {0 ~/ _2 o2 B } , P: |% p6 N" }; C. `0 G6 \, w+ s, m! G. J# A4 I auth.setDetails(authentication.getDetails()); - u1 B( V G$ B5 @ auth.setAuthenticated(

$ j3 j" e" A; p( J

true); 4 j2 s6 L! \4 F$ `- P" B( h! G' ]+ n return auth; & F0 T$ A6 U3 M3 @ } " s, R7 s/ s4 I0 C0 j+ J' ` }" x' }2 j% L; e4 w3 W. s: ] } 7 N c' ~+ e: P9 L, T; w; B } . q9 N1 B7 H7 a) B8 S 3、OAuth2 扩展3.1 自定义异常处理3.1.1 自定义授权端点处理异常授权服务器中的错误处理使用标准的Spring MVC功能,即@ExceptionHandler端点本身中的方法。

; M! n. r8 j5 `0 w: @. k/ l

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

' m8 F* @' A: Y$ ^

@Autowiredprivate WebResponseExceptionTranslator webResponseExceptionTranslator;( U7 f8 |. F# k! u , w% e$ G% S/ K+ O+ p! ? /**2 F% Y# }4 g I. @+ `. R * 自定义授权服务配置 1 s% c4 ^& [! e- w0 C * 使用密码模式需要配置 ! z3 z0 L* U9 L/ U, m: E! q$ r */

7 _/ _) J3 j) w$ q0 A! F& ~

@Overridepublic void configure(AuthorizationServerEndpointsConfigurer endpoints) {7 P8 t8 i- q) n9 N+ Q endpoints.authenticationManager(authenticationManager) g5 k6 d$ n! N* o" ]2 |( Z1 H! x .userDetailsService(userService); D9 h9 j6 D4 N! s& y/ c Z' i .exceptionTranslator(webResponseExceptionTranslator);

$ i$ ?. k8 B0 Y7 m+ @0 b

//( r) O9 w3 U: X( f3 e 5 k& s: G, c$ p, I1 @ } ) L3 C- w( n# B) Z% D/ e //省略/**+ K5 o+ i' J5 o3 ^7 t! j; d6 H, v. R * 实现WebResponseExceptionTranslator接口,自定义授权端点异常处理 9 N3 k* Q& e" A */@ComponentpublicclassCustomOAuth2WebResponseExceptionTranslator

# | i/ a% J6 Y% u: @6 R

implementsWebResponseExceptionTranslator{ ' u5 j. K' k4 ]' I private ThrowableAnalyzer throwableAnalyzer = new DefaultThrowableAnalyzer(); # j+ e7 \5 ~- V2 E& ]) U o/ o7 H5 {# W2 L

* g! `3 a4 T3 z9 J5 t) A, f

@Overridepublic ResponseEntity translate(Exception e) throws Exception {0 T+ v a K/ O0 a6 N! j Throwable[] causeChain =

$ j: E3 Q) |0 Y+ \

this.throwableAnalyzer.determineCauseChain(e);: V- P* N) w2 z1 F9 n" ] Exception ase = (OAuth2Exception)this.throwableAnalyzer.getFirstThrowableOfType( ) |& o$ O/ ?$ I" I [ OAuth2Exception

# t8 E# r* D) y% a) j8 r

.class, causeChain);if (ase != null) { * h$ s+ C% E3 Y4 ], r9 r; ]8 f" I returnthis.handleOAuth2Exception((OAuth2Exception)ase); : I' l+ [" w4 [ }4 s' Z, C$ F) s6 O8 \, s$ | ase = (AuthenticationException)

& e8 l9 \+ Q0 f

this.throwableAnalyzer.getFirstThrowableOfType( 0 E1 a5 k6 |: }4 F; Y AuthenticationException.class, causeChain);

1 h5 E% @: Y7 w( |2 Y5 Q% X4 N: p4 Y

if (ase != null) {3 u4 H4 u, X1 [1 h& ~6 n8 f& N returnthis.handleOAuth2Exception(new UnauthorizedException(e.getMessage(), e)); 1 b* A3 U+ V! ~+ o& w }" n0 c6 W4 o. r1 h2 A8 p( ?" } ase = (AccessDeniedException)

, c) U' v0 k8 i# O9 K2 ~! E# `

this.throwableAnalyzer.getFirstThrowableOfType( * m+ E {+ H3 {% Q AccessDeniedException.class, causeChain);

: H9 J' W5 Y9 _& N8 U# h$ Y

if (ase instanceof AccessDeniedException) {: R! \1 ]1 ~0 D. v returnthis.handleOAuth2Exception(new ForbiddenException(ase.getMessage(), ase)); ( G/ h# r ~ P; g } 4 q) h- V1 K. i/ C4 J ase = (HttpRequestMethodNotSupportedException)

8 w2 F, b( o; D, u* a3 ]( y

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

9 u: \% O4 s) `' J4 a% [8 S! I3 L2 G

if(ase instanceof HttpRequestMethodNotSupportedException){ * V4 e: Z3 ]/ O- p3 b returnthis.handleOAuth2Exception(new MethodNotAllowed(ase.getMessage(), ase)); : K4 C1 I4 M! d5 ?# Q- w& Y } # F) }! c) x! c ! g9 [) ^2 Y7 q

4 F- j2 ^, v: L/ H, W

returnthis.handleOAuth2Exception(new UnsupportedResponseTypeException("服务内部错误", e));5 A4 H" x& D1 w; E } * m8 o6 v, b" w8 v5 s* n 2 c! M, n$ N+ t private

! w& S& z* i, V/ y m: q

ResponseEntity handleOAuth2Exception(OAuth2Exception e) throws IOException {0 W2 x' j% Y N* M$ V w4 H int status = e.getHttpErrorCode();; u5 `1 e$ s( q2 O8 | HttpHeaders headers = new HttpHeaders(); 1 O2 U4 ~% D, o3 h! H8 g5 N/ p headers.

! L m! N) X' j

set("Cache-Control", "no-store"); 1 o2 m7 y7 e" N3 \6 f headers.set("Pragma", "no-cache");$ G( s% m" |2 s% T if (status == HttpStatus.UNAUTHORIZED.value() || e instanceof InsufficientScopeException) { ' u1 h E* [2 J2 a* ?1 D Z8 i4 x headers.

3 J8 s Y; Y: }) c+ C& Q

set("WWW-Authenticate", String.format("%s %s", "Bearer", e.getSummary())); 0 z' x5 e, w3 X |$ V9 D- u }" k' x" C- ^/ Z5 U# m2 O CustomOauthException exception = new CustomOauthException(e.getMessage(),e); & f9 X S, K2 }* M7 k9 ~$ y1 \2 Q ResponseEntity response = new ResponseEntity(exception, headers, HttpStatus.valueOf(status)); / E% P( v8 l$ u% N) ^, R

. P4 x4 c1 I: q5 s0 x

return response;$ m1 \4 M3 Y6 ?1 p } & \' a6 F w6 V0 \5 d8 Q+ ` //省略3.1.2 自定义匿名用户访问无权限资源时的异常当访问未纳入Oauth2保护资源或者访问授权端点时客户端验证失败,抛出异常,AuthenticationEntryPoint. Commence(..)就会被调用。

: f; R: ]2 b: B9 D" C# D! J

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

2 |1 ?1 k5 X6 `1 i: e" F4 ~

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

' A3 H2 ?9 O& n7 J, Y

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

6 [7 ~6 n5 r1 {$ d8 u% O

源码分析://顶层授权认证异常处理Point package org.springframework.security.web; $ O- i! f2 {9 b# y2 M4 t% I$ w* o$ z6 Y; H! } import ...8 S0 V) Y+ x: J4 r0 A0 G 4 s7 \2 ~$ ]2 q# k4 w# t% |! v4 d publicinterfaceAuthenticationEntryPoint

% B+ _: A G' W- ]1 [# I* c9 M3 n( ?- ~

{ ! T8 N4 m# l0 S- y+ J/ g" g voidcommence(HttpServletRequest var1, HttpServletResponse var2, AuthenticationException var3)throws

5 @: j$ U1 l. u3 I/ R

IOException, ServletException; q. ?& t: }% T; p3 t# y } : i; W8 R+ [& w. b' N/ p7 b* x 当ExceptionTranslationFilter catch到异常后,就会间接调用AuthenticationEntryPoint。

. s# D, n& V4 M# c2 e5 H6 X$ y

package org.springframework.security.web.access;3 Y+ j* I: O" c- N3 D# _ & H0 ?0 f2 y- Z4 c* O" e import ... , a ?" _- z$ p: p+ z$ ` publicclassExceptionTranslationFilterextends

. `* x. v& A4 z4 o: J- Z/ G

GenericFilterBean{* q S0 x# ~% X6 Z) a //省略......public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { 5 I/ ~3 W0 c$ R- E( n HttpServletRequest request = (HttpServletRequest)req; & M3 \& \8 o" Z! b1 ~' p) ?- d9 U HttpServletResponse response = (HttpServletResponse)res;- ~1 ?+ X- q4 F0 L8 P ! v2 \2 T- Y0 [* C

$ `1 E$ i# y( n& Z. Y: j

try { ! @, \' @3 b. B7 _) _5 w chain.doFilter(request, response); 9 d; e2 {& u5 J this.logger.debug("Chain processed normally");( A9 q- y# V% o }

' N7 V* I5 ?( ?3 G" m( t1 y

catch (IOException var9) { * i3 r/ q( U6 r6 y throw var9;7 r2 p& t; o8 k3 X } catch (Exception var10) { ; }1 m4 r7 _! k* E# t# t/ Q Throwable[] causeChain =

; _& J/ \# Y+ x1 P/ O1 i& o; I

this.throwableAnalyzer.determineCauseChain(var10);4 I, u: |$ ?+ E( ^! ^5 T( | RuntimeException ase = (AuthenticationException)

* O. Z/ ~$ |8 k( K2 R8 G; q w

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

8 H4 @ w+ I: G. |( B% U- ~

null) { ) B8 j8 C* l& L ase = (AccessDeniedException)this.throwableAnalyzer.getFirstThrowableOfType(AccessDeniedException

A# ^2 \- h! `, Y+ r) H

.class, causeChain); 4 f6 z& ?. i3 Q }$ j$ m) A' y/ v) y: x* R' p* G " ^3 c' f1 S- c$ m if (ase == null) { 0 m4 X& M7 \# ?* {( F if (var10 instanceof ServletException) {2 F1 m' c9 X4 C- T$ e

1 z# ~( j& F) U9 Z! \2 A0 s b/ C* Y

throw (ServletException)var10; 8 l( D. H( }$ J2 x; {7 t3 p }8 S; m1 x; A9 Z* W- Q / C1 a+ g, J, }4 p9 n4 {7 q) ` if (var10 instanceof RuntimeException) {# r1 ^$ |+ n( j8 `

& d& i! D a ?; ~: w9 [/ I

throw (RuntimeException)var10;: ~* ]+ `" \5 }9 L }0 ?5 F9 k7 D/ D- h( e* { 0 B5 `9 i2 a& h! F3 r& {5 M& _ throw new RuntimeException(var10);- U% K' [) u4 P }+ D; a* E$ ^# |* Y8 _5 K5 B & I5 Z+ W9 f7 w. F if

" l' L- v$ u/ F$ n' m |

(response.isCommitted()) { 8 ^6 r* q$ d2 S3 S% | throw new ServletException("Unable to handle the Spring Security Exception because the response is already committed."

# ? ~# E: j9 Z c) Z, e

, var10);! n5 X+ Y) i$ g: {7 H$ m } : X) Z0 @- @- N# ^6 C6 n$ ? //异常处理,间接调用AuthenticationEntryPoint.commencethis.handleSpringSecurityException(request, response, chain, (RuntimeException)ase); - Z- u' e& n( v5 ~. s" s } - F0 S" V6 K$ [9 h4 n/ K2 K1 l1 Z' E* Y/ Y }& F: @" w8 l6 j* C9 z $ _; Z6 i; X4 x# H! y, m. }4 C8 t

& [4 M0 p# h+ s# A, {& e

//省略......private void handleSpringSecurityException(HttpServletRequest request, HttpServletResponse response, FilterChain chain, RuntimeException exception) throws IOException, ServletException {4 O% F' ~% D; Z& p8 \5 E7 r+ q7 ]

/ y( j( Z- p& Z/ U

if (exception instanceof AuthenticationException) { % w' x! f1 Q0 Y this.logger.debug("Authentication exception occurred; redirecting to authentication entry point"

+ j+ ]) q0 E7 G8 ?8 i

, exception);8 s* m+ V8 l. v, T2 } ? this.sendStartAuthentication(request, response, chain, (AuthenticationException)exception); q- _0 K& n* {1 H+ j0 t# E; E }

5 {/ I" I( E$ _

elseif (exception instanceof AccessDeniedException) { 7 r' z- S2 E# g8 ^+ E# P( Q5 _ Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); / u! ]7 W( C" _: Q5 w# l

8 V z2 @3 d# T

if (!this.authenticationTrustResolver.isAnonymous(authentication) && !this.authenticationTrustResolver.isRememberMe(authentication)) {1 x8 ^" i. D9 l, O$ @8 f! c

6 T8 V( J) N6 }' a ?( y

this.logger.debug("Access is denied (user is not anonymous); delegating to AccessDeniedHandler", exception);& p/ s8 J/ m. x* E3 ]

6 P% @) {# V! I- k2 J( |8 ^

this.accessDeniedHandler.handle(request, response, (AccessDeniedException)exception); 2 u9 G$ _& ^ q- r3 D9 ? } else { " L! R2 W. J2 \" j

" Q' @$ m$ R9 r+ M5 x

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

f( @2 S: y9 p. [& W. C

"anonymous" : "not fully authenticated") + "); redirecting to authentication entry point", exception); . j) \1 Q; p! W+ r t3 ]

$ i% B: l! P& T3 W$ J. u+ y

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

8 R$ P2 Z4 m! C' v) V

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

8 u9 D/ s0 h( {- v4 t+ ? o

)));- y. R+ j+ e2 F& l# r } , {! Y( [0 ^; w0 E( M* s }( n+ n6 I; ^1 w 7 G: F _2 P% v7 O' l } ' B2 O6 H: j9 u* G, ~2 C4 W4 a$ P* Z5 U% y ////异常处理,间接调用AuthenticationEntryPoint.commenceprotected void sendStartAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, AuthenticationException reason) throws ServletException, IOException { 4 S. H$ N/ }3 m H3 [3 a; Q SecurityContextHolder.getContext().setAuthentication((Authentication)

& u& j! b8 |4 ~- J4 R+ m

null);% h+ V" U x- t2 ?4 x this.requestCache.saveRequest(request, response);% z% G' J: ?2 s; F+ K this.logger.debug("Calling Authentication entry point."

% w9 {2 Y5 w1 }+ r: K

); " d8 n+ g( O0 D2 b this.authenticationEntryPoint.commence(request, response, reason);) x1 Q: c- d/ V$ V: [ }2 E4 ?. R V1 z9 h1 o# m, U" w+ } # k! v: z) {/ A$ ~ //省略......//默认的异常处理,会将异常呈现给默认的Login视图

$ r% G- u9 J! m1 g: y+ N

package org.springframework.security.web.authentication;) _2 k* Y. s) R r" R$ Y0 j6 _ 3 d0 ?( S0 w& r& j1 T import ...& |, n# ]2 J/ I$ e 4 T, \/ T8 H \: g7 X" ^ publicclassLoginUrlAuthenticationEntryPoint

1 L) g1 ]* z3 E& q7 |

implementsAuthenticationEntryPoint, InitializingBean {//省略...public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {3 c: W; ^% a* P1 d* f' `# Y String redirectUrl =

9 H, t' l% U2 x6 s9 j2 R

null; / R2 k; Q% F3 ^: f, a U$ _ if (this.useForward) { 4 D" X# o5 \3 Q if (this.forceHttps && "http".equals(request.getScheme())) {5 N# ~" y+ A/ h# q. c' q% @3 p redirectUrl =

r- y& @! a. B% i; o- @" d

this.buildHttpsRedirectUrlForRequest(request);. d4 J6 V% p, I- [$ W0 [4 J3 l6 l }3 l. q+ j) B6 C+ E+ y) }# t 9 F1 f5 f( g0 {" W8 y$ P q if (redirectUrl == null) { ! L" i: b, ~ q$ B4 F+ Z( B' R7 c String loginForm =

1 v: h, e. c7 X% P5 |2 b

this.determineUrlToUseForThisRequest(request, response, authException); j1 l R) x* V w% ~3 }) F1 | if (logger.isDebugEnabled()) {/ V( a. q2 B; J9 g logger.debug(

3 M0 n- l- _" ~/ b) a e

"Server side forward to: " + loginForm); 3 U) Q& T1 E% V' w" {- t& }7 P) _9 C }1 h. q5 Q$ |3 O2 J! C! _ 2 g R5 n5 L( y" Y t+ |& T4 F1 ^ RequestDispatcher dispatcher = request.getRequestDispatcher(loginForm);7 `9 p- {! z4 t4 Y8 S dispatcher.forward(request, response); 0 g) n) d0 X2 K: y! h

' N" e3 A$ ~* P+ m9 F

return;$ q0 x" s' f K% [% j }& o6 R( e; J+ c8 b6 z" U& r+ ]# D$ e } else { : ?; T, o* M/ z; C! B redirectUrl = this.buildRedirectUrlToLoginPage(request, response, authException); ( u; b. U) J8 I7 |3 m } 5 U! B+ S8 X& Y" X7 q ; Y2 j1 w$ {7 k+ S

7 X+ u3 W: S( L7 n5 [/ y

this.redirectStrategy.sendRedirect(request, response, redirectUrl);" Q) E0 \6 z8 L Z, V" I& C$ Q } $ f1 D7 O2 m0 |3 O1 h: x T; U1 Z8 e9 O9 a+ g* M z' N( ^9 | //省略默认的视图呈现异常肯定不符合我们实际的应用,因此需要对此类异常进行自定义处理。

3 R- J% ~% d p$ `* f% V0 J: w

package com.easy.mall.exception;6 r* u3 g: e; x& @+ l2 m% C; B( N" v; D 5 i6 t9 s" E& |+ Q3 m3 d6 @7 j import ...# ^, Y+ D: V1 z0 @ / Q/ s! V# g1 v+ Q0 Z @Component@AllArgsConstructorpublicclassCustomAuthExceptionEntryPoint

- S; ^- y$ [0 a/ G3 A

implementsAuthenticationEntryPoint{ * v7 S- {/ y- n& ~! d) y1 ? 2 x( l( G V" D2 b" X$ F @Overridepublicvoidcommence(HttpServletRequest httpServletRequest, $ U, u1 c/ ~& O9 V HttpServletResponse response, AuthenticationException e)

3 X* J% P+ ~( [# f0 r% u) m* v# l

throws IOException, ServletException { 6 T! Z: R- s% _7 |' q0 H response.setCharacterEncoding(StandardCharsets.UTF_8.name()); " w$ W% F e8 H4 S$ J response.setContentType(MediaType.APPLICATION_JSON_VALUE);/ b& |0 d+ L( r) y CommonResult result = CommonResult.failed();5 T: z" _* Y2 O( l5 _* \ result.setCode(HttpStatus.HTTP_UNAUTHORIZED);( L. b4 S x% D( W3 Q% a

% X% [2 E& k8 i8 M1 }

if (e != null) {+ F, i2 |( A, C3 q result.setMessage("unauthorized"); & q/ A0 k9 }- X: b result.setData(e.getMessage()); 6 o% @) a5 ?! |" K3 U } 8 y8 U7 u- B' m1 N$ H8 F response.setStatus(HttpStatus.HTTP_UNAUTHORIZED); " T8 G# P6 X+ X PrintWriter printWriter = response.getWriter();7 ?+ n4 @& {, Y7 T# Y: V printWriter.append(JSONObject.toJSONString(result));3 d; e" q( l4 U4 O }. O) P3 @: ^, C5 P! q! ` } , J; G( a7 M: y' O- X4 z$ E" C1 P

4 k% [# Q! @( t: R2 F+ Z& d; {& T, t

@Configuration@EnableWebSecuritypublicclassSecurityConfigextendsWebSecurityConfigurerAdapter{ . l" }- ~8 N9 T0 Y) r* X5 t$ x: i3 f+ D2 [3 o @Bean

- v$ B1 H/ G6 ~1 X

public PasswordEncoder passwordEncoder(){( x% @% q6 M& }4 T, m: a) N) E' A+ f4 z+ b7 F returnnew BCryptPasswordEncoder();$ f( j1 y0 W. U0 Y) V }& c* c5 r$ q5 z" f U9 `( R& Q6 |; X 1 _# F6 F" {. p& m" e! p @Bean@Override

1 f/ K* p) u, V1 A; X

public AuthenticationManager authenticationManagerBean()throws Exception { . U3 M! m, y( D* ^5 i# y2 I returnsuper.authenticationManagerBean();( ?+ Z5 N( h0 P- F+ A }8 [" R- Y1 P4 t/ E9 t+ o 1 v' `# f) n4 [$ y

% Q; p* }& i" O7 s C l9 a

@Overridepublicvoidconfigure(HttpSecurity http)throws Exception { ' Q/ W0 b/ t+ E" D* @ http.csrf() ; K& }* V- `, e4 x/ @: ]( U3 \2 G- p .disable()( O, ]( ]) e! t2 Y" {( y .authorizeRequests()+ C1 ]6 C- |3 g/ m7 G+ R .antMatchers(

: Q! `( a0 L* j+ f

"/oauth/**", "/login/**", "/logout/**") * V3 ~1 a9 U" c7 p' p. ]. G .permitAll()) b& t0 s) N& `/ y1 U# P9 [4 l .anyRequest()8 m) D, L: |; e- R* }2 {3 `$ p .authenticated()1 w7 F( K8 j7 p .and()$ X; t& s$ N0 v V' w .formLogin()6 m4 \3 X: E- ?2 h .permitAll(); . B3 a) x2 j2 ^* G5 i

0 K1 ]/ L, s1 O

//web 安全控制添加注册自定义的错误处理 6 M% b! i- B3 U* | http.exceptionHandling().authenticationEntryPoint(new CustomAuthExceptionEntryPoint()); : H' p/ f# J* C6 i' v } ' n2 j6 u$ u5 C1 O }# i! [3 v2 G* L o3 `

+ W* W3 C7 L3 J6 Q/ u9 M9 @

自定义异常处理后的效果

: T) ~8 y+ b" t! X# w0 m

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

F) _! y1 [( V' J) C9 T- y; `

原生的异常信息响应:{0 c; X& J. Z; [/ _1 u "error": "invalid_token", ! @" y% x# `. E K2 C8 S "error_description": "Invalid access token: 1" + d( Q1 B" g+ a5 o0 Q }) |2 Q, f1 A7 `# j1 l 自定义异常@Configuration

" u7 ?! E3 P" Q; Z ^$ T

@EnableResourceServer$ q G' h( M5 U public class Oauth2SourceConfig extends ResourceServerConfigurerAdapter {# z0 }- i: x; [ ) t. W. {" P2 U7 ]! X* b @Override

' l9 c5 Z* m) |( ?- R# V

, P( c' l6 h/ J" j) E% ]- \2 ^ public void configure(HttpSecurity http) throws Exception { ?( X/ _8 s# s' m1 K1 }7 K; f http.authorizeRequests() # H; M) S8 s8 R( Y- v3 N9 l( r .anyRequest

4 u! C- D# p" D6 D

() 0 `) k; K$ J. h) E' Z# w .authenticated()1 Y3 _7 P, `' q: h9 K .and() / i: m2 ^. _: y2 e Z0 S .requestMatchers() f: q0 u: M, \ .antMatchers("/user/**"

" V% i: T! t; O" K4 c; V

);//配置需要保护的资源路径- Z) n% o6 B% t* q9 W }" c+ [' Z# d- F# A$ ~! p( i . i a$ N0 c* ?- `: t" H6 b5 C) O @Overridepublicvoidconfigure(ResourceServerSecurityConfigurer resources) throws

7 U+ ]" R% h( a& E' F% J7 T; [9 t! P+ ?4 _

Exception {' |7 K& x6 o& P9 U2 x resources.authenticationEntryPoint(new CustomAuthExceptionEntryPoint());//自定义受令牌保护资源服务异常处理

4 x$ i) u4 h1 q( Z9 g. o# l

3 W1 W. F; y. z0 }$ W; b @ }( S# \* B& N! r; w/ F" N) [* ~0 [ }5 C7 X+ _2 T& d4 h1 x$ N 自定义异常处理效果 {; R2 R2 l* T7 e% c "code": 401, " B( t% g7 |$ _& y- }7 S+ y9 a7 A "data": "Invalid access token: 1",/ J5 s6 A7 @9 G5 s7 N6 y "message": "unauthorized"

$ p/ V- L! T* D3 B) Z

! r8 r- t6 L0 G; P2 L3 c' { } : @$ \( B. _+ L M$ O1 V& W4 b8 L 3.1.4 自定义受OAuth2令牌保护的资源无权限访问异常//待定3.1.5 Security自定义异常分析总结根据上述一系列源码分析,我们知道Security是通过一系列Filter过滤链实现授权认证,不同情况和场景其过滤链不一样,因此当出现异常也通常由不同的异常处理器进行处理,因此需要针对不同情况进行自定义处理。

) }5 K3 w0 m; e) N1 ^6 H

附录构造Basic Auth认证头/**( q. B- m+ W& i5 o& Q- | * 构造Basic Auth认证头信息 # I, @0 g& x# G* K1 U7 v *( t8 k+ C' d* u * @return7 n1 p; ]* X6 l! J4 \1 G; Y */privateString getHeader() { . @% A+ t& L+ ~+ C: v. i! A: R8 c2 W String

6 S% P& S5 g- f$ c9 |

auth = APP_KEY + ":" + SECRET_KEY; 7 E7 s3 N4 M2 J& t4 ] byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName(

( C* L8 R" ?: H; V

"US-ASCII"))); S+ L4 t( f, M' x$ Y* L8 a ] String authHeader = "Basic " + newString(encodedAuth); . E3 T( M0 \- j' ?2 B return authHeader; o/ L0 A9 K. ^9 Y& t }

" G! R( c9 L: n6 ~4 k- \' h/ M! P* J: H5 i' I 7 J& D9 R/ P6 E X( M! @ 9 t$ u) ?6 o: p9 ` # j, v0 @% V) {0 g; `9 M
回复

使用道具 举报

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

    本版积分规则

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

    GMT+8, 2026-4-4 19:20 , Processed in 0.060146 second(s), 23 queries , Gzip On.

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

    Powered by Discuz! X3.5

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