手动验证 Azure AD 并设置登录状态

 几个核心要点

1. client_id,client_secret,username,password 是必须要的

2. 通过 https://login.microsoftonline.com/...... 提交参数,成功就可以拿到 token

3. 自定义一个 CustomAuthenticationStateProvider 类继承自抽象类 AuthenticationStateProvider,自己写修改当前验证状态的方法

    public class CustomAuthenticationStateProvider : AuthenticationStateProvider
    {
        private AuthenticationState _authenticationState;

        public CustomAuthenticationStateProvider()
        {
            var identity = new ClaimsIdentity();
            _authenticationState = new AuthenticationState(new ClaimsPrincipal(identity));
        }

        public override Task<AuthenticationState> GetAuthenticationStateAsync()
        {
            return Task.FromResult(_authenticationState);
        }

        public void SetAuthenticationState(ClaimsPrincipal user)
        {
            var authenticationState = new AuthenticationState(user);
            NotifyAuthenticationStateChanged(Task.FromResult(authenticationState));
            _authenticationState = authenticationState;
        }
    }
        var requestBody = new Dictionary<string, string>
        {
            { "grant_type", "password" },
            { "client_id", Configuration["SupportAgentAuth:ClientId"] },
            { "client_secret", Configuration["SupportAgentAuth:ClientSecret"] },
            { "scope", "openid offline_access" },
            { "username", "xxxxxx" },
            { "password", "yyyyyy" }
        };

        var response = await httpClient.PostAsync($"https://login.microsoftonline.com/{Configuration["SupportAgentAuth:TenantId"]}/oauth2/v2.0/token", 
            new FormUrlEncodedContent(requestBody));
        var responseContent = await response.Content.ReadAsStringAsync();
        var responseJson = JObject.Parse(responseContent);

        // validate user
        if (responseJson.ContainsKey("access_token"))
        {
            // Build a new ClaimsPrincipal with the selected scheme
            var identity = new ClaimsIdentity("SupportAgentAuth");
            identity.AddClaim(new Claim(ClaimTypes.Name, "xxxxxx"));
            var principal = new ClaimsPrincipal(identity);
            var customAuthStateProvider = (CustomAuthenticationStateProvider)AuthenticationStateProvider;
            customAuthStateProvider.SetAuthenticationState(principal);
            // Redirect to home page or another desired location
            NavigationManager.NavigateTo("/");
        }

 设置了验证的状态以后,页面上 Authorized 这样的UI部分才可以正常显示 

    <ul class="inline-navigation">
        <AuthorizeView>
            <Authorized>

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值