http的util类,通过http请求向飞书请求并获取user_access_token实现免登录

doPostJson方法:传入参数为,请求地址,请求体的json,请求头的map,返回为封装的jsonString

public static String doPostJson(String url, String json,Map<String, Object> headers) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000)
.setConnectionRequestTimeout(1000)
.setSocketTimeout(5000).build();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(requestConfig);
// 创建请求内容
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
// 创建请求头
if(headers != null){
for (String key : headers.keySet()) {
httpPost.addHeader(key,headers.get(key).toString());
}
}
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}

return resultString;
}

飞书相关获取token方法:

/**
* 获取飞书AppAccessToken
* @return
*/

public static String getAppAccessToken() {
Map<String, Object> headers = new HashMap<>();
headers.put("Content-Type", "application/json; charset=utf-8");
FeiShuAppAccessTokenVO appAccessTokenVO = null;
JSONObject relationFileReq = new JSONObject();
relationFileReq.put(FeiShuConstant.APP_ID, APPID);
relationFileReq.put(FeiShuConstant.APP_SECRET, APP_SECRET);
try {
String result = HttpClientUtil.doPostJson(GET_APP_ACCESS_TOKEN, relationFileReq.toJSONString(), headers);
appAccessTokenVO = JSONObject.parseObject(result, FeiShuAppAccessTokenVO.class);
log.info("飞书响应{}",appAccessTokenVO);
} catch (Exception e) {
log.error("获取飞书APPAccessToken失败!{}",e);
}
return appAccessTokenVO!=null?appAccessTokenVO.getApp_access_token():null;
}

先根据appkey和secret获取到apptoken,然后根据apptoken和前端传回来的code,获取userAccessToken,根据官方提供的返回值,自己封装成response对象,然后把json转为对象获取对应需要的用户信息。这里获取到用户的手机号,然后做一个用户校验。如果是本公司用户,那么直接返回手机号和验证码给前端,再次调用登录接口就实现免登录了
/**
* 获取飞书的UserAccessToken
* @param accessToken
* @param code
* @return
*/
public String getUserAccessToken(String accessToken,String code) {

Map<String, Object> headers = new HashMap<>();
JSONObject relationFileReq = new JSONObject();
headers.put("Content-Type", "application/json; charset=utf-8");
headers.put("Authorization", "Bearer " + accessToken);
relationFileReq.put("grant_type", "authorization_code");
relationFileReq.put("code", code);
FeiShuUserAccessTokenVO feiShuUserAccessTokenVO = null;
try {
String result = HttpClientUtil.doPostJson(GET_USER_ACCESS_TOKEN, relationFileReq.toJSONString(), headers);
feiShuUserAccessTokenVO = JSONObject.parseObject(result, FeiShuUserAccessTokenVO.class);
log.info("飞书响应{}", feiShuUserAccessTokenVO);
} catch (Exception e) {
log.error("获取飞书UserAccessToken失败!{}", e);
}
return feiShuUserAccessTokenVO != null ? feiShuUserAccessTokenVO.getData().getMobile().substring(3) : null;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot可以使用Spring Security框架实现Token认证,下面是一个简单的示例: 1. 添加依赖 在pom.xml中添加以下依赖: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> ``` 2. 配置Security 在Spring Boot的配置文件中添加以下配置: ``` # 关闭CSRF保护 security.enable-csrf=false # 配置登录地址和拦截路径 security.oauth2.resource.filter-order=3 security.oauth2.resource.user-info-uri=http://localhost:8080/oauth/userinfo security.oauth2.client.access-token-uri=http://localhost:8080/oauth/token security.oauth2.client.client-id=clientapp security.oauth2.client.client-secret=123456 security.oauth2.client.grant-type=client_credentials security.oauth2.client.scope=read ``` 3. 创建Token 在应用程序中创建Token,可以使用JWT(JSON Web Token)。 使用JWT创建Token的步骤如下: - 创建JWT Header - 创建JWT Payload - 使用所选算法签名JWT Header和JWT Payload 可以使用以下代码创建JWT Token: ``` import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import java.util.Date; public class JwtUtil { private final String secret = "mysecretkey"; public String generateToken(String username) { Date now = new Date(); Date expiryDate = new Date(now.getTime() + 3600 * 1000); return Jwts.builder() .setSubject(username) .setIssuedAt(new Date()) .setExpiration(expiryDate) .signWith(SignatureAlgorithm.HS512, secret) .compact(); } } ``` 4. 验证Token 在Spring Security中,可以使用Filter来验证Token。可以创建一个TokenAuthenticationFilter来实现Token验证。 TokenAuthenticationFilter的作用是在HTTP请求获取Token,并将Token转换为Authentication对象。 可以使用以下代码创建TokenAuthenticationFilter: ``` import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class TokenAuthenticationFilter extends AbstractAuthenticationProcessingFilter { public TokenAuthenticationFilter(String defaultFilterProcessesUrl, AuthenticationManager authManager) { super(new AntPathRequestMatcher(defaultFilterProcessesUrl)); setAuthenticationManager(authManager); } @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) { String token = request.getHeader("Authorization"); if (token == null) { throw new TokenException("Token not found"); } Authentication authentication = new UsernamePasswordAuthenticationToken(token, token); return getAuthenticationManager().authenticate(authentication); } @Override protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException { SecurityContextHolder.getContext().setAuthentication(authResult); chain.doFilter(request, response); } } ``` 5. 配置Security 在Spring Security的配置中,可以添加TokenAuthenticationFilter来实现Token验证。 可以使用以下代码配置Security: ``` import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; @Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private CustomUserDetailsService customUserDetailsService; @Override protected void configure(HttpSecurity http) throws Exception { http .csrf().disable() .authorizeRequests() .antMatchers(HttpMethod.POST, "/api/authenticate").permitAll() .anyRequest().authenticated() .and() .addFilter(new TokenAuthenticationFilter("/api/**", authenticationManager())) .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(customUserDetailsService).passwordEncoder(passwordEncoder()); } @Override protected AuthenticationManager authenticationManager() throws Exception { return super.authenticationManager(); } private PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } } ``` 在上述代码中,TokenAuthenticationFilter添加到了Spring Security的过滤器链中,并且设置了过滤路径为/api/**。在configure方法中,还添加了一个自定义的UserDetailsService,用于从数据库中获取用户信息。 以上是一个简单的Token认证实现示例,实际应用中还需要对Token进行过期时间验证、Token存储、Token刷新等处理。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值