Originally thinking of writing a wechat login, and then record, ah, wechat is again to pay, and the need for enterprise to authenticate, can only take me in the company to do the wechat login to do a record, so as not to do later, convenient use
Effect:
After scanning the code, use redirect_URI to switch to the Controller to write services, and obtain the OpenID. First go to this table to check whether this openID is associated with users
2. If there is no association, redirection to the binding page with openID, let the user enter the platform account password and click Bind. The system will verify that the account password passes and save openID to the user table. Issue our token, and then redirect to our application page with the token to complete the login. The next time the user scans the code to log in, he goes to step 1
1. The front end
/** * Third party login, */ wechatHandleClick(){const redirect_uri = encodeURIComponent(' https://domain name /auth/login.html'); const url = 'https://open.weixin.qq.com/connect/qrconnect?appid=' + this.appid + '&redirect_uri=' + redirect_uri + '&response_type=code&scope=snsapi_login&state=pc#wechat_redirect'; location.href = url }Copy the code
- The background
Redirect_uri suffix. HTML is not very confusing, a look that is the front end, in fact, is the background 😄
controller:
import com.sinotrans.iot.auth.server.service.biz.service.LoginService; import com.sinotrans.iot.auth.server.service.biz.wecharOauth2.AccessTokenResult; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.view.RedirectView; import java.awt.*; @RestController public class LoginController { @Value("${wx.pc.login.success.redirect_uri}") private String successPage; @Value("${wx.pc.login.bind.redirect_uri}") private String bindPage; @autowired private LoginService LoginService; /** * Access_token * @param code * @return */ @getMapping ("/login.html") public ModelAndView loginHtml(String code,String state) throws Exception { AccessTokenResult tokenResult = loginService.pc(code,state); if (StringUtils.isNotBlank(tokenResult.getAccess_token())) { String spage = successPage + "token=" + tokenResult.getAccess_token(); return new ModelAndView(new RedirectView(spage)); } String bpage = bindPage + "openid=" + tokenResult.getOpenid(); return new ModelAndView(new RedirectView(bpage)); } /** * Bind user wechat openID * @param userCode Login account * @param password Login password * @return token */ @getMapping (value = "/bindUser",produces = MediaType.APPLICATION_JSON_UTF8_VALUE) public String bindUser(String openid,String userCode,String password) throws Exception { return loginService.bindUser(openid,userCode,password); }}Copy the code
service:
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.sinotrans.framework.mybatis.support.FilterCondition; import com.sinotrans.iot.auth.server.service.biz.controller.TokenController; import com.sinotrans.iot.auth.server.service.biz.model.SysUserModel; import com.sinotrans.iot.auth.server.service.biz.service.LoginService; import com.sinotrans.iot.auth.server.service.biz.service.SysUserManager; import com.sinotrans.iot.auth.server.service.biz.vo.TokenPasswordVo; import com.sinotrans.iot.auth.server.service.biz.wecharOauth2.AccessTokenResult; import com.sinotrans.iot.auth.server.service.util.HttpUtils; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; import java.util.Map; @Service public class LoginServiceImpl implements LoginService { private Logger log = LoggerFactory.getLogger(getClass()); @Value("${wx.open.appid}") private String wxOpenAppid; @Value("${wx.open.appsecret}") private String wxOpenAppsecret; @Autowired private SysUserManager sysUserManager; @Autowired private TokenController tokenController; /** * PC login ** @param code after wechat scan code returned * after getting openID. First go to the user table to check whether the openID is associated with the user. * 1. If it is associated, we will directly issue our token and then redirect to our application page with the token to complete the login. * 2. * The system then verifies the account password by automatically associating it with the user's OpenID, And then issue our tokens, * Then the user is redirected to our application page with the token to complete the login. The next time the user accesses the code, the user goes to step 1. */ @override public AccessTokenResult PC (String Code,String State) throws Exception { String tokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token"; String param = "appid=" + wxOpenAppid + "&secret=" + wxOpenAppsecret + "&code=" + code + "&state=" + state + "&grant_type=authorization_code"; String strResult = HttpUtils.sendGet(tokenUrl, param); AccessTokenResult resule = JSONObject.parseObject(strResult, AccessTokenResult.class); if (StringUtils.isBlank(resule.getOpenid())) { throw new RuntimeException(JSON.toJSONString(resule)); } List<FilterCondition> conditionList = new ArrayList<>(); conditionList.add(new FilterCondition("openId", resule.getOpenid(), "=")); List<SysUserModel> user = sysUserManager.getUser(conditionList); if (! user.isEmpty()) { resule.setAccess_token(getToken(user.get(0))); }else { resule.setAccess_token(""); } return resule; } /** * Bind user * @param userCode * @param password * @return * @throws Exception */ @override public String bindUser(String openid,String userCode, String password) throws Exception { String token = ""; List<FilterCondition> conditionList = new ArrayList<>(); conditionList.add(new FilterCondition("code", userCode, "=")); conditionList.add(new FilterCondition("pwd", password, "=")); List<SysUserModel> user = sysUserManager.getUser(conditionList); if(! user.isEmpty()){ SysUserModel sysUserModel = user.get(0); sysUserModel.setOpenId(openid); sysUserManager.save(sysUserModel); // Bind openId token = getToken(sysUserModel); } return token; } /** * Obtain the token from an existing method * @param user * @return * @throws Exception */ private String getToken(SysUserModel user) throws Exception { String token; TokenPasswordVo tokenPasswordVo = new TokenPasswordVo(); tokenPasswordVo.setUsername(user.getCode()); tokenPasswordVo.setPassword(user.getPwd()); Map<String, Object> o = (Map<String, Object>)tokenController.v2login(null, tokenPasswordVo); token = o.get("access_token").toString(); return token; }}Copy the code
model:
Public class AccessTokenResult {private String Access_token; // Access_token interface call certificate timeout duration, unit: second private Long expires_in; // User refreshes access_token private String refresh_token; Private String OpenID; // User authorization scope, separated by comma (,) private String scope; // Scope of user authorization, separated by comma (,) private String unionID; // Error code private Long errCode; // Error message private String errmsg; public String getAccess_token() { return access_token; } public void setAccess_token(String access_token) { this.access_token = access_token; } public Long getExpires_in() { return expires_in; } public void setExpires_in(Long expires_in) { this.expires_in = expires_in; } public String getRefresh_token() { return refresh_token; } public void setRefresh_token(String refresh_token) { this.refresh_token = refresh_token; } public String getOpenid() { return openid; } public void setOpenid(String openid) { this.openid = openid; } public String getScope() { return scope; } public void setScope(String scope) { this.scope = scope; } public String getUnionid() { return unionid; } public void setUnionid(String unionid) { this.unionid = unionid; } public Long getErrcode() { return errcode; } public void setErrcode(Long errcode) { this.errcode = errcode; } public String getErrmsg() { return errmsg; } public void setErrmsg(String errmsg) { this.errmsg = errmsg; }}Copy the code