Koril
V2EX  ›  问与答

在 Spring Security 中登陆注册等接口放在过滤器(Filter)还是控制器(Controller)中?

  •  
  •   Koril · Oct 17, 2024 · 6907 views
    This topic created in 766 days ago, the information mentioned may be changed or developed.

    之前一些老项目都是放在 AuthController ,jwt 的校验放在 JwtAuthFilter 里。

    但是我看了下 spring security 官网架构介绍,以及看了下 UsernamePasswordAuthenticationFilter 类,

    我感觉是不是所有跟认证授权相关的东西全部放 Filter 就好了? controller 只负责一些业务逻辑的接口,跟认证授权完全无关。

    比如现在,我移除掉 controller 的那些 /login ,/register, /refreshToken 之类的接口,然后再增加 LoginFilter/RegisterFilter 等过滤器,塞到 JwtAuthFilter 后面,这样做符合规范吗,最佳实践是什么?

    我目前试了下,两种模式都能走通正常的登录认证流程,但是我不太喜欢多种方式的实现,就像 import this 里面说的:There should be one-- and preferably only one --obvious way to do it.

    2 replies  •  2024-10-25 17:56:00 +08:00
    flmn
    flmn
    Oct 22, 2024
    1
    Spring Security 把登录放到 Filter 里,是为了它自身的统一,或者说是权宜之计,如果你用它自身的登录,比如 Basic ,可以直接用。
    但是如果你自己做的认证,Filter 只用来鉴权,那么大胆的放 Controller 里面吧,最符合直觉。我就是这样干的。
    所以说不要用 Spring Security 的错误来惩罚自己,怀疑自己。
    Koril
    Koril
    OP
    Oct 25, 2024
    2
    @flmn 好的,谢谢你的建议
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   3540 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 33ms · UTC 04:08 · PVG 12:08 · LAX 20:08 · JFK 23:08
    ♥ Do have faith in what you're doing.