使用OpenIDConnect无法从HttpContext获取AAD的访问令牌

时间:2019-07-05 14:16:56

标签: azure azure-active-directory openid-connect

我已配置Open ID Connect与Azure AD。我希望从AAD检索access_token。目前,我只能检索id_token。我已将Azure Active Directory应用程序注册配置为同时包含access_token和id_token。

我已将Azure Active Directory应用程序注册配置为同时包含access_token和id_token。 我也尝试过从标头中检索令牌,但没有任何运气。

Startup.cs

services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
                .AddAzureAD(options => Configuration.Bind("AzureAD", options));
            services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, options =>
            {
                options.Authority = options.Authority + "/v2.0/";
                options.TokenValidationParameters.ValidateIssuer = true;
                options.ResponseType = OpenIdConnectResponseType.CodeIdToken;
                options.SaveTokens = true;
            });

MyController.cs

if(User.Identity.IsAuthenticated)
            {
                string accessToken = await HttpContext.GetTokenAsync("access_token");
                string idToken = await HttpContext.GetTokenAsync("id_token");
}

appsettings.json

"AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "Domain": "mydomain",
    "TenantId": "organizations",
    "ClientId": "myclientid",
    "ClientSecret": "myclientsecret",
    "CallbackPath": "/signin-oidc",
    "SignedOutCallbackPath ": "/signout-callback-oidc"
  }

2 个答案:

答案 0 :(得分:0)

根据documentation

,您将需要使用CodeIdTokenToken响应类型

options.ResponseType = OpenIdConnectResponseType.CodeIdTokenToken;

答案 1 :(得分:0)

我设法解决了这个问题。对于可能遇到此问题的任何人,请将响应类型设置为 Code 即可获取id_token和access_token。这将指示Open ID Connect使用授权代码流。

   //Service Class
    public class BroadcastService extends Service {
        private Intent intent;
        public static final String BROADCAST_ACTION = "com.xyz";

        private Handler handler = new Handler();
        private long initial_time;
        long timeInMilliseconds = 0L;


        @Override
        public void onCreate() {
            super.onCreate();
            initial_time = SystemClock.uptimeMillis();
            intent = new Intent(BROADCAST_ACTION);
            handler.removeCallbacks(sendUpdatesToUI);
            handler.postDelayed(sendUpdatesToUI, 1000); // 1 second
        }

        private Runnable sendUpdatesToUI = new Runnable() {
            public void run() {
                DisplayLoggingInfo();
                handler.postDelayed(this, 1000); // 1 seconds
            }
        };

        private void DisplayLoggingInfo() {

            timeInMilliseconds = SystemClock.uptimeMillis() - initial_time;

            int timer = (int) timeInMilliseconds / 1000;
            intent.putExtra("time", timer);
            sendBroadcast(intent);

        }

        @Override
        public void onDestroy() {
            super.onDestroy();
            handler.removeCallbacks(sendUpdatesToUI);

        }

        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }
    }

    // Java class which runs when ride is active and shows the timer 

    public class RideIsActive extends AppCompatActivity {


        private TextView timer;
        private Button endRide;

        Intent intent;
        long timeSwapBuff = 0L;
        long updatedTime = 0L;

        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_ride_is_active);

            timer  = findViewById(R.id.timer);
            endRide = findViewById(R.id.endRide);

            startService(new Intent(this, BroadcastService.class));

            endRide.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    unregisterReceiver(broadcastReceiver);
                    stopService(intent);
                }
            });

        }

        private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {

                updateUI(intent);
            }
        };

        private void updateUI(Intent intent) {
            int time = intent.getIntExtra("time", 0);

            Log.d("Hello", "Time " + time);

            int hrs = time/3600;
            int mins = time / 60;
            int secs = time % 60;
            timer.setText(String.format("%02d", hrs) + ":" + String.format("%02d", mins) + ":"
                    + String.format("%02d", secs));
        }

        @Override
        protected void onResume() {
            super.onResume();
            registerReceiver(broadcastReceiver, new IntentFilter(BroadcastService.BROADCAST_ACTION));
        }



    //Layout

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".RideIsActive">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/timer"
            android:layout_centerInParent="true"
            android:textSize="25dp"
            android:textColor="#000000"
            android:text="00:00:00"/>

        <Button
            android:id="@+id/endRide"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:text="End Ride"
            android:textColor="@color/textBlack"
            android:background="@color/quantum_orange500"/>


    </RelativeLayout>