Search in sources :

Example 1 with WxMaJscode2SessionResult

use of cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult in project security-weixin-spring-boot-starter by hiwepy.

the class WxMaAuthenticationProvider method authenticate.

/**
 * <p>完成匹配Token的认证,这里返回的对象最终会通过:SecurityContextHolder.getContext().setAuthentication(authResult); 放置在上下文中</p>
 * @author 		:<a href="https://github.com/hiwepy">wandl</a>
 * @param authentication  {@link WxMaAuthenticationToken IdentityCodeAuthenticationToken} 对象
 * @return 认证结果{@link Authentication}对象
 * @throws AuthenticationException  认证失败会抛出异常
 */
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    Assert.notNull(authentication, "No authentication data provided");
    if (logger.isDebugEnabled()) {
        logger.debug("Processing authentication request : " + authentication);
    }
    WxMaLoginRequest loginRequest = (WxMaLoginRequest) authentication.getPrincipal();
    try {
        WxMaAuthenticationToken loginToken = (WxMaAuthenticationToken) authentication;
        loginToken.setOpenid(loginRequest.getOpenid());
        loginToken.setUnionid(loginRequest.getUnionid());
        loginToken.setSessionKey(loginRequest.getSessionKey());
        loginToken.setUserInfo(loginRequest.getUserInfo());
        // 表示需要根据jscode获取会话信息
        if (!StringUtils.hasText(loginRequest.getSessionKey()) && StringUtils.hasText(loginRequest.getJscode())) {
            WxMaJscode2SessionResult sessionResult = getWxMaService().jsCode2SessionInfo(loginRequest.getJscode());
            if (null != sessionResult) {
                loginToken.setOpenid(sessionResult.getOpenid());
                loginToken.setUnionid(sessionResult.getUnionid());
                loginToken.setSessionKey(sessionResult.getSessionKey());
            }
        }
        if (StringUtils.hasText(loginRequest.getSessionKey()) && StringUtils.hasText(loginRequest.getEncryptedData()) && StringUtils.hasText(loginRequest.getIv())) {
            try {
                // 解密手机号码信息
                WxMaPhoneNumberInfo phoneNumberInfo = getWxMaService().getUserService().getPhoneNoInfo(loginRequest.getSessionKey(), loginRequest.getEncryptedData(), loginRequest.getIv());
                if (!Objects.isNull(phoneNumberInfo) && StringUtils.hasText(phoneNumberInfo.getPhoneNumber())) {
                    loginToken.setPhoneNumberInfo(phoneNumberInfo);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (Objects.isNull(loginRequest.getUserInfo()) && StringUtils.hasText(loginRequest.getSessionKey()) && StringUtils.hasText(loginRequest.getEncryptedData()) && StringUtils.hasText(loginRequest.getIv())) {
            try {
                // 解密用户信息
                WxMaUserInfo userInfo = getWxMaService().getUserService().getUserInfo(loginRequest.getSessionKey(), loginRequest.getEncryptedData(), loginRequest.getIv());
                if (null == userInfo) {
                    loginToken.setUserInfo(userInfo);
                }
            } catch (Exception e) {
                throw new AuthenticationServiceException("微信登录认证失败.", e);
            }
        }
        UserDetails ud = getUserDetailsService().loadUserDetails(loginToken);
        // User Status Check
        getUserDetailsChecker().check(ud);
        WxMaAuthenticationToken authenticationToken = null;
        if (SecurityPrincipal.class.isAssignableFrom(ud.getClass())) {
            authenticationToken = new WxMaAuthenticationToken(ud, ud.getPassword(), ud.getAuthorities());
        } else {
            authenticationToken = new WxMaAuthenticationToken(ud.getUsername(), ud.getPassword(), ud.getAuthorities());
        }
        authenticationToken.setDetails(authentication.getDetails());
        return authenticationToken;
    } catch (WxErrorException e) {
        throw new AuthenticationServiceException("微信登录认证失败.", e);
    }
}
Also used : UserDetails(org.springframework.security.core.userdetails.UserDetails) WxMaUserInfo(cn.binarywang.wx.miniapp.bean.WxMaUserInfo) WxMaJscode2SessionResult(cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult) WxMaPhoneNumberInfo(cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo) AuthenticationServiceException(org.springframework.security.authentication.AuthenticationServiceException) WxErrorException(me.chanjar.weixin.common.error.WxErrorException) AuthenticationException(org.springframework.security.core.AuthenticationException) AuthenticationServiceException(org.springframework.security.authentication.AuthenticationServiceException) WxErrorException(me.chanjar.weixin.common.error.WxErrorException)

Example 2 with WxMaJscode2SessionResult

use of cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult in project nutz-spring-boot-starter by nutzam.

the class SocialLoginController method oauth.

@GetMapping("{channel}/oauth")
@Operation(summary = "用code进行oauth登录,各端根据前置操作获取到code调用此接口,如果已经绑定,返回token,如果没有绑定则返回openid")
public Result<String> oauth(@Parameter(description = "授权码", required = true) @RequestParam("code") String code, @Parameter(description = "授权渠道", required = true) @PathVariable("channel") Channel channel) throws WxErrorException {
    if (channel == Channel.MINIAPP) {
        WxMaJscode2SessionResult result = wxMaService.jsCode2SessionInfo(code);
        LoginChannel loginChannel = loginChannelService.fetch(Cnd.where(LoginChannel.Fields.openid, "=", result.getOpenid()).and(LoginChannel.Fields.channel, "=", channel));
        if (loginChannel == null) {
            // 用户没有绑定
            return Result.<String>builder().data(result.getOpenid()).state(OperationState.FAIL).build();
        } else {
            // 已经绑定
            User user = userService.fetch(loginChannel.getUserId());
            return Result.success(user.toUser().getToken());
        }
    } else {
        WxOAuth2AccessToken token = wxMpService.getOAuth2Service().getAccessToken(code);
        WxOAuth2UserInfo result = wxMpService.getOAuth2Service().getUserInfo(token, "zh-CN");
        LoginChannel loginChannel = loginChannelService.fetch(Cnd.where(LoginChannel.Fields.openid, "=", result.getOpenid()).and(LoginChannel.Fields.channel, "=", channel));
        if (loginChannel == null) {
            // 用户没有绑定
            return Result.fail(result.getOpenid());
        } else {
            // 已经绑定
            User user = userService.fetch(loginChannel.getUserId());
            return Result.success(user.toUser().getToken());
        }
    }
}
Also used : LoginChannel(tech.riemann.demo.entity.acl.LoginChannel) User(tech.riemann.demo.entity.acl.User) WxMaJscode2SessionResult(cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult) WxOAuth2AccessToken(me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken) WxOAuth2UserInfo(me.chanjar.weixin.common.bean.WxOAuth2UserInfo) GetMapping(org.springframework.web.bind.annotation.GetMapping) Operation(io.swagger.v3.oas.annotations.Operation)

Example 3 with WxMaJscode2SessionResult

use of cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult in project JBM by numen06.

the class WxMaUserController method login2.

@PostMapping("/login")
public ResultBody<WxMaJscode2SessionResult> login2(@PathVariable String appid, String code) {
    if (StringUtils.isBlank(code)) {
        return ResultBody.error(null, "empty jscode");
    }
    final WxMaService wxService = WxMaConfiguration.getMaService(appid);
    try {
        WxMaJscode2SessionResult session = wxService.getUserService().getSessionInfo(code);
        log.info(session.getSessionKey());
        log.info(session.getOpenid());
        // TODO 可以增加自己的逻辑,关联业务相关数据
        return ResultBody.success(session, "微信登录成功");
    } catch (WxErrorException e) {
        log.error(e.getMessage(), e);
        return ResultBody.error(null, e.getMessage());
    }
}
Also used : WxMaService(cn.binarywang.wx.miniapp.api.WxMaService) WxMaJscode2SessionResult(cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult) WxErrorException(me.chanjar.weixin.common.error.WxErrorException)

Example 4 with WxMaJscode2SessionResult

use of cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult in project spring-cloud-alibaba by longlylong.

the class WxMaUserController method getCommonLoginResult.

private Result<LoginResultDTO> getCommonLoginResult(@RequestBody @Valid CommonLoginVo vo, String appId) {
    try {
        WxMaService wxMaService = WxMaConfiguration.getMaService(appId);
        WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(vo.getCode());
        String openId = session.getOpenid();
        Result<LoginResultDTO> token = null;
        return token;
    } catch (WxErrorException e) {
        throw TDExceptionHandler.throwGlobalException("getCommonLoginResult", e);
    }
}
Also used : LoginResultDTO(com.thatday.user.modules.user.dto.LoginResultDTO) WxMaService(cn.binarywang.wx.miniapp.api.WxMaService) WxMaJscode2SessionResult(cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult) WxErrorException(me.chanjar.weixin.common.error.WxErrorException)

Example 5 with WxMaJscode2SessionResult

use of cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult in project spring-cloud-alibaba by longlylong.

the class WxMaUserController method authorLogin.

@PostMapping("/authorLogin")
@ApiOperation("普通授权登录")
public Result<LoginResultDTO> authorLogin(@Valid @RequestBody AuthorLoginVo vo) {
    String appId = "app id";
    try {
        WxMaService wxMaService = WxMaConfiguration.getMaService(appId);
        WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(vo.getCode());
        // 解密用户信息
        WxMaUserInfo userInfo = wxMaService.getUserService().getUserInfo(session.getSessionKey(), vo.getEncryptedData(), vo.getIv());
        return null;
    } catch (WxErrorException e) {
        throw TDExceptionHandler.throwGlobalException("tcyAuthorLogin", e);
    }
}
Also used : WxMaUserInfo(cn.binarywang.wx.miniapp.bean.WxMaUserInfo) WxMaService(cn.binarywang.wx.miniapp.api.WxMaService) WxMaJscode2SessionResult(cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult) WxErrorException(me.chanjar.weixin.common.error.WxErrorException) PostMapping(org.springframework.web.bind.annotation.PostMapping) ApiOperation(io.swagger.annotations.ApiOperation)

Aggregations

WxMaJscode2SessionResult (cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult)13 WxErrorException (me.chanjar.weixin.common.error.WxErrorException)9 WxMaService (cn.binarywang.wx.miniapp.api.WxMaService)6 HashMap (java.util.HashMap)3 WxError (me.chanjar.weixin.common.error.WxError)3 LitemallUser (org.linlinjava.litemall.db.domain.LitemallUser)3 WxMaPhoneNumberInfo (cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo)2 WxMaUserInfo (cn.binarywang.wx.miniapp.bean.WxMaUserInfo)2 BusinessException (com.chao.cloud.common.exception.BusinessException)2 ApiOperation (io.swagger.annotations.ApiOperation)2 UserInfo (org.linlinjava.litemall.wx.dto.UserInfo)2 GetMapping (org.springframework.web.bind.annotation.GetMapping)2 PostMapping (org.springframework.web.bind.annotation.PostMapping)2 WxLoginErrorException (com.stardata.starshop2.authcontext.domain.WxLoginErrorException)1 LoginResultDTO (com.thatday.user.modules.user.dto.LoginResultDTO)1 Operation (io.swagger.v3.oas.annotations.Operation)1 WxOAuth2UserInfo (me.chanjar.weixin.common.bean.WxOAuth2UserInfo)1 WxOAuth2AccessToken (me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken)1 WxErrorException (me.chanjar.weixin.common.exception.WxErrorException)1 BCryptPasswordEncoder (org.linlinjava.litemall.core.util.bcrypt.BCryptPasswordEncoder)1