In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-05-05 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces Spring security how to rewrite Filter to achieve json login, the article is very detailed, has a certain reference value, interested friends must read it!
JSON login
The above demonstrates an original login scheme. If you want to pass the user name and password through JSON, you need to customize the relevant filter. Through the analysis of the source code, we find that the default user name and password is extracted in the UsernamePasswordAuthenticationFilter filter, and some of the source codes are as follows:
} public Authentication attemptAuthentication (HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {if (postOnly & &! request.getMethod (). Equals ("POST")) {throw new AuthenticationServiceException ("Authentication method not supported:" + request.getMethod ());} String username = obtainUsername (request); String password = obtainPassword (request); if (username = null) {username = "" } if (password = = null) {password = "";} username = username.trim (); UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken (username, password); / / Allow subclasses to set the "details" property setDetails (request, authRequest); return this.getAuthenticationManager (). Authenticate (authRequest);} protected String obtainPassword (HttpServletRequest request) {return request.getParameter (passwordParameter) } protected String obtainUsername (HttpServletRequest request) {return request.getParameter (usernameParameter);} /... /.}
As you can see here, the default user name / password extraction is extracted through getParameter in request. If you want to use JSON to pass the user name and password, you only need to replace this filter. The custom filter is as follows:
Public class CustomAuthenticationFilter extends UsernamePasswordAuthenticationFilter {@ Override public Authentication attemptAuthentication (HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {if (request.getContentType () .equals (MediaType.APPLICATION_JSON_UTF8_VALUE) | | request.getContentType () .equals (MediaType.APPLICATION_JSON_VALUE)) {ObjectMapper mapper = new ObjectMapper (); UsernamePasswordAuthenticationToken authRequest = null Try (InputStream is = request.getInputStream ()) {Map authenticationBean = mapper.readValue (is, Map.class); authRequest = new UsernamePasswordAuthenticationToken (authenticationBean.get ("username"), authenticationBean.get ("password");} catch (IOException e) {e.printStackTrace (); authRequest = new UsernamePasswordAuthenticationToken ("", ") } finally {setDetails (request, authRequest); return this.getAuthenticationManager () .authenticate (authRequest);}} else {return super.attemptAuthentication (request, response);}
Filter.setAuthenticationSuccessHandler (new AuthenticationSuccessHandler () {@ Override public void onAuthenticationSuccess (HttpServletRequest req, HttpServletResponse resp, Authentication authentication) throws IOException, ServletException {resp.setContentType ("application/json;charset=utf-8"); PrintWriter out = resp.getWriter (); RespBean respBean = RespBean.ok ("login successful!") Out.write (new ObjectMapper () .writeValueAsString (respBean)); out.flush (); out.close ();}}) Filter.setAuthenticationFailureHandler (new AuthenticationFailureHandler () {@ Override public void onAuthenticationFailure (HttpServletRequest req, HttpServletResponse resp, AuthenticationException e) throws IOException, ServletException {resp.setContentype ("application/json;charset=utf-8"); PrintWriter out = resp.getWriter (); RespBean respBean = RespBean.error ("login failed!") Out.write (new ObjectMapper (). WriteValueAsString (respBean)); out.flush (); out.close ();}}); filter.setAuthenticationManager (authenticationManagerBean ()); return filter;}
Done ~
Spring security5 uses json to log in to public class CustomUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter {@ Override @ SneakyThrows (IOException.class) / / lombok try catch public Authentication attemptAuthentication (HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {if (request.getContentType (). Contains (MediaType.APPLICATION_JSON_VALUE)) {ObjectMapper mapper = new ObjectMapper (); Map map = mapper.readValue (request.getInputStream (), Map.class); String username = map.get (super.getUsernameParameter ()) String password = map.get (super.getPasswordParameter ()); if (username = = null) {username = "";} if (password = = null) {password = "";} username = username.trim (); UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken (username, password) SetDetails (request, authRequest); return this.getAuthenticationManager (). Authenticate (authRequest);} return super.attemptAuthentication (request, response);} @ EnableWebSecuritypublic class SecurityConfig extends WebSecurityConfigurerAdapter {@ Override protected void configure (HttpSecurity http) throws Exception {http.addFilterAt (usernamePasswordAuthenticationFilter (), UsernamePasswordAuthenticationFilter.class)} CustomUsernamePasswordAuthenticationFilter usernamePasswordAuthenticationFilter () throws Exception {CustomUsernamePasswordAuthenticationFilter filter = new CustomUsernamePasswordAuthenticationFilter (); filter.setAuthenticationManager (super.authenticationManagerBean ()) Filter.setFilterProcessesUrl (customSecurityProperties.getLoginUrl ()); / deal with login success filter.setAuthenticationSuccessHandler (new AuthenticationSuccessHandler ()); / deal with login failure filter.setAuthenticationFailureHandler (new AuthenticationFailureHandler ()); return filter;}} these are all the contents of the article "how Spring security rewrites Filter to achieve json login". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.