栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringBoot 整合SpringSecrity

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringBoot 整合SpringSecrity

导入项目依赖
  
            org.springframework.boot
            spring-boot-starter-security
        

        
            org.springframework.boot
            spring-boot-starter-validation
        
        
            org.springframework.boot
            spring-boot-starter-web
        
Json 数据格式化配置(可有可无)
@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 authorities;
    private  boolean enabled;

    @Override
    public Collection 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 menus = menuService.gteAllMenusWithRole();
        //for(Menu menu:menus){
        //    //判断请求url与菜单角色是否匹配
        //    if(antPathMatcher.match(menu.getPath(),requestUrl)){
        //
        //        return SecurityConfig.createList(str);
        //    }
        //}
        return  SecurityConfig.createList("ROLE_LOGIN");
    }

    @Override
    public Collection getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class aClass) {
        return true;
    }
}

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 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> userLogin(@RequestBody @Validated LoginUser user) {
		return userService.login(user);
}
}

UserService 接口
public interface UserService extends IService {
	ResponseData> login(LoginUser user);

	ResponseData> getUserByUserName(String name);

	ResponseData> getAllUserList(Integer page, Integer size, Integer state, String keyword);
}
UserServiceImpl 类
	@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);
	}

至此整合项目完成

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/952930.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号