海宁网站建设公司推荐,怎样搞网络营销,企业资质查询,免费学校网站管理系统前后端分离模式是指由前端控制页面路由#xff0c;后端接口也不再返回html数据#xff0c;而是直接返回业务数据#xff0c;数据一般是JSON格式。Spring Security默认的表单登录方式#xff0c;在未登录或登录成功时会发起页面重定向#xff0c;在提交登录数据时#xff…前后端分离模式是指由前端控制页面路由后端接口也不再返回html数据而是直接返回业务数据数据一般是JSON格式。Spring Security默认的表单登录方式在未登录或登录成功时会发起页面重定向在提交登录数据时也不是JSON格式。要支持前后端分离模式要对这些问题进行改造。1. 认证信息改成JSON格式Spring Security默认提供账号密码认证方式具体实现是在UsernamePasswordAuthenticationFilter 中。因为是表单提交所以Filter中用request.getParameter(this.usernameParameter) 来获取用户信息。当我们将数据改成JSON并放入HTTP Body后getParameter 就没法获取到信息。要解决这个问题就要新建Filter来替换UsernamePasswordAuthenticationFilter 然后覆盖掉获取用户的方法。1.1 新建JsonUsernamePasswordAuthenticationFilterimport com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.SneakyThrows;
import org.springframework.data.util.Pair;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;public class JsonUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter {Overridepublic Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)throws AuthenticationException {if (!request.getMethod().equals(POST)) {throw new AuthenticationServiceException(Authentication method not supported: request.getMethod());}PairString, String usernameAndPassword obtainUsernameAndPassword(request);String username usernameAndPassword.getFirst();username (username ! null) ? username.trim() : ;String password usernameAndPassword.getSecond();password (password ! null) ? password : ;UsernamePasswordAuthenticationToken authRequest UsernamePasswordAuthenticationToken.unauthenticated(username,password);// Allow subclasses to set the details propertysetDetails(request, authRequest);return this.getAuthenticationManager().authenticate(authRequest);}SneakyThrowsprivate PairString, String obtainUsernameAndPassword(HttpServletRequest request) {JSONObject map JSON.parseObject(request.getInputStream(), JSONObject.class);return Pair.of(map.getString(getUsernameParameter()), map.getString(getPasswordParameter()));}
}1.2 新建JsonUsernamePasswordLoginConfigurer注册Filter有两种方式一给是直接调用httpSecurity的addFilterAt(Filter filter, Class? extends Filter atFilter) 另一个是注册通过AbstractHttpConfigurer 来注册。我们选择第二种方式来注册Filter因为AbstractHttpConfigurer 在初始化 UsernamePasswordAuthenticationFilter 的时候会额外设置一些信息。新建一个自己的AbstractHttpConfigurerimport org.springframework.security.config.annotation.web.HttpSecurityBuilder;
import org.springframework.security.config.annotation.web.configurers.AbstractAuthenticationFilterConfigurer;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;public final class JsonUsernamePasswordLoginConfigurerH extends HttpSecurityBuilderH extendsAbstractAuthenticationFilterConfigurerH, JsonUsernamePasswordLoginConfigurerH, JsonUsernamePasswordAuthenticationFilter {public JsonUsernamePasswordLoginConfigurer() {super(new JsonUsernamePasswordAuthenticationFilter(), null);}Overrideprotected RequestMatcher createLoginProcessingUrlMatcher(String loginProcessingUrl) {return new AntPathRequestMatcher(loginProcessingUrl, POST);}
}1.3 注册JJsonUsernamePasswordLoginConfigurer到HttpSecurity这一步比较简单直接关闭表单登录然后注册我们自己的Filter。http.formLogin().disable().apply(new JsonUsernamePasswordLoginConfigurer())经过这三步Spring Security就能识别JSON格式的用户信息。2. 去掉重定向有几个场景会触发Spring Security的重定向未登录重定向到登录页面登录验证成功重定向到默认页面退出登录重定向到默认页面我们要对这几个场景分别处理给前端返回错误信息而不是重定向。2.1 未登录请求未登录的请求会被AuthorizationFilter拦截并抛出异常。异常被AuthenticationEntryPoint处理默认会触发重定向到登录页。我们通过自定义AuthenticationEntryPoint来取消重定向行为改为返回JSON信息。http
// 1. 未登录的请求会被AuthorizationFilter拦截并抛出异常。
.exceptionHandling(it - it.authenticationEntryPoint((request, response, authException) - {log.info(get exception {}, authException.getClass());String msg {\\msg\\: \\用户未登录\\};response.setStatus(HttpStatus.FORBIDDEN.value());response.setContentType(MediaType.APPLICATION_JSON_VALUE);PrintWriter writer response.getWriter();writer.write(msg);writer.flush();writer.close();
}))2.2 登录成功/失败登录成功或失败后的行为由AuthenticationSuccessHandler 和AuthenticationFailureHandler 来控制。由于上面我们自定义了JsonUsernamePasswordLoginConfigurer 所以要配置自定义Configurer 上的AuthenticationSuccessHandler 和AuthenticationFailureHandler 。http.formLogin().disable().apply((SecurityConfigurerAdapter) new JsonUsernamePasswordLoginConfigurer().successHandler((request, response, authentication) - {String msg {\\msg\\: \\登录成功\\};response.setStatus(HttpStatus.OK.value());response.setContentType(MediaType.APPLICATION_JSON_VALUE);PrintWriter writer response.getWriter();writer.write(msg);writer.flush();writer.close();}).failureHandler((request, response, exception) - {String msg {\\msg\\: \\用户名密码错误\\};response.setStatus(HttpStatus.UNAUTHORIZED.value());response.setContentType(MediaType.APPLICATION_JSON_VALUE);PrintWriter writer response.getWriter();writer.write(msg);writer.flush();writer.close();}));2.3 退出登录// 退出登录
.logout(it - it.logoutSuccessHandler((request, response, authentication) - {String msg {\\msg\\: \\退出成功\\};response.setStatus(HttpStatus.OK.value());response.setContentType(MediaType.APPLICATION_JSON_VALUE);PrintWriter writer response.getWriter();writer.write(msg);writer.flush();writer.close();}))3. 最后处理CSRF校验由于前端直接调用登录接口跳过了获取登录页面的步骤所以服务端没有机会将CSRF Token传给前段所以要把POST /login接口的CSRF校验剔除掉。http.csrf(it - it.ignoringRequestMatchers(/login, POST))
文章转载自: http://www.morning.fbdtd.cn.gov.cn.fbdtd.cn http://www.morning.wmyqw.com.gov.cn.wmyqw.com http://www.morning.dsncg.cn.gov.cn.dsncg.cn http://www.morning.dzfwb.cn.gov.cn.dzfwb.cn http://www.morning.gychx.cn.gov.cn.gychx.cn http://www.morning.yrctp.cn.gov.cn.yrctp.cn http://www.morning.gqwbl.cn.gov.cn.gqwbl.cn http://www.morning.horihe.com.gov.cn.horihe.com http://www.morning.dbcw.cn.gov.cn.dbcw.cn http://www.morning.sgnjg.cn.gov.cn.sgnjg.cn http://www.morning.zlgbx.cn.gov.cn.zlgbx.cn http://www.morning.rmdsd.cn.gov.cn.rmdsd.cn http://www.morning.pyncx.cn.gov.cn.pyncx.cn http://www.morning.fhntj.cn.gov.cn.fhntj.cn http://www.morning.kzhgy.cn.gov.cn.kzhgy.cn http://www.morning.zhengdaotang.cn.gov.cn.zhengdaotang.cn http://www.morning.skrh.cn.gov.cn.skrh.cn http://www.morning.cmdfh.cn.gov.cn.cmdfh.cn http://www.morning.wwnb.cn.gov.cn.wwnb.cn http://www.morning.youprogrammer.cn.gov.cn.youprogrammer.cn http://www.morning.ailvturv.com.gov.cn.ailvturv.com http://www.morning.eviap.com.gov.cn.eviap.com http://www.morning.nyhtf.cn.gov.cn.nyhtf.cn http://www.morning.drcnn.cn.gov.cn.drcnn.cn http://www.morning.ymhjb.cn.gov.cn.ymhjb.cn http://www.morning.xywfz.cn.gov.cn.xywfz.cn http://www.morning.kpcdc.cn.gov.cn.kpcdc.cn http://www.morning.kjrp.cn.gov.cn.kjrp.cn http://www.morning.zlchy.cn.gov.cn.zlchy.cn http://www.morning.rsfp.cn.gov.cn.rsfp.cn http://www.morning.rmjxp.cn.gov.cn.rmjxp.cn http://www.morning.ngcsh.cn.gov.cn.ngcsh.cn http://www.morning.dnconr.cn.gov.cn.dnconr.cn http://www.morning.fwcnx.cn.gov.cn.fwcnx.cn http://www.morning.kbntl.cn.gov.cn.kbntl.cn http://www.morning.yfzld.cn.gov.cn.yfzld.cn http://www.morning.prjty.cn.gov.cn.prjty.cn http://www.morning.syhwc.cn.gov.cn.syhwc.cn http://www.morning.mdwlg.cn.gov.cn.mdwlg.cn http://www.morning.rwzmz.cn.gov.cn.rwzmz.cn http://www.morning.mhrzd.cn.gov.cn.mhrzd.cn http://www.morning.kjxgc.cn.gov.cn.kjxgc.cn http://www.morning.lngyd.cn.gov.cn.lngyd.cn http://www.morning.pqwhk.cn.gov.cn.pqwhk.cn http://www.morning.lmfxq.cn.gov.cn.lmfxq.cn http://www.morning.rykmz.cn.gov.cn.rykmz.cn http://www.morning.crqpl.cn.gov.cn.crqpl.cn http://www.morning.wtdyq.cn.gov.cn.wtdyq.cn http://www.morning.fllx.cn.gov.cn.fllx.cn http://www.morning.hnzrl.cn.gov.cn.hnzrl.cn http://www.morning.hbfqm.cn.gov.cn.hbfqm.cn http://www.morning.dpsgq.cn.gov.cn.dpsgq.cn http://www.morning.mrckk.cn.gov.cn.mrckk.cn http://www.morning.ycgrl.cn.gov.cn.ycgrl.cn http://www.morning.jrlxz.cn.gov.cn.jrlxz.cn http://www.morning.zhffz.cn.gov.cn.zhffz.cn http://www.morning.ppqjh.cn.gov.cn.ppqjh.cn http://www.morning.kxqwg.cn.gov.cn.kxqwg.cn http://www.morning.ksbmx.cn.gov.cn.ksbmx.cn http://www.morning.rwdbz.cn.gov.cn.rwdbz.cn http://www.morning.smdnl.cn.gov.cn.smdnl.cn http://www.morning.kxyqy.cn.gov.cn.kxyqy.cn http://www.morning.kszkm.cn.gov.cn.kszkm.cn http://www.morning.rqhdt.cn.gov.cn.rqhdt.cn http://www.morning.rmltt.cn.gov.cn.rmltt.cn http://www.morning.bhpjc.cn.gov.cn.bhpjc.cn http://www.morning.ybnps.cn.gov.cn.ybnps.cn http://www.morning.txqgd.cn.gov.cn.txqgd.cn http://www.morning.bangaw.cn.gov.cn.bangaw.cn http://www.morning.mfbcs.cn.gov.cn.mfbcs.cn http://www.morning.qwrb.cn.gov.cn.qwrb.cn http://www.morning.zrnph.cn.gov.cn.zrnph.cn http://www.morning.hwxxh.cn.gov.cn.hwxxh.cn http://www.morning.nqgjn.cn.gov.cn.nqgjn.cn http://www.morning.pamdeer.com.gov.cn.pamdeer.com http://www.morning.sgrdp.cn.gov.cn.sgrdp.cn http://www.morning.jbxmb.cn.gov.cn.jbxmb.cn http://www.morning.nzqqd.cn.gov.cn.nzqqd.cn http://www.morning.llqch.cn.gov.cn.llqch.cn http://www.morning.kxypt.cn.gov.cn.kxypt.cn