spingboot 集成identityserver4身份验证

时间:2024-01-23 07:45:45

一、新建项目:com.saas.swaggerdemo

详情见:spring-boot2.7.8添加swagger-CSDN博客

在之前项目基础上添加如下依赖

       <dependency>
            <groupId>com.nimbusds</groupId>
            <artifactId>nimbus-jose-jwt</artifactId>
            <version>7.9</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>4.4.10</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.6</version>
        </dependency>
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.11</version>
        </dependency>
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20180813</version>
        </dependency>

 二、添加过滤器JwkFilter

package com.saas.swaggerdemo;
import com.nimbusds.jose.proc.BadJOSEException;
import com.nimbusds.jose.proc.SecurityContext;
import org.json.JSONObject;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.net.URL;
import java.text.ParseException;

import com.nimbusds.jose.*;
import com.nimbusds.jose.jwk.source.*;
import com.nimbusds.jwt.*;
import com.nimbusds.jose.proc.JWSKeySelector;
import com.nimbusds.jose.proc.JWSVerificationKeySelector;
import com.nimbusds.jwt.proc.*;

@WebFilter(urlPatterns = "/*", filterName="jwkTokenFilter")
public class JwkFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("jwk公钥解析验证授权...");
    }
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException
    {
        boolean authenticated = false;
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse rep = (HttpServletResponse) servletResponse;
        boolean authorizationHeaderExist = req.getHeader("Authorization") != null;
        if (!authorizationHeaderExist) {
            rep.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }
        String jwkEndpoint = "http://192.168.31.132:7000/.well-known/openid-configuration/jwks";
        String token = cutToken(req.getHeader("Authorization"));
        ConfigurableJWTProcessor jwtProcessor = new DefaultJWTProcessor();
        JWKSource keySource = new RemoteJWKSet(new URL(jwkEndpoint));
        JWSAlgorithm expectedJWSAlg = JWSAlgorithm.RS256;
        JWSKeySelector keySelector = new JWSVerificationKeySelector(expectedJWSAlg, keySource);
        if(keySelector==null)
        {
            rep.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            System.out.println("无法获取公钥");
            return;
        }
        jwtProcessor.setJWSKeySelector(keySelector);
        SecurityContext ctx = null;
        JWTClaimsSet claimsSet = null;
        try {
            claimsSet = jwtProcessor.process(token, ctx);
            authenticated = true;
        } catch (ParseException e) {
            rep.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            e.printStackTrace();
            return;
        } catch (BadJOSEException e) {
            rep.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            e.printStackTrace();
            return;
        } catch (JOSEException e) {
            rep.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            e.printStackTrace();
            return;
        }
        System.out.println(claimsSet.toJSONObject());
        if(claimsSet==null) {
            rep.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
        JSONObject jo = new JSONObject(claimsSet.toJSONObject());
        String userid = jo.getString("userid");
        if (authenticated)
        {
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            rep.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
    }


    //帮助类
    public String cutToken(String originToken)
    {
        String[] temp = originToken.split(" ");
        return temp[1];
    }

    @Override
    public void destroy() {
    }
}

添加 @ServletComponentScan

 三、准备Identityserver4Server

三、测试

Postman带上Token调用接口

  获取到用户ID

使用过期或无效的token