日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

使用Spring Security保护REST服务

發布時間:2023/12/3 javascript 24 豆豆
生活随笔 收集整理的這篇文章主要介紹了 使用Spring Security保护REST服务 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

總覽

最近,我正在一個使用REST服務層與客戶端應用程序(GWT應用程序)進行通信的項目中。 因此,我花了很多時間來弄清楚如何使用Spring Security保護REST服務。 本文介紹了我找到的解決方案,并已實現。 我希望此解決方案將對某人有所幫助,并節省大量寶貴的時間。

解決方案

在普通的Web應用程序中,每當訪問安全資源時,Spring Security都會檢查當前用戶的安全上下文,并決定將其轉發到登錄頁面(如果用戶未通過身份驗證),或將其轉發到未經授權的資源。頁面(如果他沒有所需的權限)。

在我們的場景中,這是不同的,因為我們沒有要轉發的頁面,我們需要調整和覆蓋Spring Security以僅使用HTTP協議狀態進行通信,下面我列出了使Spring Security發揮最大作用的工作:

  • 身份驗證將通過普通形式的登錄名進行管理,唯一的區別是響應將以JSON以及HTTP狀態(可通過代碼200(如果通過驗證)或代碼401(如果身份驗證失敗))進行;
  • 重寫AuthenticationFailureHandler以返回代碼401 UNAUTHORIZED;
  • 重寫AuthenticationSuccessHandler以返回代碼20 OK,HTTP響應的主體包含當前已認證用戶的JSON數據;
  • 重寫AuthenticationEntryPoint以始終返回代碼401 UNAUTHORIZED。 這將覆蓋Spring Security的默認行為,該行為是在用戶不符合安全要求的情況下將用戶轉發到登錄頁面,因為在REST上我們沒有任何登錄頁面;
  • 覆蓋LogoutSuccessHandler以返回代碼20 OK;

就像由Spring Security保護的普通Web應用程序一樣,在訪問受保護的服務之前,必須首先通過向登錄URL提交密碼和用戶名來進行身份驗證。

注意:以下解決方案要求Spring Security的最低版本為3.2。

覆蓋AuthenticationEntryPoint

該類擴展了org.springframework.security.web.AuthenticationEntryPoint,并且僅實現了一種方法,該方法會在未經授權的情況下發送響應錯誤(帶有401狀態代碼)。

@Component public class HttpAuthenticationEntryPoint implements AuthenticationEntryPoint {@Overridepublic void commence(HttpServletRequest request, HttpServletResponse response,AuthenticationException authException) throws IOException {response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authException.getMessage());} }

重寫AuthenticationSuccessHandler

AuthenticationSuccessHandler負責成功認證后的操作,默認情況下它將重定向到URL,但在我們的情況下,我們希望它發送帶有數據的HTTP響應。

@Component public class AuthSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {private static final Logger LOGGER = LoggerFactory.getLogger(AuthSuccessHandler.class);private final ObjectMapper mapper;@AutowiredAuthSuccessHandler(MappingJackson2HttpMessageConverter messageConverter) {this.mapper = messageConverter.getObjectMapper();}@Overridepublic void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,Authentication authentication) throws IOException, ServletException {response.setStatus(HttpServletResponse.SC_OK);NuvolaUserDetails userDetails = (NuvolaUserDetails) authentication.getPrincipal();User user = userDetails.getUser();userDetails.setUser(user);LOGGER.info(userDetails.getUsername() + " got is connected ");PrintWriter writer = response.getWriter();mapper.writeValue(writer, user);writer.flush();} }

重寫AuthenticationFailureHandler

AuthenticationFaillureHandler負責身份驗證失敗后的處理方法,默認情況下它將重定向到登錄頁面URL,但是在我們的情況下,我們只希望它發送帶有401 UNAUTHORIZED代碼的HTTP響應。

@Component public class AuthFailureHandler extends SimpleUrlAuthenticationFailureHandler {@Overridepublic void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,AuthenticationException exception) throws IOException, ServletException {response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);PrintWriter writer = response.getWriter();writer.write(exception.getMessage());writer.flush();} }

覆蓋LogoutSuccessHandler

LogoutSuccessHandler決定用戶成功注銷后的操作,默認情況下它將重定向到登錄頁面URL,因為我們沒有重寫它以返回帶有20 OK代碼的HTTP響應。

@Component public class HttpLogoutSuccessHandler implements LogoutSuccessHandler {@Overridepublic void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)throws IOException {response.setStatus(HttpServletResponse.SC_OK);response.getWriter().flush();} }

Spring安全配置

這是最后一步,將所有工作放在一起,我更喜歡使用新的方式來配置Spring Security,它使用Java而不是XML,但是您可以輕松地將此配置適應XML。

@Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter {private static final String LOGIN_PATH = ApiPaths.ROOT + ApiPaths.User.ROOT + ApiPaths.User.LOGIN;@Autowiredprivate NuvolaUserDetailsService userDetailsService;@Autowiredprivate HttpAuthenticationEntryPoint authenticationEntryPoint;@Autowiredprivate AuthSuccessHandler authSuccessHandler;@Autowiredprivate AuthFailureHandler authFailureHandler;@Autowiredprivate HttpLogoutSuccessHandler logoutSuccessHandler;@Bean@Overridepublic AuthenticationManager authenticationManagerBean() throws Exception {return super.authenticationManagerBean();}@Bean@Overridepublic UserDetailsService userDetailsServiceBean() throws Exception {return super.userDetailsServiceBean();}@Beanpublic AuthenticationProvider authenticationProvider() {DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();authenticationProvider.setUserDetailsService(userDetailsService);authenticationProvider.setPasswordEncoder(new ShaPasswordEncoder());return authenticationProvider;}@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {auth.authenticationProvider(authenticationProvider());}@Overrideprotected AuthenticationManager authenticationManager() throws Exception {return super.authenticationManager();}@Overrideprotected void configure(HttpSecurity http) throws Exception {http.csrf().disable().authenticationProvider(authenticationProvider()).exceptionHandling().authenticationEntryPoint(authenticationEntryPoint).and().formLogin().permitAll().loginProcessingUrl(LOGIN_PATH).usernameParameter(USERNAME).passwordParameter(PASSWORD).successHandler(authSuccessHandler).failureHandler(authFailureHandler).and().logout().permitAll().logoutRequestMatcher(new AntPathRequestMatcher(LOGIN_PATH, "DELETE")).logoutSuccessHandler(logoutSuccessHandler).and().sessionManagement().maximumSessions(1);http.authorizeRequests().anyRequest().authenticated();} }

這是總體配置的一個潛行高峰,我在本文中附加了一個Github存儲庫,其中包含示例項目https://github.com/imrabti/gwtp-spring-security 。

我希望這可以幫助一些努力尋找解決方案的開發人員,請隨時提出任何問題,或發布任何可以使該解決方案更好的增強功能。

翻譯自: https://www.javacodegeeks.com/2014/09/secure-rest-services-using-spring-security.html

總結

以上是生活随笔為你收集整理的使用Spring Security保护REST服务的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。