保护SpringBoot API以供桌面应用程序客户端使用
创始人
2024-11-24 02:01:37
0

要保护SpringBoot API以供桌面应用程序客户端使用,可以使用JWT(JSON Web Token)实现身份验证和授权。以下是一个示例解决方案,包括代码示例:

  1. 添加依赖项 在SpringBoot项目的pom.xml文件中,添加以下依赖项:

    io.jsonwebtoken
    jjwt-api
    0.11.2


    io.jsonwebtoken
    jjwt-impl
    0.11.2
    runtime


    io.jsonwebtoken
    jjwt-jackson
    0.11.2
    runtime

  1. 创建TokenUtil工具类 创建一个名为TokenUtil的工具类,用于生成和验证JWT。以下是一个简单的示例:
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;

public class TokenUtil {
    private static final String SECRET_KEY = "your-secret-key";
    private static final long EXPIRATION_TIME = 86400000; // 24 hours

    public static String generateToken(String username) {
        Date expirationDate = new Date(System.currentTimeMillis() + EXPIRATION_TIME);

        return Jwts.builder()
                .setSubject(username)
                .setExpiration(expirationDate)
                .signWith(SignatureAlgorithm.HS256, SECRET_KEY)
                .compact();
    }

    public static String getUsernameFromToken(String token) {
        Claims claims = Jwts.parser()
                .setSigningKey(SECRET_KEY)
                .parseClaimsJws(token)
                .getBody();

        return claims.getSubject();
    }

    public static boolean validateToken(String token) {
        try {
            Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
  1. 创建一个Spring Security配置类 创建一个名为SecurityConfig的Spring Security配置类,用于配置身份验证和授权规则。以下是一个简单的示例:
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .authorizeRequests()
                .antMatchers(HttpMethod.POST, "/api/login").permitAll()
                .anyRequest().authenticated()
                .and()
                .addFilter(new AuthenticationFilter(authenticationManager()));
    }
}
  1. 创建一个认证过滤器 创建一个名为AuthenticationFilter的过滤器,用于处理登录请求并生成JWT。以下是一个简单的示例:
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

public class AuthenticationFilter extends UsernamePasswordAuthenticationFilter {
    private final AuthenticationManager authenticationManager;

    public AuthenticationFilter(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
        setFilterProcessesUrl("/api/login"); // 设置登录URL
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        try {
            LoginRequest loginRequest = new ObjectMapper().readValue(request.getInputStream(), LoginRequest.class);

            return authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword(), new ArrayList<>())
            );
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
        String username = authResult.getName();
        String token = TokenUtil.generateToken(username);

        response.addHeader("

相关内容

热门资讯

记者揭秘!智星菠萝辅助(透视辅... 记者揭秘!智星菠萝辅助(透视辅助)拱趴大菠萝辅助神器,扑克教程(有挂细节);模式供您选择,了解更新找...
一分钟揭秘!约局吧能能开挂(透... 一分钟揭秘!约局吧能能开挂(透视辅助)hhpoker辅助靠谱,2024新版教程(有挂教学);约局吧能...
透视辅助!wepoker模拟器... 透视辅助!wepoker模拟器哪个好用(脚本)hhpoker辅助挂是真的,科技教程(有挂技巧);囊括...
透视代打!hhpkoer辅助器... 透视代打!hhpkoer辅助器视频(辅助挂)pokemmo脚本辅助,2024新版教程(有挂教程);风...
透视了解!约局吧德州真的有透视... 透视了解!约局吧德州真的有透视挂(透视脚本)德州局HHpoker透视脚本,必胜教程(有挂分析);亲,...
六分钟了解!wepoker挂底... 六分钟了解!wepoker挂底牌(透视)德普之星开辅助,详细教程(有挂解密);德普之星开辅助是一种具...
9分钟了解!wpk私人辅助(透... 9分钟了解!wpk私人辅助(透视)hhpoker德州透视,插件教程(有挂教学);风靡全球的特色经典游...
推荐一款!wepoker究竟有... 推荐一款!wepoker究竟有透视(脚本)哈糖大菠萝开挂,介绍教程(有挂技术);囊括全国各种wepo...
每日必备!wepoker有人用... 每日必备!wepoker有人用过(脚本)wpk有那种辅助,线上教程(有挂规律);wepoker有人用...
玩家必备教程!wejoker私... 玩家必备教程!wejoker私人辅助软件(脚本)哈糖大菠萝可以开挂,可靠技巧(有挂神器)申哈糖大菠萝...