我是 spring boot 的新手,我想为我的后端创建一个 rest api,但我也喜欢 spring security 的身份验证系统,我想在我的应用程序中使用它,而不必为这部分代码制作我自己的 restful api。
这是否可行,这样做会更好,而不是将所有内容都作为 rest api?
是的,这是非常可行的。步骤:
-
您必须将 Spring 安全会话管理配置为无状态
@Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable().exceptionHandling().authenticationEntryPoint(authenticationEntryPoint()).and() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().authorizeRequests()
}
-
将身份验证入口点配置为返回 HTTP 状态而不是视图
@Bean public AuthenticationEntryPoint authenticationEntryPoint() { return new AuthenticationEntryPoint() { @Override public void commence(HttpServletRequest resq, HttpServletResponse resp, AuthenticationException arg2) throws IOException, ServletException { resp.sendError(HttpStatus.UNAUTHORIZED.value(), "Secured URL Hit"); } }; }
-
继续使用常用的身份验证提供程序