After taking a break, I resumed working on SpringBoot.
Previously, I successfully established connections between the OAuth2.0 Authorization server, Resource server, and the client, which left me feeling quite content.
Today’s goal involves testing the functionality of ‘hasAuthority()’ in controlling API access. I’ve configured ‘hasAuthority(“Scope_api.read”)’, where ‘scope’ is specific to the client. This setting ensures that only clients with the ‘api.read’ scope can access the API; otherwise, a 404 Forbidden error occurs. The ‘SCOPE_’ prefix is automatically added by the system and doesn’t require your attention.
I then proceeded to investigate whether Role-based Access Control could be implemented on the Resource Server. I applied ‘@PreAuthorize(“hasAuthority(‘ROLE_PTE_STUDENT’)”)’ to some APIs within the ‘@RestController’. This setup aims to restrict access to users possessing the ‘ROLE_PTE_STUDENT’ privilege or role. Clients can still directly visit these APIs irrespective of the user’s role.
However, I encountered an issue—it seems that Method Security isn’t activated yet.
After adding “@EnableMethodSecurity” at the beginning of WebSecurityConfig on the Authorization Server and reattempting, I encountered a 404 Forbidden error. This outcome indicates that “@PreAuthorize” is indeed functioning as intended.
The 404 error occurred because, upon decoding the JWT Token on the Resource Server, the ‘GrantedAuthorities’ solely contained ‘SCOPE’ for clients. To utilize Role-based Access Control, we need to manually add Roles and Privileges, a process managed by Token Customizer and related to Token customization. The necessary step involves creating a Token Decoder on the Resource Server, converting Roles and Privileges to ‘GrantedAuthorities’. This transformation enables the implementation of Role-based Access Control.
I printed the JWT Token and was elated that the previous step was successful! However, I discovered that the SCOPE prefix was missing. Therefore, I rewrote the JWT Decoder on the Resource Server, including the SCOPE prefix.
Voilà! Everything is now functioning perfectly!
今天又开始弄SpringBoot了。
之前把OAuth认证服务器,资源服务器,和客户端成功联通起来,让我很开心。
我今天测试资源服务器,hasAuthority()控制API开发权限。我目前的设置是hasAuthority(“SCOPE_api.read”),scope是给客户端的,表示有api.read的客户端才可以访问这个API,不然会有404Forbidden错误。SCOPE_前缀不用管,系统会自己加。
我然后就想试下Role-based access control在资源服务器上是否可以用,我在RestController设置了一些API,在上面加上@PreAuthorize(“hasAuthority(‘ROLE_PTE_STUDENT’)”),表示只有ROLE_PTE_STUDENT权限的用户才可以访问这个API,结果不行。客户端可以直接访问,不管用户有没有这个角色。
这是因为Method Security还没有启动。
我在WebSecurityConfig这个配置文件上加上了@EnableMethodSecurity方法,再试下,我就得到404Forbidden错误。挺好,这说明@PreAuthorize起作用了。
但为什么会有404错误呢?因为JWT Token在资源服务器解码的时候,GrantedAuthorities里只有客户端的SCOPE,要自己在认证服务器JWT Token Encode的时候把Role和Privilege加进去,这属于Token自定义(Token customizer)。在资源服务要创建一个Token decoder,把JWT Token里面的Role和Privilege转换为GrantedAuthorities,这样Role-based Access Control就能用了。
我把JWT token打印出来,看到上步做成功了,很高兴!不过我发现客户端的SCOPE没有加进去,因为我重写了资源服务器的JWT decoder,需要自己把scope加进去。
我现在就来做这个工作!