最新

SpringCloud之Security 编写过滤器处理类 1.UserLoginSuccessHandler.java

package com.springcloud.blog.admin.security.handler; import com.springcloud.blog.admin.config.JWTConfig; import com.springcloud.blog.admin.security.entity.SelfUserEntity; import com.springcloud.blog.admin.utils.AccessAddressUtil; import com.springcloud.blog.admin.utils.JWTTokenUtil; import com.springcloud.blog.admin.utils.RedisUtil; import com.springcloud.blog.admin.utils.ResultUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.AuthenticationSuccessHandler; import org.springframework.stereotype.Component; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.HashMap; import java.util.Map; /** * @Description 登录成功处理类 * @Author youcong */ @Component public class UserLoginSuccessHandler implements AuthenticationSuccessHandler {/** * 登录成功返回结果 * @Author youcong */ @Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication){ // 组装JWT SelfUserEntity selfUserEntity =(SelfUserEntity) authentication.getPrincipal(); String token = JWTTokenUtil.createAccessToken(selfUserEntity); token = JWTConfig.tokenPrefix + token; // 封装返回参数 Map resultData = https://www.it610.com/article/new HashMap<>(); resultData.put("code","200"); resultData.put("msg", "登录成功"); resultData.put("token",token); ResultUtil.responseJson(response,resultData); } }


2.UserLoginFailureHandler.java

package com.springcloud.blog.admin.security.handler; import com.springcloud.blog.admin.utils.ResultUtil; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.LockedException; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.web.authentication.AuthenticationFailureHandler; import org.springframework.stereotype.Component; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * @Description 登录失败处理类 * @Author youcong */ @Component public class UserLoginFailureHandler implements AuthenticationFailureHandler { /** * 登录失败返回结果 * @Author youcong */ @Override public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception){ // 这些对于操作的处理类可以根据不同异常进行不同处理 if (exception instanceof UsernameNotFoundException){ System.out.println("【登录失败】"+exception.getMessage()); ResultUtil.responseJson(response,ResultUtil.resultCode(500,"用户名不存在")); } if (exception instanceof LockedException){ System.out.println("【登录失败】"+exception.getMessage()); ResultUtil.responseJson(response,ResultUtil.resultCode(500,"用户被冻结")); } if (exception instanceof BadCredentialsException){ System.out.println("【登录失败】"+exception.getMessage()); ResultUtil.responseJson(response,ResultUtil.resultCode(500,"密码错误")); } ResultUtil.responseJson(response,ResultUtil.resultCode(500,"登录失败")); } }


3.UserLogoutSuccessHandler.java

package com.springcloud.blog.admin.security.handler; import com.springcloud.blog.admin.utils.DateUtil; import com.springcloud.blog.admin.utils.RedisUtil; import com.springcloud.blog.admin.utils.ResultUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.authentication.logout.LogoutSuccessHandler; import org.springframework.stereotype.Component; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.HashMap; import java.util.Map; /** * 登出成功处理类 * @Author youcong */ @Component public class UserLogoutSuccessHandler implements LogoutSuccessHandler {/** * 用户登出返回结果 * 这里应该让前端清除掉Token * @Author youcong */ @Override public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication){Map resultData = https://www.it610.com/article/new HashMap<>(); resultData.put("code","200"); resultData.put("msg", "登出成功"); SecurityContextHolder.clearContext(); ResultUtil.responseJson(response,ResultUtil.resultSuccess(resultData)); } }


4.UserAuthAccessDeniedHandler.java

package com.springcloud.blog.admin.security.handler; import com.springcloud.blog.admin.utils.ResultUtil; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.web.access.AccessDeniedHandler; import org.springframework.stereotype.Component; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * @Description 暂无权限处理类 * @Author youcong */ @Component public class UserAuthAccessDeniedHandler implements AccessDeniedHandler { /** * 暂无权限返回结果 * @Author youcong */ @Override public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException exception){ ResultUtil.responseJson(response,ResultUtil.resultCode(403,"未授权")); } }


5.UserAuthenticationEntryPointHandler.java

package com.springcloud.blog.admin.security.handler; import com.springcloud.blog.admin.utils.ResultUtil; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.AuthenticationEntryPoint; import org.springframework.stereotype.Component; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 用户未登录处理类 * @Author youcong */ @Component public class UserAuthenticationEntryPointHandler implements AuthenticationEntryPoint { /** * 用户未登录返回结果 * @Author youcong */ @Override public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception){ ResultUtil.responseJson(response,ResultUtil.resultCode(401,"未登录")); } }


6.UserAuthenticationProvider.java
自定义登录验证这个类,需要根据实际情况重写。通常来说改动不大。
【最新】
package com.springcloud.blog.admin.security; import com.baomidou.mybatisplus.mapper.EntityWrapper; import com.springcloud.blog.admin.entity.Usermeta; import com.springcloud.blog.admin.entity.Users; import com.springcloud.blog.admin.security.entity.SelfUserEntity; import com.springcloud.blog.admin.service.UsermetaService; import com.springcloud.blog.admin.service.UsersService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.LockedException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Component; import java.util.HashSet; import java.util.List; import java.util.Set; /** * 自定义登录验证 * * @Author youcong */ @Component public class UserAuthenticationProvider implements AuthenticationProvider {@Autowired private UsersService usersService; @Autowired private UsermetaService usermetaService; @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { // 获取表单输入中返回的用户名 String userName = (String) authentication.getPrincipal(); // 获取表单中输入的密码 String password = (String) authentication.getCredentials(); // 查询用户是否存在 SelfUserEntity userInfo = usersService.getUserInfo(userName); if (userInfo.getUsername() == null || userInfo.getUsername() == "") { throw new UsernameNotFoundException("用户名不存在"); }// 我们还要判断密码是否正确,这里我们的密码使用BCryptPasswordEncoder进行加密的 if (!new BCryptPasswordEncoder().matches(password, userInfo.getPassword())) { throw new BadCredentialsException("密码不正确"); } // 还可以加一些其他信息的判断,比如用户账号已停用等判断 if (userInfo.getStatus().equals("1")) { throw new LockedException("该用户已被冻结"); } // 角色集合 Set authorities = new HashSet<>(); EntityWrapper roleWrapper = new EntityWrapper<>(); roleWrapper.eq("user_id",userInfo.getUserId()); roleWrapper.eq("meta_key","wp_user_level"); // 查询用户角色 List sysRoleEntityList = usermetaService.selectList(roleWrapper); for (Usermeta sysRoleEntity: sysRoleEntityList){ authorities.add(new SimpleGrantedAuthority("ROLE_" + sysRoleEntity.getMetaValue())); } userInfo.setAuthorities(authorities); // 进行登录 return new UsernamePasswordAuthenticationToken(userInfo, password, authorities); }@Override public boolean supports(Class authentication) { return true; } }

    推荐阅读