這期內(nèi)容當(dāng)中小編將會(huì)給大家?guī)?lái)有關(guān)使用Spring Security怎么JSON進(jìn)行配置并登錄,文章內(nèi)容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
創(chuàng)新互聯(lián)公司主營(yíng)易門網(wǎng)站建設(shè)的網(wǎng)絡(luò)公司,主營(yíng)網(wǎng)站建設(shè)方案,成都app軟件開發(fā),易門h5微信小程序定制開發(fā)搭建,易門網(wǎng)站營(yíng)銷推廣歡迎易門等地區(qū)企業(yè)咨詢
準(zhǔn)備工作
基本的spring security配置就不說(shuō)了,網(wǎng)上一堆例子,只要弄到普通的表單登錄和自定義UserDetailsService就可以。因?yàn)樾枰貙慒ilter,所以需要對(duì)spring security的工作流程有一定的了解,這里簡(jiǎn)單說(shuō)一下spring security的原理。
spring security 是基于javax.servlet.Filter的,因此才能在spring mvc(DispatcherServlet基于Servlet)前起作用。
UsernamePasswordAuthenticationFilter:實(shí)現(xiàn)Filter接口,負(fù)責(zé)攔截登錄處理的url,帳號(hào)和密碼會(huì)在這里獲取,然后封裝成Authentication交給AuthenticationManager進(jìn)行認(rèn)證工作
Authentication:貫穿整個(gè)認(rèn)證過(guò)程,封裝了認(rèn)證的用戶名,密碼和權(quán)限角色等信息,接口有一個(gè)boolean isAuthenticated()方法來(lái)決定該Authentication認(rèn)證成功沒;
AuthenticationManager:認(rèn)證管理器,但本身并不做認(rèn)證工作,只是做個(gè)管理者的角色。例如默認(rèn)實(shí)現(xiàn)ProviderManager會(huì)持有一個(gè)AuthenticationProvider數(shù)組,把認(rèn)證工作交給這些AuthenticationProvider,直到有一個(gè)AuthenticationProvider完成了認(rèn)證工作。
AuthenticationProvider:認(rèn)證提供者,默認(rèn)實(shí)現(xiàn),也是最常使用的是DaoAuthenticationProvider。我們?cè)谂渲脮r(shí)一般重寫一個(gè)UserDetailsService來(lái)從數(shù)據(jù)庫(kù)獲取正確的用戶名密碼,其實(shí)就是配置了DaoAuthenticationProvider的UserDetailsService屬性,DaoAuthenticationProvider會(huì)做帳號(hào)和密碼的比對(duì),如果正常就返回給AuthenticationManager一個(gè)驗(yàn)證成功的Authentication
看UsernamePasswordAuthenticationFilter源碼里的obtainUsername和obtainPassword方法只是簡(jiǎn)單地調(diào)用request.getParameter方法,因此如果用json發(fā)送用戶名和密碼會(huì)導(dǎo)致DaoAuthenticationProvider檢查密碼時(shí)為空,拋出BadCredentialsException。
/** * Enables subclasses to override the composition of the password, such as by * including additional values and a separator. * <p> * This might be used for example if a postcode/zipcode was required in addition to * the password. A delimiter such as a pipe (|) should be used to separate the * password and extended value(s). The <code>AuthenticationDao</code> will need to * generate the expected password in a corresponding manner. * </p> * * @param request so that request attributes can be retrieved * * @return the password that will be presented in the <code>Authentication</code> * request token to the <code>AuthenticationManager</code> */ protected String obtainPassword(HttpServletRequest request) { return request.getParameter(passwordParameter); } /** * Enables subclasses to override the composition of the username, such as by * including additional values and a separator. * * @param request so that request attributes can be retrieved * * @return the username that will be presented in the <code>Authentication</code> * request token to the <code>AuthenticationManager</code> */ protected String obtainUsername(HttpServletRequest request) { return request.getParameter(usernameParameter); }
重寫UsernamePasswordAnthenticationFilter
上面UsernamePasswordAnthenticationFilter的obtainUsername和obtainPassword方法的注釋已經(jīng)說(shuō)了,可以讓子類來(lái)自定義用戶名和密碼的獲取工作。但是我們不打算重寫這兩個(gè)方法,而是重寫它們的調(diào)用者attemptAuthentication方法,因?yàn)閖son反序列化畢竟有一定消耗,不會(huì)反序列化兩次,只需要在重寫的attemptAuthentication方法中檢查是否json登錄,然后直接反序列化返回Authentication對(duì)象即可。這樣我們沒有破壞原有的獲取流程,還是可以重用父類原有的attemptAuthentication方法來(lái)處理表單登錄。
/** * AuthenticationFilter that supports rest login(json login) and form login. * @author chenhuanming */ public class CustomAuthenticationFilter extends UsernamePasswordAuthenticationFilter { @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { //attempt Authentication when Content-Type is json if(request.getContentType().equals(MediaType.APPLICATION_JSON_UTF8_VALUE) ||request.getContentType().equals(MediaType.APPLICATION_JSON_VALUE)){ //use jackson to deserialize json ObjectMapper mapper = new ObjectMapper(); UsernamePasswordAuthenticationToken authRequest = null; try (InputStream is = request.getInputStream()){ AuthenticationBean authenticationBean = mapper.readValue(is,AuthenticationBean.class); authRequest = new UsernamePasswordAuthenticationToken( authenticationBean.getUsername(), authenticationBean.getPassword()); }catch (IOException e) { e.printStackTrace(); new UsernamePasswordAuthenticationToken( "", ""); }finally { setDetails(request, authRequest); return this.getAuthenticationManager().authenticate(authRequest); } } //transmit it to UsernamePasswordAuthenticationFilter else { return super.attemptAuthentication(request, response); } } }
封裝的AuthenticationBean類,用了lombok簡(jiǎn)化代碼(lombok幫我們寫getter和setter方法而已)
@Getter @Setter public class AuthenticationBean { private String username; private String password; }
WebSecurityConfigurerAdapter配置
重寫Filter不是問題,主要是怎么把這個(gè)Filter加到spring security的眾多filter里面。
@Override protected void configure(HttpSecurity http) throws Exception { http .cors().and() .antMatcher("/**").authorizeRequests() .antMatchers("/", "/login**").permitAll() .anyRequest().authenticated() //這里必須要寫formLogin(),不然原有的UsernamePasswordAuthenticationFilter不會(huì)出現(xiàn),也就無(wú)法配置我們重新的UsernamePasswordAuthenticationFilter .and().formLogin().loginPage("/") .and().csrf().disable(); //用重寫的Filter替換掉原有的UsernamePasswordAuthenticationFilter http.addFilterAt(customAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class); } //注冊(cè)自定義的UsernamePasswordAuthenticationFilter @Bean CustomAuthenticationFilter customAuthenticationFilter() throws Exception { CustomAuthenticationFilter filter = new CustomAuthenticationFilter(); filter.setAuthenticationSuccessHandler(new SuccessHandler()); filter.setAuthenticationFailureHandler(new FailureHandler()); filter.setFilterProcessesUrl("/login/self"); //這句很關(guān)鍵,重用WebSecurityConfigurerAdapter配置的AuthenticationManager,不然要自己組裝AuthenticationManager filter.setAuthenticationManager(authenticationManagerBean()); return filter; }
題外話,如果搭自己的oauth3的server,需要讓spring security oauth3共享同一個(gè)AuthenticationManager(源碼的解釋是這樣寫可以暴露出這個(gè)AuthenticationManager,也就是注冊(cè)到spring ioc)
@Override @Bean // share AuthenticationManager for web and oauth public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); }
上述就是小編為大家分享的使用Spring Security怎么JSON進(jìn)行配置并登錄了,如果剛好有類似的疑惑,不妨參照上述分析進(jìn)行理解。如果想知道更多相關(guān)知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。
分享題目:使用SpringSecurity怎么JSON進(jìn)行配置并登錄
文章地址:http://muchs.cn/article28/ihspcp.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供標(biāo)簽優(yōu)化、網(wǎng)站建設(shè)、小程序開發(fā)、響應(yīng)式網(wǎng)站、App設(shè)計(jì)、網(wǎng)站改版
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)