我对Azure AD Graph和身份验证过程都很陌生。我能够在使用.NET MVC应用程序的本示例中使用Azure AD Graph客户端合并单点登录:https://github.com/Azure-Samples/active-directory-dotnet-graphapi-web
我的困境是即使我已经对我的会话进行了身份验证,它仍然要求我再次登录以执行以下控制器中的操作:
// TODO: Declare member variables here:
int mIndex;
ProgressBar progressBar;
TextView textView;
TextView tvScore;
TextView tvHighScore;
Button btnFalse;
Button btnTrue;
Random randomGenerator;
TrueFalse trueFalse;
int question;
int mScore;
int mHighScore;
// TODO: Uncomment to create question bank
private TrueFalse[] mQuestionBank = new TrueFalse[] {
new TrueFalse(R.string.question_1, true),
new TrueFalse(R.string.question_2, true),
new TrueFalse(R.string.question_3, true),
new TrueFalse(R.string.question_4, true),
new TrueFalse(R.string.question_5, true),
new TrueFalse(R.string.question_6, false),
new TrueFalse(R.string.question_7, true),
new TrueFalse(R.string.question_8, false),
new TrueFalse(R.string.question_9, true),
new TrueFalse(R.string.question_10, true),
new TrueFalse(R.string.question_11, false),
new TrueFalse(R.string.question_12, false),
new TrueFalse(R.string.question_13,true)
};
// TODO: Declare constants here
final int PROGRESS_BAR_INCREAMENT =(int) Math.ceil(100.0 / mQuestionBank.length);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar = (ProgressBar)findViewById(R.id.progress_bar);
btnFalse = (Button)findViewById(R.id.false_button);
btnTrue = (Button)findViewById(R.id.true_button);
tvScore = (TextView)findViewById(R.id.score);
tvHighScore = (TextView)findViewById(R.id.textView);
textView = (TextView)findViewById(R.id.question_text_view);
randomGenerator = new Random();
trueFalse = new TrueFalse(R.string.question_1, true);
question = mQuestionBank[mIndex].getQuestion();
textView.setText(question);
// click Listeners
btnFalse.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
checkAnswer(false);
updateQuestion();
}
});
btnTrue.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
checkAnswer(true);
updateQuestion();
}
});
}
public void updateQuestion(){
mIndex = (mIndex + 1) % mQuestionBank.length;
question = mQuestionBank[mIndex].getQuestion();
textView.setText(question);
progressBar.incrementProgressBy(PROGRESS_BAR_INCREAMENT);
if (mIndex == 0){
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("یاریەکە تەواو بوو !");
alert.setCancelable(false);
alert.setMessage("توانیت " + mScore +"خاڵ بەدەست بێنیت ");
alert.setPositiveButton("دەرچوون", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alert.show();
}
}
private void checkAnswer(boolean userSelection){
boolean correctAnswer = mQuestionBank[mIndex].isTrueOrfalse();
if (userSelection == correctAnswer){
Toast.makeText(this,R.string.correct_toast,Toast.LENGTH_SHORT).show();
mScore++;
tvScore.setText(mScore + " /13");
}else{
Toast.makeText(this,R.string.incorrect_toast,Toast.LENGTH_SHORT).show();
}
if (mScore > mHighScore){
tvHighScore.setText("بەرزترین خاڵ : " + mScore);
}else if (mScore < mHighScore){
tvHighScore.setText(mHighScore);
}
readFile();
saveFile();
}
private void saveFile(){
int highScoreTextView = mHighScore;
SharedPreferences sharedPref = getSharedPreferences("MY_FILE", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("HIGH SCORE = ", highScoreTextView);
editor.commit();
Toast.makeText(this,"SAVED",Toast.LENGTH_SHORT).show();
}
private void readFile(){
SharedPreferences sharedPref = getSharedPreferences("MY_FILE", Activity.MODE_PRIVATE);
int name = sharedPref.getInt("name", -1 );
tvHighScore.setText("بەرزترین خاڵ :"+ name);
}
我得到的错误是:
&#39; /&#39;中的服务器错误应用 需要授权
黄色框中有以下代码行:
public ActionResult Test()
{
if (Request.QueryString["reauth"] == "True")
{
//Send an OpenID Connect sign -in request to get a new set of tokens.
// If the user still has a valid session with Azure AD, they will not be prompted for their credentials.
// The OpenID Connect middleware will return to this controller after the sign-in response has been handled.
HttpContext.GetOwinContext()
.Authentication.Challenge(OpenIdConnectAuthenticationDefaults.AuthenticationType);
}
// Access the Azure Active Directory Graph Client
ActiveDirectoryClient client = AuthenticationHelper.GetActiveDirectoryClient();
// Obtain the current user's AD objectId
string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
// Query and obtain the current user object from the Azure AD Graph Client
User user = (User)client.Users.
Where(u => u.ObjectId
.Equals(userObjectID, StringComparison.CurrentCultureIgnoreCase)).
ExecuteSingleAsync().
Result;
// Get the employee Id from Azure AD (via a directory extension)
IReadOnlyDictionary<string, object> extendedProperty = user.GetExtendedProperties();
object extendedProp = extendedProperty["extension_ExtensionId_employeeID"];
// Hash the employee Id
var empId = PasswordHash.ArgonHashString(extendedProp.ToString(), PasswordHash.StrengthArgon.Moderate);
// Send to the view for testing only
ViewBag.EmployeeName = user.DisplayName;
ViewBag.EmployeeEmail = user.Mail;
ViewBag.EmployeeId = empId;
return View();
}
由于我对身份验证工作相当新,我需要一些关于如何获取当前会话令牌的指导,以便我不会收到此错误。
我正在使用Azure AD Graph,因为我在Azure中获取了一个我无法通过Microsoft Graph获取的特定目录扩展(现在并且基于我当前的截止日期)
任何建议都会有所帮助。
答案 0 :(得分:1)
如果令牌为空,则用户需要重新授权。如code sample所示,您可以使用try catch语句来处理异常:
try
{
}
catch (Exception e)
{
//
// The user needs to re-authorize. Show them a message to that effect.
//
ViewBag.ErrorMessage = "AuthorizationRequired";
return View(userList);
}
向用户显示消息(例如,“用户”视图文件夹中的Index.cshtml):
@if (ViewBag.ErrorMessage == "AuthorizationRequired")
{
<p>You have to sign-in to see Users. Click @Html.ActionLink("here", "Index", "Users", new { reauth = true }, null) to sign-in.</p>
}
如果您想直接发送OpenID Connect登录请求以获取一组新令牌而不是向用户显示错误消息,您可以使用:
catch (Exception e)
{
....
HttpContext.GetOwinContext()
.Authentication.Challenge(new AuthenticationProperties {RedirectUri = "/"},
OpenIdConnectAuthenticationDefaults.AuthenticationType);
.....
}
如果用户仍与Azure AD建立有效会话,则系统不会提示他们输入凭据。在处理登录响应后,OpenID Connect中间件将返回当前控制器。