Json 数据格式化配置(可有可无)org.springframework.boot spring-boot-starter-security org.springframework.boot spring-boot-starter-validation org.springframework.boot spring-boot-starter-web
@Configuration
public class JsonMessageConverterConfig {
@Bean
@Primary
public HttpMessageConverters fastJsonHttpMessageConverters(){
FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");
fastJsonConfig.setSerializerFeatures(
SerializerFeature.PrettyFormat,
SerializerFeature.WriteNullStringAsEmpty,
SerializerFeature.WriteNullListAsEmpty,
SerializerFeature.WriteMapNullValue,
SerializerFeature.MapSortField,
SerializerFeature.DisableCircularReferenceDetect);
fastConverter.setFastJsonConfig(fastJsonConfig);
return new HttpMessageConverters(fastConverter);
}
}
编写SecrityConfig
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private JwtAccessDeniedHandler jwtAccessDeniedHandler;
@Autowired
private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
@Autowired
private CustomFilter customFilter;
@Autowired
private CustomUrlDecisionManager customUrlDecisionManager;
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers(
"/login",
"/logout",
"/css
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class AdminDetails implements UserDetails {
private String id;
private String username;
private String password;
private Collection extends GrantedAuthority> authorities;
private boolean enabled;
@Override
public Collection extends GrantedAuthority> getAuthorities() {
return this.authorities;
}
@Override
public String getPassword() {
return this.password;
}
@Override
public String getUsername() {
return this.username;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return this.enabled;
}
}
CustomFilter 类(可无)
@Component
public class CustomFilter implements FilterInvocationSecurityMetadataSource {
@Autowired
private MenuService menuService;
AntPathMatcher antPathMatcher = new AntPathMatcher();
@Override
public Collection getAttributes(Object object) throws IllegalArgumentException {
//获取请求url
String requestUrl = ((FilterInvocation) object).getRequestUrl();
//获取菜单
List
CustomUrlDecisionManager 类(可无)
@Component
public class CustomUrlDecisionManager implements AccessDecisionManager {
@Override
public void decide(Authentication authentication, Object o, Collection configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
for (ConfigAttribute configAttribute : configAttributes) {
//当前url所需角色
String needRole = configAttribute.getAttribute();
if("ROLE_LOGIN".equals(needRole)){
//判断是否登录
if (authentication instanceof AnonymousAuthenticationToken){
throw new AccessDeniedException("尚未登录,请登录!");
}else {
return;
}
}
//判断角色是否为url所需角色
Collection extends GrantedAuthority> authorities = authentication.getAuthorities();
for (GrantedAuthority authority : authorities) {
if (authority.getAuthority().equals(needRole)){
return;
}
}
}
throw new AccessDeniedException("权限不足,请联系管理员!");
}
@Override
public boolean supports(ConfigAttribute configAttribute) {
return true;
}
@Override
public boolean supports(Class> aClass) {
return true;
}
}
JwtAccessDeniedHandler 类
@Component
public class JwtAccessDeniedHandler implements AccessDeniedHandler {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json");
PrintWriter writer = response.getWriter();
writer.write(JSON.toJSONString(ResponseData.failure(403,"权限不足,请联系管理员")));
writer.flush();
writer.close();
}
}
JwtAuthencationTokenFilter 类
@Component
@Slf4j
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json");
PrintWriter writer = response.getWriter();
writer.write(JSON.toJSONString(ResponseData.failure(201,"未登录,请先登录")));
writer.flush();
writer.close();
}
}
自定义UserDetailsServiceImpl 实现 UserDetailsService接口
@Service
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
private UserServiceImpl userService;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
QueryWrapper userQueryWrapper = new QueryWrapper<>();
userQueryWrapper.eq("user_name", username);
AdminDetails securityUserDetails = null;
try {
User user = userService.getOne(userQueryWrapper, true);
securityUserDetails = new AdminDetails();
securityUserDetails.setUsername(user.getUserName());
securityUserDetails.setPassword(user.getPassword());
securityUserDetails.setEnabled(user.getStatus() == 1);
} catch (Exception e) {
throw new UsernameNotFoundException("用户登录失败!");
}
return securityUserDetails;
}
}
LoginController
@RestController
public class LoginController {
@Autowired
private UserService userService;
@PostMapping("/login")
public ResponseData
UserService 接口
public interface UserService extends IServiceUserServiceImpl 类{ ResponseData
@Override public ResponseData> login(LoginUser loginUser) { String captcha = redisUtil.get(loginUser.getKey()).toString(); if (StringUtils.isEmpty(loginUser.getCode())||!captcha.equalsIgnoreCase(loginUser.getCode())){ return ResponseData.failure("验证码输入错误,请重新输入!"); } //登录 AdminDetails userDetails = (AdminDetails) userDetailsService.loadUserByUsername(loginUser.getUsername()); if (null== userDetails||!passwordEncoder.matches(loginUser.getPassword(),userDetails.getPassword())){ return ResponseData.failure("用户名或密码不正确"); } if (!userDetails.isEnabled()){ return ResponseData.failure("账户被禁用,请联系管理员"); } //设置用户对象至SpringSecurity全局上下文,方便其他地方使用 UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); SecurityContextHolder.getContext().setAuthentication(authenticationToken); //生成token String token = jwtUtil.generateToken(userDetails); Map tokenMap = new HashMap<>(); tokenMap.put("header",tokenHeader); tokenMap.put("token",token); return ResponseData.success(tokenMap); }
至此整合项目完成



