Example #1
0
        /// <summary>
        /// 获取用户信息。
        /// </summary>
        /// <param name="authService">OAuth服务。</param>
        /// <param name="code">公众平台Code参数。</param>
        /// <returns>用户信息。</returns>
        public static OAuthUserInfo GetUserInfo(this IOAuthService authService, string code)
        {
            code.NotEmptyOrWhiteSpace("code");
            var result = authService.NotNull("authService").GetAccessToken(code);

            if (result == null)
            {
                throw new ArgumentException("根据 Code 获取访问票据失败。", "code");
            }
            return(authService.GetUserInfo(result, result.OpenId));
        }
Example #2
0
        public async Task <IActionResult> GithubRedirect([FromQuery] GithubOAuthRedirectQuery query, [FromServices] IOAuthService oAuthService,
                                                         [FromServices] IOptions <GithubOAuth> githubOauthConfig)
        {
            if (User.Identity?.IsAuthenticated == true)
            {
                return(Redirect("/"));
            }
            if (!githubOauthConfig.Value.Enabled)
            {
                return(Redirect("/"));
            }
            if (string.IsNullOrEmpty(query.Code))
            {
                return(Redirect("/"));
            }

            OAuthUserInfo userInfo;

            try
            {
                userInfo = await oAuthService.GetUserInfo(OAuthProvider.Github, query.Code).CAF();
            }
            catch (FailedOperationException)
            {
                _logger.LogWarning("Bounced OAuth attempt from OAuth provider: {Provider}", OAuthProvider.Github.ToString());
                return(Redirect("/"));
            }
            (string userId, string roles) = await _userService.AddOrUpdateOAuthUser(userInfo).CAF();

            await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme
                                          , ClaimsPrincipal(userId, roles, oAuthUser : true)).CAF();

            await _userService.TryLoginOAuth(userId).CAF();

            _logger.LogInformation("Successfully logged in for User id: {UserId} from OAuth Provider: {Provider}",
                                   userId, OAuthProvider.Github.ToString());

            return(Redirect("/"));
        }