Barry
Barry

Reputation: 415

MicrosoftGraphAuthProvider does not respect [Authenticate("microsoftgraph")] attribute

We have implemented the MicrosoftGraphAuthProvider and it is all set up correctly as we have added an endpoint to output the authorized user's credentials using the following:

 if (!IsAuthenticated) return null;
 var session = this.Request.GetSession(true);
 return session.ToJson();

This outputs my user, with the provider as microsoftgraph. Great, everything as expected.

However, when we add the authorization attribute:

 [Authenticate("microsoftgraph")]

It returns a 401 and acts as if we are not logged in at all. All ss-id and ss-pid are sent in headers correctly, but it still returns a 401.

However, elsewhere in the system, we are using this same method to limit to API key auths

  [Authenticate("apikey")]

We currently have 3 IAuthProviders loaded into the API.

Is there an issue in the provider itself or is there a different methodology behind limiting a service to microsfoftgraph provider?

Upvotes: 1

Views: 52

Answers (1)

mythz
mythz

Reputation: 143339

When you use an Auth Provider name, e.g:

[Authenticate("microsoftgraph")]

It tells ServiceStack to check with that registered AuthProvider to determine whether it thinks user is Authenticated which it does by calling its IsAuthorized() method, MicrosoftGraphAuthProvider doesn't have one defined so it uses its base OAuthProvider implementation:

public override bool IsAuthorized(IAuthSession session, IAuthTokens tokens, Authenticate request = null)
{
    if (request != null)
    {
        if (!LoginMatchesSession(session, request.UserName)) return false;
    }

    return session != null && session.IsAuthenticated && !string.IsNullOrEmpty(tokens?.AccessTokenSecret);
}

You can override this behavior by either overriding the AuthProvider and implementing IsAuthorized or by overriding your Custom UserSession and overriding IsAuthorized(provider), e.g:

public class MyUserSession : AuthUserSession
{
    public override bool IsAuthorized(string provider)
    {
        if (provider == MicrosoftGraphAuthProvider.Name)
            return IsAuthenticated && AuthProvider == provider;
        return base.IsAuthorized(provider);
    }
}

Upvotes: 1

Related Questions