您好,登錄后才能下訂單哦!
這篇文章將為大家詳細講解有關springsecurity如何使用application/json接收數據,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。
spring security 使用 application/json 接收數據
不了解 security 的請看 security 的簡單使用
https://blog.51cto.com/5013162/2404946
在使用 spring security 登錄用戶的時候 發現使用 application/josn 后臺不能獲取到數據
看 UsernamePasswordAuthenticationFilter 源碼發現
//獲取密碼 protected String obtainPassword(HttpServletRequest request) { return request.getParameter(passwordParameter); } //獲取用戶名 protected String obtainUsername(HttpServletRequest request) { return request.getParameter(usernameParameter); }
是直接從request 獲取的 不是從 requestBody 中獲取的
那我們就只需要重寫這兩個方法從 requestBody 中獲取參數
重寫 UsernamePasswordAuthenticationFilter 類
public class UserAuthenticationFilter extends UsernamePasswordAuthenticationFilter { private ThreadLocal<Map<String,String>> threadLocal = new ThreadLocal<>(); @Override protected String obtainPassword(HttpServletRequest request) { String password = this.getBodyParams(request).get(super.SPRING_SECURITY_FORM_PASSWORD_KEY); if(!StringUtils.isEmpty(password)){ return password; } return super.obtainPassword(request); } @Override protected String obtainUsername(HttpServletRequest request) { String username = this.getBodyParams(request).get(super.SPRING_SECURITY_FORM_USERNAME_KEY); if(!StringUtils.isEmpty(username)){ return username; } return super.obtainUsername(request); } /** * 獲取body參數 body中的參數只能獲取一次 * @param request * @return */ private Map<String,String> getBodyParams(HttpServletRequest request){ Map<String,String> bodyParams = threadLocal.get(); if(bodyParams==null) { ObjectMapper objectMapper = new ObjectMapper(); try (InputStream is = request.getInputStream()) { bodyParams = objectMapper.readValue(is, Map.class); } catch (IOException e) { } if(bodyParams==null) bodyParams = new HashMap<>(); threadLocal.set(bodyParams); } return bodyParams; } } 自定義 SecurityConfig 類 @Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired UserDetailServiceImpl userDetailService; @Autowired LoginSuccessHandler loginSuccessHandler; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { //自定義用戶驗證和加密方式 auth.userDetailsService(userDetailService).passwordEncoder(new BCryptPasswordEncoder()); } @Override protected void configure(HttpSecurity http) throws Exception { http.formLogin() // 定義當需要用戶登錄時候,轉到的登錄頁面。 // .loginPage("/login.html") //自定義登錄頁面 // .loginProcessingUrl("/login") //自定義登錄接口地址 // .successHandler(loginSuccessHandler) .and() // 定義哪些URL需要被保護、哪些不需要被保護 .authorizeRequests().antMatchers("/login").permitAll() //不需要保護的URL .anyRequest() // 任何請求,登錄后可以訪問 .authenticated() .and() .logout().logoutSuccessUrl("/login").permitAll() // 登出 .and() .csrf().disable(); //配置自定義過濾器 增加post json 支持 http.addFilterAt(UserAuthenticationFilterBean(), UsernamePasswordAuthenticationFilter.class); } private UserAuthenticationFilter UserAuthenticationFilterBean() throws Exception { UserAuthenticationFilter userAuthenticationFilter = new UserAuthenticationFilter(); userAuthenticationFilter.setAuthenticationManager(super.authenticationManager()); userAuthenticationFilter.setAuthenticationSuccessHandler(loginSuccessHandler); return userAuthenticationFilter; } }
登錄成功處理類
LoginSuccessHandler.class
@Component public class LoginSuccessHandler implements AuthenticationSuccessHandler { @Override public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException { httpServletResponse.setContentType("application/json;charset=UTF-8"); httpServletResponse.getWriter().write(authentication.getName()); } }
用戶校驗處理類
@Component public class UserDetailServiceImpl implements UserDetailsService { /** * 用戶校驗 * @param s * @return * @throws UsernameNotFoundException */ @Override public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException { Collection<GrantedAuthority> collection = new ArrayList<>();//權限集合 String password = new BCryptPasswordEncoder().encode("123456"); User user = new User(s,password,collection); return user; } }
改造完成 支持 post application/json 同時也支持 post form-data/x-www-form-urlencoded
都可以獲取到傳入的參數
關于“springsecurity如何使用application/json接收數據”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,使各位可以學到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。