spring boot实现微信小程序登录完整代码
时间: 2023-07-30 17:09:39 浏览: 36
以下是一个基于 Spring Boot 和 Spring Security 的微信小程序登录示例代码:
1. 自定义 WeChatAuthenticationToken 类
```java
public class WeChatAuthenticationToken extends AbstractAuthenticationToken {
private final Object principal;
private Object credentials;
public WeChatAuthenticationToken(Object principal, Object credentials) {
super(null);
this.principal = principal;
this.credentials = credentials;
setAuthenticated(false);
}
public WeChatAuthenticationToken(Object principal, Object credentials,
Collection<? extends GrantedAuthority> authorities) {
super(authorities);
this.principal = principal;
this.credentials = credentials;
super.setAuthenticated(true); // must use super, as we override
}
@Override
public Object getCredentials() {
return this.credentials;
}
@Override
public Object getPrincipal() {
return this.principal;
}
@Override
public void eraseCredentials() {
super.eraseCredentials();
this.credentials = null;
}
}
```
2. 自定义 WeChatAuthenticationProvider 类
```java
@Service
public class WeChatAuthenticationProvider implements AuthenticationProvider {
private final String WECHAT_APPID = "your wechat appid"; // 微信小程序的 appid
private final String WECHAT_SECRET = "your wechat appsecret"; // 微信小程序的 appsecret
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String code = authentication.getCredentials().toString();
// 调用微信接口,获取 openid 和 session_key
String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + WECHAT_APPID
+ "&secret=" + WECHAT_SECRET
+ "&js_code=" + code
+ "&grant_type=authorization_code";
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
String responseBody = responseEntity.getBody();
ObjectMapper objectMapper = new ObjectMapper();
try {
JsonNode jsonNode = objectMapper.readTree(responseBody);
String openid = jsonNode.get("openid").asText();
String sessionKey = jsonNode.get("session_key").asText();
// 将 openid 和 session_key 封装成一个 WeChatAuthenticationToken 对象,返回认证结果
WeChatAuthenticationToken authenticationToken = new WeChatAuthenticationToken(openid, sessionKey);
return authenticationToken;
} catch (IOException e) {
throw new AuthenticationServiceException("Failed to get openid and session_key from wechat api", e);
}
}
@Override
public boolean supports(Class<?> authentication) {
return WeChatAuthenticationToken.class.isAssignableFrom(authentication);
}
}
```
3. 自定义 WeChatAuthenticationFilter 类
```java
public class WeChatAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
private final String LOGIN_URL = "/login/wechat";
public WeChatAuthenticationFilter() {
super(new AntPathRequestMatcher("/login/wechat", "POST"));
}
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException, IOException, ServletException {
String code = IOUtils.toString(request.getInputStream(), Charset.forName("UTF-8"));
// 将 code 封装成一个 WeChatAuthenticationToken 对象,交给 AuthenticationManager 进行认证
WeChatAuthenticationToken authenticationToken = new WeChatAuthenticationToken(code, code);
return getAuthenticationManager().authenticate(authenticationToken);
}
}
```
4. 自定义 WeChatAuthenticationSuccessHandler 类
```java
public class WeChatAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
private final long EXPIRATION_TIME = 1000 * 60 * 60 * 24; // 登录态过期时间为 1 天
private final String SECRET_KEY = "your secret key"; // JWT 加密所需的秘钥
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws ServletException, IOException {
String openid = authentication.getName();
String sessionKey = authentication.getCredentials().toString();
// 生成 JWT
String jwt = Jwts.builder()
.setSubject(openid)
.setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
.signWith(SignatureAlgorithm.HS512, SECRET_KEY)
.compact();
// 将 JWT 返回给前端
response.setContentType("application/json;charset=UTF-8");
response.getWriter().write("{\"jwt\":\"" + jwt + "\"}");
}
}
```
5. Spring Security 配置
```java
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private WeChatAuthenticationProvider weChatAuthenticationProvider;
@Autowired
private WeChatAuthenticationSuccessHandler weChatAuthenticationSuccessHandler;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.addFilterBefore(weChatAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
.authorizeRequests()
.antMatchers("/login/wechat").permitAll()
.anyRequest().authenticated()
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and().exceptionHandling().authenticationEntryPoint(new Http403ForbiddenEntryPoint());
}
@Bean
public WeChatAuthenticationFilter weChatAuthenticationFilter() throws Exception {
WeChatAuthenticationFilter filter = new WeChatAuthenticationFilter();
filter.setAuthenticationManager(authenticationManager());
filter.setAuthenticationSuccessHandler(weChatAuthenticationSuccessHandler);
return filter;
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(weChatAuthenticationProvider);
}
}
```
注意,在使用 JWT 进行加密时,需要保证 SECRET_KEY 的安全性。建议将 SECRET_KEY 存储在安全的地方,并且不要将其泄露给他人。
相关推荐


















