# 单独授权使用

我们将通过一个简单的 Demo 来阐述 CollectiveOAuth 类库的使用方法


# Step1 WebConfig中配置授权秘钥信息

<!--微信服务号自动授权-->
<add key="CollectiveOAuth_WECHAT_MP_ClientId" value="xxxxxxxxxxxx" />
<add key="CollectiveOAuth_WECHAT_MP_ClientSecret" value="xxxxxxxxxxxxxxxxxxxxxxxxxxx" />
<add key="CollectiveOAuth_WECHAT_MP_Scope" value="snsapi_userinfo" />
<add key="CollectiveOAuth_WECHAT_MP_RedirectUri" value="https://yours.domain.com/oauth2/callback?authSource=WECHAT_MP" />

# Step2 构建授权地址

/// <summary>
/// 构建授权Url方法
/// </summary>
/// <param name="authSource"></param>
/// <returns>RedirectUrl</returns>
public ActionResult Authorization(string authSource)
{
    // 创建授权request
    var clientConfig = new ClientConfig();
    clientConfig.clientId = AppSettingUtils.GetStrValue($"CollectiveOAuth_WECHAT_MP_ClientId");
    clientConfig.clientSecret = AppSettingUtils.GetStrValue($"CollectiveOAuth_WECHAT_MP_ClientSecret");
    clientConfig.redirectUri = AppSettingUtils.GetStrValue($"CollectiveOAuth_WECHAT_MP_RedirectUri");
    clientConfig.scope = AppSettingUtils.GetStrValue($"CollectiveOAuth_WECHAT_MP_Scope");
    
    AuthRequest authRequest = new WeChatMpAuthRequest(clientConfig);
    // 生成授权Url
    var authorizeUrl = authRequest.authorize(AuthStateUtils.createState());
    return Redirect(authorizeUrl);
}

# Step3 接收授权回调

/// <summary>
/// 授权回调方法
/// </summary>
/// <param name="authSource"></param>
/// <param name="authCallback"></param>
/// <returns></returns>
public ActionResult Callback(string authSource, AuthCallback authCallback)
{
    // 创建授权request
    var clientConfig = new ClientConfig();
    clientConfig.clientId = AppSettingUtils.GetStrValue($"CollectiveOAuth_WECHAT_MP_ClientId");
    clientConfig.clientSecret = AppSettingUtils.GetStrValue($"CollectiveOAuth_WECHAT_MP_ClientSecret");
    clientConfig.redirectUri = AppSettingUtils.GetStrValue($"CollectiveOAuth_WECHAT_MP_RedirectUri");
    clientConfig.scope = AppSettingUtils.GetStrValue($"CollectiveOAuth_WECHAT_MP_Scope");
    
    AuthRequest authRequest = new WeChatMpAuthRequest(clientConfig);
    var authResponse = authRequest.login(authCallback);
    //如果返回结果等于2000 代表授权成功
    if(authResponse.code == 2000){
      var userInfo = authResponse.data;
    }
    return View();
}