欢迎您访问365答案网,请分享给你的朋友!
生活常识 学习资料

集成springsecurity

时间:2023-07-03
依赖

org.springframework.boot spring-boot-starter-security

配置类

package com.ljh.config;import com.fasterxml.jackson.databind.ObjectMapper;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.http.HttpStatus;import org.springframework.security.authentication.AuthenticationManager;import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;import org.springframework.security.config.annotation.web.builders.HttpSecurity;import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;import org.springframework.security.core.userdetails.User;import org.springframework.security.core.userdetails.UserDetailsService;import org.springframework.security.provisioning.InMemoryUserDetailsManager;import javax.servlet.http.HttpServletResponse;import java.util.HashMap;@Configurationpublic class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .mvcMatchers("/code11","/doLogin") .permitAll() .anyRequest().authenticated() .and() .formLogin() .and() .exceptionHandling() .authenticationEntryPoint((httpServletRequest, httpServletResponse, e) -> { httpServletResponse.setContentType("application/json;charset=utf-8"); httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); httpServletResponse.getWriter().println("必须认证后才能访问"); }) .and() .logout() .and() .csrf() .disable(); } @Override @Bean public UserDetailsService userDetailsService(){ InMemoryUserDetailsManager inMemoryUserDetailsManager = new InMemoryUserDetailsManager(); inMemoryUserDetailsManager.createUser(User.withUsername("root").password("{noop}123").roles("admin").build()); return inMemoryUserDetailsManager; } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService()); } @Override @Bean public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } @Bean public KpatchaFilter kpatchaFilter() throws Exception { KpatchaFilter kpatchaFilter = new KpatchaFilter(); kpatchaFilter.setFilterProcessesUrl("/doLogin"); kpatchaFilter.setUsernameParameter("username"); kpatchaFilter.setPasswordParameter("pwd"); kpatchaFilter.setAuthenticationManager(authenticationManagerBean()); kpatchaFilter.setAuthenticationSuccessHandler((req,response,authentication)->{ HashMap result = new HashMap<>(); result.put("msg","登陆成功"); result.put("用户信息",authentication.getPrincipal()); response.setContentType("application/json;charset=UTF-8"); response.setStatus(HttpStatus.OK.value()); String s = new ObjectMapper().writevalueAsString(result); response.getWriter().println(s); }); kpatchaFilter.setAuthenticationFailureHandler((req,response,exception)->{ HashMap result = new HashMap<>(); result.put("msg","登陆失败"); result.put("失败原因",exception.getMessage()); response.setContentType("application/json;charset=UTF-8"); response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value()); String s = new ObjectMapper().writevalueAsString(result); response.getWriter().println(s); }); return kpatchaFilter; }}

自定义过滤器

package com.ljh.config;import com.fasterxml.jackson.databind.ObjectMapper;import org.springframework.context.annotation.Configuration;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;import org.springframework.util.ObjectUtils;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;import java.util.Map;public class KpatchaFilter extends UsernamePasswordAuthenticationFilter { @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { if ( !request.getMethod().equals("POST")) { throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod()); } //获取请求验证码 try { Map map = new ObjectMapper().readValue(request.getInputStream(), Map.class); String username = map.get("username"); String password = map.get("pwd"); String kaptcha = map.get("code"); //获取session中的验证码 String code = (String) request.getSession().getAttribute("kaptcha"); System.out.println("=============session中的验证码"+code); //获取用户名和密码认证 if (!ObjectUtils.isEmpty(kaptcha)&&!ObjectUtils.isEmpty(code)&&kaptcha.equalsIgnoreCase(code)){ UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(username, password); setDetails(request,usernamePasswordAuthenticationToken); return this.getAuthenticationManager().authenticate(usernamePasswordAuthenticationToken); } } catch (IOException e) { e.printStackTrace(); } throw new RuntimeException("验证码不匹配"); }}

Copyright © 2016-2020 www.365daan.com All Rights Reserved. 365答案网 版权所有 备案号:

部分内容来自互联网,版权归原作者所有,如有冒犯请联系我们,我们将在三个工作时内妥善处理。