SpringSecurity+JWT实现前后端分离认证和授权 第一部分:编码

这篇博客详细介绍了如何使用Spring Security与JWT(JSON Web Token)进行整合,实现Web应用的安全认证和授权。首先,配置了WebSecurityConfig类,通过自定义过滤器JwtTokenCheckFilter来检查JWT并设置到安全上下文中。接着,定义了登录成功和失败的处理器,以及JWT的生成和验证。此外,还展示了如何使用@PreAuthorize注解进行权限控制。博客内容包括配置、常量、过滤器和测试接口的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目录

第一部分:编码

配置类:WebSecurityConfig类

常量类:JwtConstant 类

过滤器:JwtTokenCheckFilter类

启动类:SpringsecurityJwtApplication 类

测试时的接口:TestController类


第一部分:编码

配置类:WebSecurityConfig类

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private JwtTokenCheckFilter jwtTokenCheckFilter ;
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //所有请求发送给服务端都会先执行过滤器中的操作
        http.addFilterBefore(jwtTokenCheckFilter, UsernamePasswordAuthenticationFilter.class) ;
        //去掉防护
        http.csrf().disable() ;
        //表单提交
        http.formLogin()
                .loginProcessingUrl("/doLogin")
                .successHandler(authenticationSuccessHandler()) //登录成功处理器
                .failureHandler(authenticationFailureHandler())//登录失败处理器
                .permitAll() ; //放行
        //禁用session 因为我们使用的是前后端分离。根本不需要session,只要你具有token(jwt)就可以进行访问
        http.sessionManagement().disable() ;
        //放行所有的接口 因为我们使用了jwt ;所以只要请求携带了jwt 只要能被解析,那么就相当于登录成功!
        http.authorizeRequests().antMatchers("/**").permitAll() ;//所以我们对所有请求进行放行 不做安全登录验证
    }
    //进行配置用户信息
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                //创建增加用户mxy
                .withUser("mxy")
                //设置密码 并且进行加密
                .password(passwordEncoder().encode("123"))
                //对用户进行设置访问权限
                .authorities("sys:add","sys:query") ;
    }
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder() ;
    }
    /**
     * 登录成功时的返回值
     * 1.拿到用户信息
     * 2.根据用户信息生成jwt
     * 3.写出去给客户端浏览器
     * @return
     */
    @Bean
    public AuthenticationSuccessHandler authenticationSuccessHandler() {
        return new AuthenticationSuccessHandler() {
            @Override
            public void onAuthenticationSuccess(HttpServletRequest request,
                                                HttpServletResponse response,
                                                Authentication authentication) throws IOException, ServletException {
                //设置编码以及数据格式类型为json
                response.setContentType("application/json;charaset=utf-8");
                //获取到用户信息 进行强转
                User principal = (User) authentication.getPrincipal();
                //拿到我们的用户名
                String username = principal.getUsername() ;
                //拿到我们的权限对应的集合
                Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
                List<String> authStrs = new ArrayList<>(authorities.size() * 2);//使用2倍的大小 防止轻易扩容
                //遍历authStrs集合 进行设置权限
                authorities.forEach(new Consumer<GrantedAuthority>() {
                    @Override
                    public void accept(GrantedAuthority author) {
                        //该接口重写的实现方法 内置了功能
                        //这个方法的最终作用效果为:
                        // 遍历authorities集合之后 把集合中的每一个元素的权限都设置给authStrs 这个List集合中
                        authStrs.add(author.getAuthority());
                    }
                });
                //生成jwt jwt其实就是我们所说的token
                //1.颁发token的时间
                Date createTime = new Date() ;
                //2.token过期的时间
                Calendar now = Calendar.getInstance();
                now.set(Calendar.SECOND,7200);//设置过期时间
                Date expireTime = now.getTime();//获取到过期时间expireTime
                //3.token中的header
                HashMap<String, Object> header = new HashMap<>(4);
                header.put("alg","HS256") ;
                header.put("typ","JWT") ;
                //4.token的载体
                String jwt = com.auth0.jwt.JWT.create()
                        .withHeader(header)
                        .withIssuedAt(createTime)
                        .withExpiresAt (expireTime)
                        //自定义的进行设置一些信息到JWT中
                        .withClaim("username",username)//设置用户名
                        .withClaim("auths",authStrs) //设置用户对应的权限
                        //5.设置签名
                        .sign(Algorithm.HMAC256(JwtConstant.SIGN)) ;
                //生成JWT之后,我们就要将其写出去给客户端浏览器
                HashMap<String,Object> map = new HashMap<>(8) ;
                //jwt其实就是我们所说的token
                map.put("access_token",jwt) ;
                map.put("expire_time",JwtConstant.EXPIRE_TIME) ;
                map.put("type","bearer") ;//记住:token就一种类型 那就是bearer
                ObjectMapper objectMapper = new ObjectMapper();
                String s = objectMapper.writeValueAsString(map) ;
                PrintWriter writer = response.getWriter() ;
                writer.write(s) ;
                writer.flush();
                writer.close();
            }
        } ;
    }
    //登录失败时
    @Bean
    public AuthenticationFailureHandler authenticationFailureHandler() {
        return new AuthenticationFailureHandler() {
            @Override
            public void onAuthenticationFailure(HttpServletRequest request,
                                                HttpServletResponse response,
                                                AuthenticationException e) throws IOException, ServletException {
                //设置编码格式以及数据的类型为Json格式
                response.setContentType("application/json;charset=utf-8");
                //失败的话,那么就写出去给客户端浏览器即可
                HashMap<String, Object> map = new HashMap<>(4);
                map.put("code",401) ;
                map.put("msg","登录失败") ;
                ObjectMapper objectMapper = new ObjectMapper() ;
                //把Map集合类型的数据转化为String类型的数据
                String s = objectMapper.writeValueAsString(map) ;
                PrintWriter writer = response.getWriter() ;
                writer.write(s) ;
                writer.flush();
                writer.close();
            }
        } ;
    }
}

常量类:JwtConstant 类

public interface JwtConstant {

    /**
     * 过期时间
     */
    Integer EXPIRE_TIME = 7200 ;
    /**
     * 加密的字符串
     */
    String SIGN = "security-jwt-sign" ;
    /**
     * header头里面的信息
     */
    String AUTHORIZATION = "Authorization" ;
}

过滤器:JwtTokenCheckFilter类

@Configuration
public class JwtTokenCheckFilter extends OncePerRequestFilter {

    /**
     * 每次请求都会走这个方法
     * jwt会从Headers带回来
     * 解析jwt 然后把解析后的数据设置到上下文去
     * 每一个请求都会进行解析,会大大的增大登录服务器的负担。所以说:jwt的性能没有session好
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        //设置一个响应编码
        response.setContentType("application/json;charset=utf-8");
        //1.拿到url
        String path = request.getRequestURI() ;
        String method = request.getMethod() ;//拿到请求的类型 : Get Post Put Delete
        if ("/doLogin".equals(path) && "POST".equalsIgnoreCase(method)) {
            //直接进行放行,因为登录没有token
            filterChain.doFilter(request,response) ;
            return;
        }
        //验证jwt 先进行获取到 请求中携带的Headers字段中的authorization数据
        //该数据的格式为:bearer+空格+jwt
        String authorization = request.getHeader(JwtConstant.AUTHORIZATION) ;
        //如果authorization有文本 即是有内容的意思
        if (StringUtils.hasText(authorization)) {
            //把authorization中的无用前缀 bearer+空格给进行删除 剩余的就是jwt的内容
            String jwt = authorization.replaceAll("bearer ","") ;
            //解析jwt
            //第一步:先进行验证签名 验证完签名之后才可以进行解析
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(JwtConstant.SIGN)).build() ;
            //jwt解析之后的类型为 DecodedJWT
            DecodedJWT decodedJWT = null ;
            try {
                decodedJWT = jwtVerifier.verify(jwt) ;
            } catch (JWTVerificationException e) {
                //报错了,写一个401异常
                response.getWriter().write("token验证失败");
                return;
            }
            //拿到解析之后的jwt了 即是对应的用户信息的数据。我们给后端服务器进行设置一下这些数据
            //拿到解析后数据中的用户名username的数据:
            Claim usernameClaim = decodedJWT.getClaim("username") ;
            String username = usernameClaim.asString(); //再开一层化为String类型
            //拿到jwt中的权限数据
            Claim authsClaim = decodedJWT.getClaim("auths") ;
            List<String> authStrs = authsClaim.asList(String.class); //String.class 表示转化为的集合中的元素类型为String
            //转变权限信息  容量设置为2倍避免轻易就扩容
            ArrayList<SimpleGrantedAuthority> simpleGrantedAuthorities = new ArrayList<>(authStrs.size() * 2);
            authStrs.forEach(new Consumer<String>() {
                //该接口对象中重写方法的作用就是:
                //把authStrs集合中的每一个String类型的元素进行遍历
                // 然后转变为SimpleGrantedAuthority类型的元素设置到simpleGrantedAuthorities集合中
                @Override
                public void accept(String authStr) {
                    simpleGrantedAuthorities.add(new SimpleGrantedAuthority(authStr)) ;
                }
            });
            //变成Security认识的对象
            UsernamePasswordAuthenticationToken authenticationToken =
                    //该token参数为:用户名 密码和权限集合列表
                    new UsernamePasswordAuthenticationToken(username,null,simpleGrantedAuthorities) ;
            // 怎么才能让security认识呢?
            //void setAuthentication(Authentication var1);
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            //代码继续往下执行 放行
            filterChain.doFilter(request,response) ;
        }
    }
}

启动类:SpringsecurityJwtApplication 类

@SpringBootApplication
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SpringsecurityJwtApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringsecurityJwtApplication.class, args);
    }

}

测试时的接口:TestController类

@RestController
public class TestController {

    @GetMapping("test1")
    @PreAuthorize("hasAuthority('sys:add')")
    public String test1() {
        return "add成功" ;
    }
    @GetMapping("test2")
    @PreAuthorize("hasAuthority('sys:delete')")
    public String test2() {
        return "delete成功" ;
    }
}

### 回答1: 前后端分离是一种将前端界面与后端逻辑进行分离开发的架构方式,使得前端与后端可以并行开发。OAuth 2.0是一种授权框架,用于授权认证流程的规范化,而Spring Security是一个在Java实现安全控制的框架,提供了大量的安全特性。Spring Authorization Server是Spring Security中用于实现授权服务器的模块,它支持OAuth 2.0的各种授权模式。 密码模式是OAuth 2.0中的一种授权模式,它允许用户通过提交用户名密码来获取访问令牌,然后使用该令牌来访问受保护的资源。在前后端分离的架构中,可以使用Spring Security配合Spring Authorization Server来实现密码模式的认证授权。 在密码模式下,前端首先需要收集用户的用户名密码,并将其发送给后端。后端使用Spring Security提供的密码编码器对密码进行加密,并验证用户名密码的正确性。如果验证通过,则后端向客户端颁发一个访问令牌,通常是一个JWT(JSON Web Token)。前端使用获得的访问令牌来访问需要受保护的资源,每次请求将该令牌作为Authorization头的Bearer字段发送给后端进行验证。后端可以使用Spring Security的资源服务器来验证该令牌的有效性,并根据用户的权限控制对资源的访问。 使用Spring SecuritySpring Authorization Server的密码模式可以实现安全的前后端分离架构。通过合理配置使用安全特性,可以保障用户的身份认证资源的授权,确保系统的安全性。 ### 回答2: 前后端分离是一种软件架构模式,前端后端通过使用API进行通信,分别负责处理用户界面数据逻辑。OAuth 2.0是一种用于授权的开放标准协议,它允许用户在第三方应用程序中授权访问其受保护的资源。Spring Security是Spring框架中的一个模块,提供了身份验证授权功能。 在前后端分离的架构中,前端应用程序通常需要使用OAuth 2.0协议进行用户授权,以访问后端应用程序的受保护资源。为了实现密码模式,我们可以使用Spring Security的模块之一,即spring-authorization-server。 spring-authorization-server是Spring Security的一个子模块,用于实现OAuth 2.0协议中的授权服务器。密码模式是OAuth 2.0协议中的一种授权模式,允许前端应用程序通过用户的用户名密码进行授权。密码模式在安全性上有一定的风险,因此在实际应用中需要谨慎使用。 使用spring-authorization-server的密码模式,我们可以在前端应用程序中收集用户的用户名密码,并将其提交给后端应用程序进行验证。后端应用程序将使用Spring Security进行身份验证,并向前端应用程序颁发一个访问令牌,该令牌可以用于后续的API请求。 通过使用前后端分离、OAuth 2.0spring-authorization-server的密码模式,我们可以实现安全的用户授权身份验证机制,确保只有经过授权的用户才能访问受保护的资源。这种架构模式能够提高系统的安全性可扩展性,适用于各种类型的应用程序。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值