几个核心要点
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 userif (responseJson.ContainsKey("access_token")){// Build a new ClaimsPrincipal with the selected schemevar 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 locationNavigationManager.NavigateTo("/");}
设置了验证的状态以后,页面上 Authorized 这样的UI部分才可以正常显示
<ul class="inline-navigation"><AuthorizeView><Authorized>