您好,登錄后才能下訂單哦!
這篇文章將為大家詳細(xì)講解有關(guān)springsecurity如何使用application/json接收數(shù)據(jù),小編覺得挺實(shí)用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。
spring security 使用 application/json 接收數(shù)據(jù)
不了解 security 的請看 security 的簡單使用
https://blog.51cto.com/5013162/2404946
在使用 spring security 登錄用戶的時候 發(fā)現(xiàn)使用 application/josn 后臺不能獲取到數(shù)據(jù)
看 UsernamePasswordAuthenticationFilter 源碼發(fā)現(xiàn)
//獲取密碼 protected String obtainPassword(HttpServletRequest request) { return request.getParameter(passwordParameter); } //獲取用戶名 protected String obtainUsername(HttpServletRequest request) { return request.getParameter(usernameParameter); }
是直接從request 獲取的 不是從 requestBody 中獲取的
那我們就只需要重寫這兩個方法從 requestBody 中獲取參數(shù)
重寫 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參數(shù) body中的參數(shù)只能獲取一次 * @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 { //自定義用戶驗(yàn)證和加密方式 auth.userDetailsService(userDetailService).passwordEncoder(new BCryptPasswordEncoder()); } @Override protected void configure(HttpSecurity http) throws Exception { http.formLogin() // 定義當(dāng)需要用戶登錄時候,轉(zhuǎn)到的登錄頁面。 // .loginPage("/login.html") //自定義登錄頁面 // .loginProcessingUrl("/login") //自定義登錄接口地址 // .successHandler(loginSuccessHandler) .and() // 定義哪些URL需要被保護(hù)、哪些不需要被保護(hù) .authorizeRequests().antMatchers("/login").permitAll() //不需要保護(hù)的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()); } }
用戶校驗(yàn)處理類
@Component public class UserDetailServiceImpl implements UserDetailsService { /** * 用戶校驗(yàn) * @param s * @return * @throws UsernameNotFoundException */ @Override public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException { Collection<GrantedAuthority> collection = new ArrayList<>();//權(quán)限集合 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
都可以獲取到傳入的參數(shù)
關(guān)于“springsecurity如何使用application/json接收數(shù)據(jù)”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,使各位可以學(xué)到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。