首页JavaBee 正文

Java springboot使用identityServer4

时间: 2022年6月10日 浏览 90

Java springboot使用identityServer4

写下如何使用Java SpringBoot IdentityServer4作为身份验证服务器和令牌发布服务器。 我也是新手,所以如果你不明白,请给我更多的建议。 除此之外,中国在很长一段时间里,我还没有写单词是不合适的,欢迎您指出,共同进步。

  • 背景知识:是什么? JWT
  • 第一部分:IdentityServer4服务器设置
  • 第二部分:Java SpringBoot框架和IDS4的结合
  • SpringBoot演示源代码:[https://github.com/Danni-Ke/SpringBootDemo] [https_github.com_Danni-Ke_SpringBootDemo]

什么是Jwt,包括参数,你可以参考以下链接做的一些理解:

[https://www.cnblogs.com/zjutzz/p/5790180.html] [https_www.cnblogs.com_zjutzz_p_5790180.html]

这个链接是英文的,但是是的。 jwt更详细的,良好的英语的学生可以去。

[https://tools.ietf.org/html/rfc7519] [https_tools.ietf.org_html_rfc7519]

这种联系主要是说jwt refernce牌不同,它是非常重要的,也有一些错误,我在一个洞:

[https://www.cnblogs.com/Irving/articles/9357539.html] [https_www.cnblogs.com_Irving_articles_9357539.html]

 

关于IdentityServer4如何构建和使用,在网上有很多教程,我不会做更多的解释,因为我是一个新手。 但是我使用的是一个带UI界面IdentityServer4和身份(如用户管理的一部分)服务器相结合,建了很多事情,非常友好的新手,省略探索的脚步。 但不建议新手使用,构建… 像爱自己那样IdentityServer还有IdentitySevrer4一些参数不理解,可以做进一步的了解。 下面是IdentityServer4 UI的github源链接:

[https://github.com/skoruba/IdentityServer4.Admin] [https_github.com_skoruba_IdentityServer4.Admin]

  • 如果有人感兴趣配置这IdentityServer4 UI,以后,我也会记录如何构建相对的事。 这个IdentityServer上述配置相关的信息,比如API,客户,用户资源之后,我们将使用以下端点:
  • * http://x.x.x.x: 5000 /连接/令牌 *端口的请求令牌,需要提供客户id、客户秘密,用户名,用户密码,授权的方式,这里我选择grant_type是的密码。
  • * http://x.x.x.x: 5000 /连接/内省 *牌内省端点,许多国内语录refenrece令牌,然后有很多官方文件翻译的大男人,不是翻译(我不知道实际的意义)。 这个端点可以用于包或图书馆可以用来解析jwt令牌的程序来验证令牌的有效性。 只是注意到,唯一的区别是,关于renfence令牌和智威汤逊令牌参数发送给这个端点是不同的。 关于参考,什么是发送client_id和秘密。 但是jwt令牌,发送是base64编码的请求头Api_name Api_secret,这就是为什么Api是的秘密这个参数,但是我们很少使用。
  • http://x.x.x.x: 5000 / .well-known openid-configuration / jwks (公钥开放端点)用于获取分辨率jwt令牌的公钥开放端点。

如何启动一个新项目,这里不多讲,网上有很多教程,让我们直接点,这种方式我用Intellij IDEA。 然后注册过滤器,有两种方法来验证jwt:

  • 通过自省端点返回验证结果,使用 * http://x.x.x.x: 5000 /连接/内省 *
  • 打开本地解析端点通过公钥标记,使用 http://x.x.x.x: 5000 / .well-known openid-configuration / jwks

因为没有客户机,这样邮递员不是寻求令牌,使用 http://x.x.x.x: 5000 /连接/令牌, 和给我们的java程序启动的要求。

这是非常简单的,上层代码,主要是滤波器内部dofiler的一部分:

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println(" Start filtering requests , Endpoint authentication is introspective by the authentication server token");
boolean authenticated = false;
HttpServletRequest req = (HttpServletRequest) servletRequest;
HttpServletResponse rep = (HttpServletResponse) servletResponse;
//-------------- Send request to introspection endpoint -------------------------------
//-------------- Prepare to request information ----------------------------------------
// Actually, one. url A request is a set of key pair values ,getHeader() Method to get the head of what you want
// Value after key name , Because of the request token Of keyname This is it , But if we want to change here, we need to change
// Inside this header If not token Not this one , Will be abnormal
boolean authorizationHeaderExist = req.getHeader("Authorization") != null;
if (!authorizationHeaderExist) {
rep.setStatus(HttpServletResponse.SC_BAD_REQUEST);
return;
}
String token = cutToken(req.getHeader("Authorization"));
// Get the encoded ApiSecret and ApiName, stay application.propertiesz in
String apiNameSecret = "Basic " + ApiNameSecretbase64();
// It can be put into the configuration , There is a unified reform
String introspectEndpoint = "http://localhost:5000/connect/introspect";
//------------- Create a request ----------------------------------------------
//protected HttpClient client = new DefaultHttpClient(); Has been out of date
HttpClient client = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(introspectEndpoint);
// Add request header
post.setHeader("Authorization", apiNameSecret);
// Add request body (body)
List<NameValuePair> urlBodys = new ArrayList<NameValuePair>();
urlBodys.add(new BasicNameValuePair("token", token));
post.setEntity(new UrlEncodedFormEntity((urlBodys)));
HttpResponse response = client.execute(post);
System.out.println("nSending 'POST' request to URL : " + introspectEndpoint);
System.out.println("Post parameters : " + post.getEntity());
System.out.println("Response Code : " +
response.getStatusLine().getStatusCode());
// Read back reponse Of content Information , With the result of the decision
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
// Be careful StringBuffer No String
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
// Debugging with , Print the requested content
System.out.println(result.toString());
//------------------------------- Decision authenticated Result ---------------------------
JSONObject jo = new JSONObject(result.toString());
Boolean active = jo.getBoolean("active");
if (response.getStatusLine().getStatusCode() == 200&& active==true)
{
String role = jo.getString("role");
authenticated = true;
}
//-------------------------------- Handle authenticated Result , Decide whether to send out 401-----------
if (authenticated)
{
// After calling this method , Indicates that the filter passes through the original url Request processing method
filterChain.doFilter(servletRequest, servletResponse);
} else {
rep.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
return;
}
}
// Return Api Name and secret The coding , Part of the request header
public String ApiNameSecretbase64()
{
String result = api.getapiName()+":"+api.getapiSecret();
byte[] data=Base64.encodeBase64(result.getBytes());
return new String(data);
}
// Handle token Character string , Remove Bearer
public String cutToken(String originToken)
{
String[] temp = originToken.split(" ");
return temp[1];
}

以上ApiNameSecretbase64是阅读中的信息的功能配置,返回编码Api名称和秘密,下面是我的申请。 属性相关的配置,这些配置需要放置在IdentityServer那边,它可以通过使用内存或像我一样UI管理界面直接补充道:

#IdentityServer4 Profile parameters
api.name = Api1
api.secret=secreta

同时开始java项目和IdentityServer4之后,请求将看到的结果,如果你没有令牌就没有授权,不要把邮差的结果,因为本文主要关注代码。 请求的影响这个端点,请参考官方文档返回格式,你可以在当地建立验证相应的答复。 我把它直接活跃这布尔,以确定如果令牌是合法的。

关于代码:

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException
{
System.out.println(" Start filtering requests , By the authentication server jwk Public key resolution verification token");
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://localhost:5000/.well-known/openid-configuration/jwks";
//String token = cutToken(((HttpServletRequest) servletRequest).getHeader("Authorization"));
String token = cutToken(req.getHeader("Authorization"));
//------------ analysis ------------------------------------------------------
//com.nimbusds JWT Parsing package , This package does not find the source code at present ,
//https://connect2id.com/products/nimbus-jose-jwt/examples/validating-jwt-access-tokens
// Create parsing objects
ConfigurableJWTProcessor jwtProcessor = new DefaultJWTProcessor();
// Provide a public key address to get
JWKSource keySource = new RemoteJWKSet(new URL(jwkEndpoint));
// Provide analytic algorithm , The algorithm type should be correct , What is the server , At present is RSA256 algorithm
JWSAlgorithm expectedJWSAlg = JWSAlgorithm.RS256;
// fill in RSA The public key source is obtained from the public key address
JWSKeySelector keySelector = new JWSVerificationKeySelector(expectedJWSAlg, keySource);
if(keySelector==null)
{
rep.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
System.out.println(" Unable to get public key .");
return;
}
// Set the resolution processing object created in the first step
jwtProcessor.setJWSKeySelector(keySelector);
// Deal with received token( token ), Error returns the object
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;
}
// Debugging with , Print out
System.out.println(claimsSet.toJSONObject());
// Failure returned unauthorized
if(claimsSet==null) {
rep.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
return;
}
// Decode the contents , Especially the characters , Although there is no need for , Take it out smoothly
JSONObject jo = new JSONObject(claimsSet.toJSONObject());
String role = jo.getString("role");
// Try the expired token, Delete users can not try
//-------------------------------- Handle authenticated Result , Decide whether to send out 401-----------
if (authenticated)
{
// After calling this method , Indicates that the filter passes through the original url Request processing method
filterChain.doFilter(servletRequest, servletResponse);
} else {
rep.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
return;
}
}
// Helper classes
public String cutToken(String originToken)
{
String[] temp = originToken.split(" ");
return temp[1];
}

这主要是一个包,使用链接如下,学生良好的英语可以直接研究这个链接:

https://connect2id.com/products/nimbus-jose-jwt/examples/validating-jwt-access-tokens

这个袋子需要进口的maven取决于以下:

<!-- https://mvnrepository.com/artifact/com.nimbusds/nimbus-jose-jwt -->
<dependency>
<groupId>com.nimbusds</groupId>
<artifactId>nimbus-jose-jwt</artifactId>
<version>7.3</version>
</dependency>
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.*;

就像这样,没有一个非常明确的地方直接看源代码。

[https_github.com_Danni-Ke_SpringBootDemo]

 https://github.com/Danni-Ke/SpringBootDemo

[https_www.cnblogs.com_zjutzz_p_5790180.html]

https://www.cnblogs.com/zjutzz/p/5790180.html

 [https_tools.ietf.org_html_rfc7519]:

 https://tools.ietf.org/html/rfc7519

 [https_www.cnblogs.com_Irving_articles_9357539.html]:

https://www.cnblogs.com/Irving/articles/9357539.html

[https_github.com_skoruba_IdentityServer4.Admin]:

https://github.com/skoruba/IdentityServer4.Admin