c# - Azure Web应用程序授权: session variables for auth/me

标签 c# azure

我是 Azure Web 身份验证新手,想知道我做错了什么?

Home/index 是默认路由。

我有这个函数捕获/.auth/me 信息:

var mobileClient = new WindowsAzure.MobileServiceClient(functionAppBaseUrl);
        $(document).ready(function () {
            mobileClient.invokeApi(`${functionAppBaseUrl}.auth/me`,
                {
                    method: 'GET',
                    headers: {
                        'accept': 'application/json',
                        'content-type': 'application/json'
                    }
                })
                .then(function (response) {
                    console.log(`Response from .auth/me: ${response.responseText}`);
                    $.ajax({
                        type: "POST",
                        url: '@Url.Action("Auth", "Home")',
                        dataType: 'json',
                        data: { login: JSON.stringify(response) },
                        success: function () {
                            console.log("Success Post");
                        },
                        error: function () {
                            console.log("Post Failed");
                        }

                    });
                }, function (error) {
                    console.log(`Error from .auth/me: ${JSON.stringify(error)}`);
                });
        });

成功后,会将数据发布到家庭 Controller 中的 Auth/Home。

 [HttpPost]
        public IActionResult Auth(ExternalLogin login)
        {
            string userRole;
            var role = _context.Employees.Where(x => x.id == login.id)
                        .Select(x => x.HrFlag)
                        .FirstOrDefault();
            if (role == true)
                userRole = "hr";
            else
                userRole = "employee";

            var empId = _context.Employees.Where(x => x.id== login.id)
                        .Select(x => x.EmployeeId)
                        .FirstOrDefault();

            HttpContext.Session.SetString("user_id", login.id);
            HttpContext.Session.SetString("expiry_on", login.ExpiresOn.ToShortTimeString());
            HttpContext.Session.SetString("access_token", login.AccessToken);
            HttpContext.Session.SetString("user_role", userRole);
            HttpContext.Session.SetString("empId", empId.ToString());

            return View(nameof(HomeHr));
        }

然后它将 ajax 调用(从/auth/me)传递的值获取到模型中,然后我设置 session 变量。然后我在layout.cshtml和home.cshtml中调用它们

布局.cshtml:

@using Microsoft.AspNetCore.Http;

@inject IHttpContextAccessor HttpContextAccessor
@{ var empId = Context.Session.GetString("empId");}
 <a class="dropdown-item" href="@Url.Action("EditHr", "Home", new { id = empId })">My Profile</a>
                    @if (Context.Session.GetString("user_role") == "hr")
                    {
                        <a class="dropdown-item" href="@Url.Action("employees", "Home")">Employees</a>

外部登录模型

public class ExternalLogin
    {
        [JsonProperty("access_token", NullValueHandling = NullValueHandling.Ignore)]
        public string AccessToken { get; set; }
        [JsonProperty("provider_name", NullValueHandling = NullValueHandling.Ignore)]
        public string ProviderName { get; set; }
        [JsonProperty("user_id", NullValueHandling = NullValueHandling.Ignore)]
        public string Id{ get; set; }
        [JsonProperty("user_claims", NullValueHandling = NullValueHandling.Ignore)]
        public AuthUserClaim[] UserClaims { get; set; }
        [JsonProperty("access_token_secret", NullValueHandling = NullValueHandling.Ignore)]
        public string AccessTokenSecret { get; set; }
        [JsonProperty("authentication_token", NullValueHandling = NullValueHandling.Ignore)]
        public string AuthenticationToken { get; set; }
        [JsonProperty("expires_on", NullValueHandling = NullValueHandling.Ignore)]
        public DateTime ExpiresOn { get; set; }
        [JsonProperty("id_token", NullValueHandling = NullValueHandling.Ignore)]
        public string IdToken { get; set; }
        [JsonProperty("refresh_token", NullValueHandling = NullValueHandling.Ignore)]
        public string RefreshToken { get; set; }
    }

我试图实现的一般流程: 当用户访问azure托管网站时:用户登录,重定向到我的应用程序home/index,/.auth/me捕获并显示在控制台中,ajax帖子(/.auth/me)到Home/Auth,设置 session 变量并使它们保持事件状态,直到 expiry_on = datetime.now。

谢谢!

最佳答案

所以这比预想的要简单得多。不知道为什么没有这方面的文档,也许是因为这是一个显而易见的答案,哈哈。

以下是我从 Azure 身份验证获取重定向上的 .auth/me json 所做的操作。

进行了 ajax 调用。

$(document).ready(function () {

        $.ajax({
            type: "GET",
            url: 'https://mcintranet-stage.azurewebsites.net/.auth/me',
            success: function (response) {
                console.log(response);
                Login(response);
            },
            error: function () {
                console.log("Post Failed");
            }

        });

    });

然后将对象 - 从 .auth/me - 传递到函数服务器端:

    function Login(responseData) {
        $.ajax({
            type: "POST",
            url: `@Url.Action("Login", "Account")`,
            data: responseData[0],
            success: function (response) {
                if (response == "Success") {
                    console.log("Success Post");
                    window.location.href = window.location.origin + "/Home/HomeHr";
                }
                else if (response == "Failed")
                    console.log("Failed Post");
            },
            error: function () {
                console.log("Post Failed");
            }
        })
    }

服务器端设置授权

[HttpPost]
        public string Login(ExternalLogin login)
        {
            var userToken = login.access_token;
            var empId = login.user_id;
            var emp = _context.Employees.Where(x => x.Id== empId).FirstOrDefault();

            if (UserExists(empId) == true)
            {
                if (empId != null)
                {
                    HttpContext.Session.SetString("username", empId);
                    HttpContext.Session.SetString("empId", emp.EmployeeId.ToString());
                    HttpContext.Session.SetString("user_role", IsInRole(emp.Id));
                    HttpContext.Session.SetString("name", emp.Fullname);

                }
                return "Success";
            }
            return "Failed";
        }

关于c# - Azure Web应用程序授权: session variables for auth/me,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53838184/

相关文章:

c# - RSA公钥解密c#(powershell)

c# - 当我为类的字段赋值时,添加一些与特定字段关联的元数据?

azure - 将数据从一个 azure 帐户的容器复制到另一个 azure 帐户的容器

c# - 属性注入(inject)的值在构造函数中为空

c# - 如何从 Linux 上运行的 .NET Core 应用程序关闭计算机

Azure函数: how to set CORS via automation?

azure - 无法通过 Bash 删除文件

azure - "The deserializer has no knowledge of any type that maps to this name..."上的 Service Fabric 错误

php - 适用于 PHP 的 Azure SDK 和适用于 Windows Server 1.1 的服务总线

c# - 在 MVC 4 Razor 中加载页面时从数据库加载数据的正确方法