使用SpringBoot security和Jwt实现权限管理2

本文介绍了如何使用SpringBoot Security和Jwt进行权限管理,详细讲解了SpringBoot security配置、JwtTokenFilter的实现、@PreAuthorize注解的使用,以及解决跨域问题的方法。文中通过实例展示了用户注册、登录及权限验证的过程,并提供了测试结果。
摘要由CSDN通过智能技术生成

上篇文章主要是做了准备工作,这篇将介绍SpringBoot security和Jwt的结合

SpringBoot security相关代码说明

从上篇文章中提到的WebSecurityConfig讲起,下面的configure方法主要是添加了http.apply(new JwtTokenFilterConfigurer(jwtTokenProvider));,使得所有请求都将经过Jwt过滤器,Jwt过滤器负责验证用户身份并把用户角色列表传递给Security框架管理。

    @Override
    protected void configure(HttpSecurity http) throws Exception {
   

        // Disable CSRF (cross site request forgery)
        http.csrf().disable();

        // No session will be created or used by spring security
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        // Entry points
        http.authorizeRequests()
                .antMatchers(HttpMethod.OPTIONS).permitAll() //配合@CrossOrigin 解决跨域问题
                .antMatchers("/users/signin").permitAll()//开放登录
                .antMatchers("/users/signup").permitAll()//开发注册
                .antMatchers("/test/**").permitAll() // test/**无需websecurity认证
                // Disallow everything else..
                .anyRequest().authenticated(); // 其他请求都需要认证

        // 所有请求都将被JwtTokenFilterConfigurer拦截
        http.apply(new JwtTokenFilterConfigurer(jwtTokenProvider));

    }

Jwt相关代码说明

在JwtTokenFilterConfigurer中,会执行JwtTokenFilter过滤器。JwtTokenFilter过滤器主要代码如下:

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
   
        String token = jwtTokenProvider.resolveToken(httpServletRequest);
        try {
   
            if (token != null && jwtTokenProvider.validateToken(token)) {
   
                Authentication auth = jwtTokenProvider.getAuthentication(token);
                // 传值给controller,controller可使用@PreAuthorize注解进行认证
                SecurityContextHolder.ge
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值