本文整理汇总了C#中DotNetOpenAuth.OAuth2.AuthorizationState类的典型用法代码示例。如果您正苦于以下问题:C# AuthorizationState类的具体用法?C# AuthorizationState怎么用?C# AuthorizationState使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
AuthorizationState类属于DotNetOpenAuth.OAuth2命名空间,在下文中一共展示了AuthorizationState类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: AuthorizationCodeGrant
public void AuthorizationCodeGrant() {
var coordinator = new OAuth2Coordinator<WebServerClient>(
AuthorizationServerDescription,
AuthorizationServerMock,
new WebServerClient(AuthorizationServerDescription),
client => {
var authState = new AuthorizationState {
Callback = ClientCallback,
};
client.PrepareRequestUserAuthorization(authState).Respond();
var result = client.ProcessUserAuthorization();
Assert.IsNotNullOrEmpty(result.AccessToken);
Assert.IsNotNullOrEmpty(result.RefreshToken);
},
server => {
var request = server.ReadAuthorizationRequest();
server.ApproveAuthorizationRequest(request, ResourceOwnerUsername);
var tokenRequest = server.ReadAccessTokenRequest();
IAccessTokenRequest accessTokenRequest = tokenRequest;
Assert.IsTrue(accessTokenRequest.ClientAuthenticated);
var tokenResponse = server.PrepareAccessTokenResponse(tokenRequest);
server.Channel.Respond(tokenResponse);
});
coordinator.Run();
}
示例2: CheckForValidAccessTokenTest
public void CheckForValidAccessTokenTest()
{
int accessTokenCounter = 1;
var state = new AuthorizationState();
var client = new NativeApplicationClient(new Uri("http://example.com"));
var auth = new OAuth2Authenticator<NativeApplicationClient>(
client, (clt) =>
{
// Load a "cached" access token.
state.AccessToken = "token" + (accessTokenCounter++);
return state;
});
// Check that the initial state is null.
Assert.IsNull(auth.State);
// Check that the state was set when .LoadAccessToken() is called.
auth.LoadAccessToken();
Assert.AreEqual(state, auth.State);
Assert.AreEqual("token1", auth.State.AccessToken);
// Check that it wont be set again.
auth.LoadAccessToken();
Assert.AreEqual("token1", auth.State.AccessToken);
// Check that it is set if our state gets invalid.
state.AccessToken = null;
auth.LoadAccessToken();
Assert.AreEqual("token2", auth.State.AccessToken);
}
示例3: NamedAuthorizationState
public NamedAuthorizationState(Guid guid, string name, AuthorizationState authorizationState)
{
Guid = guid;
Name = name;
AuthorizationState = authorizationState;
IsHistorical = true;
}
示例4: ImplicitGrant
public async Task ImplicitGrant() {
var coordinatorClient = new UserAgentClient(AuthorizationServerDescription);
coordinatorClient.ClientCredentialApplicator = null; // implicit grant clients don't need a secret.
Handle(AuthorizationServerDescription.AuthorizationEndpoint).By(
async (req, ct) => {
var server = new AuthorizationServer(AuthorizationServerMock);
var request = await server.ReadAuthorizationRequestAsync(req, ct);
Assert.That(request, Is.Not.Null);
IAccessTokenRequest accessTokenRequest = (EndUserAuthorizationImplicitRequest)request;
Assert.That(accessTokenRequest.ClientAuthenticated, Is.False);
var response = server.PrepareApproveAuthorizationRequest(request, ResourceOwnerUsername);
return await server.Channel.PrepareResponseAsync(response, ct);
});
{
var client = new UserAgentClient(AuthorizationServerDescription, ClientId, ClientSecret, this.HostFactories);
var authState = new AuthorizationState(TestScopes) { Callback = ClientCallback, };
var request = client.PrepareRequestUserAuthorization(authState, implicitResponseType: true);
Assert.That(request.ResponseType, Is.EqualTo(EndUserAuthorizationResponseType.AccessToken));
var authRequestRedirect = await client.Channel.PrepareResponseAsync(request);
Uri authRequestResponse;
this.HostFactories.AllowAutoRedirects = false;
using (var httpClient = this.HostFactories.CreateHttpClient()) {
using (var httpResponse = await httpClient.GetAsync(authRequestRedirect.Headers.Location)) {
authRequestResponse = httpResponse.Headers.Location;
}
}
var incoming =
await client.Channel.ReadFromRequestAsync(new HttpRequestMessage(HttpMethod.Get, authRequestResponse), CancellationToken.None);
var result = await client.ProcessUserAuthorizationAsync(authState, incoming, CancellationToken.None);
Assert.That(result.AccessToken, Is.Not.Null.And.Not.Empty);
Assert.That(result.RefreshToken, Is.Null);
}
}
示例5: GetAnalyticsService
/// <summary>
/// Return Analytics Service object
/// </summary>
/// <returns>Analytics Service object</returns>
public static AnalyticsService GetAnalyticsService()
{
var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description);
provider.ClientIdentifier = Settings.ClientIdentifier;
provider.ClientSecret = Settings.ClientSecret;
if (string.IsNullOrWhiteSpace(provider.ClientIdentifier))
{
throw new Exception("Client identifier not found");
}
if (string.IsNullOrWhiteSpace(provider.ClientSecret))
{
throw new Exception("Client secret not found");
}
string refreshToken = Settings.RefreshToken;
if (string.IsNullOrWhiteSpace(refreshToken))
{
throw new Exception("Refresh token not found");
}
var request = HttpContext.Current.Request;
var authenticator = new OAuth2Authenticator<NativeApplicationClient>(provider, (arg) =>
{
IAuthorizationState state = new AuthorizationState(new[] { "https://www.googleapis.com/auth/analytics.readonly" });
state.Callback = new Uri(string.Format("{0}://{1}{2}/GoogleAnalytics/Callback", request.Url.Scheme, request.Url.Host, request.Url.Port == 80 ? string.Empty : ":" + request.Url.Port));
state.RefreshToken = refreshToken;
var result = arg.RefreshToken(state);
return state;
});
return new AnalyticsService(authenticator);
}
示例6: DecodeRefreshToken
public void DecodeRefreshToken() {
var refreshTokenSource = new TaskCompletionSource<string>();
var coordinator = new OAuth2Coordinator<WebServerClient>(
AuthorizationServerDescription,
AuthorizationServerMock,
new WebServerClient(AuthorizationServerDescription),
client => {
try {
var authState = new AuthorizationState(TestScopes) {
Callback = ClientCallback,
};
client.PrepareRequestUserAuthorization(authState).Respond();
var result = client.ProcessUserAuthorization();
Assert.That(result.AccessToken, Is.Not.Null.And.Not.Empty);
Assert.That(result.RefreshToken, Is.Not.Null.And.Not.Empty);
refreshTokenSource.SetResult(result.RefreshToken);
} catch {
refreshTokenSource.TrySetCanceled();
}
},
server => {
var request = server.ReadAuthorizationRequest();
Assert.That(request, Is.Not.Null);
server.ApproveAuthorizationRequest(request, ResourceOwnerUsername);
server.HandleTokenRequest().Respond();
var authorization = server.DecodeRefreshToken(refreshTokenSource.Task.Result);
Assert.That(authorization, Is.Not.Null);
Assert.That(authorization.User, Is.EqualTo(ResourceOwnerUsername));
});
coordinator.Run();
}
示例7: AuthorizationCodeGrant
public void AuthorizationCodeGrant() {
var coordinator = new OAuth2Coordinator<UserAgentClient>(
AuthorizationServerDescription,
AuthorizationServerMock,
new UserAgentClient(AuthorizationServerDescription),
client => {
var authState = new AuthorizationState(TestScopes) {
Callback = ClientCallback,
};
var request = client.PrepareRequestUserAuthorization(authState);
Assert.AreEqual(EndUserAuthorizationResponseType.AuthorizationCode, request.ResponseType);
client.Channel.Respond(request);
var incoming = client.Channel.ReadFromRequest();
var result = client.ProcessUserAuthorization(authState, incoming);
Assert.That(result.AccessToken, Is.Not.Null.And.Not.Empty);
Assert.That(result.RefreshToken, Is.Not.Null.And.Not.Empty);
},
server => {
var request = server.ReadAuthorizationRequest();
Assert.That(request, Is.Not.Null);
server.ApproveAuthorizationRequest(request, ResourceOwnerUsername);
server.HandleTokenRequest().Respond();
});
coordinator.Run();
}
示例8: ImplicitGrant
public void ImplicitGrant() {
var coordinatorClient = new UserAgentClient(AuthorizationServerDescription);
var coordinator = new OAuth2Coordinator<UserAgentClient>(
AuthorizationServerDescription,
AuthorizationServerMock,
coordinatorClient,
client => {
var authState = new AuthorizationState {
Callback = ClientCallback,
};
var request = client.PrepareRequestUserAuthorization(authState, implicitResponseType: true);
Assert.AreEqual(EndUserAuthorizationResponseType.AccessToken, request.ResponseType);
client.Channel.Respond(request);
var incoming = client.Channel.ReadFromRequest();
var result = client.ProcessUserAuthorization(authState, incoming);
Assert.IsNotNullOrEmpty(result.AccessToken);
Assert.IsNull(result.RefreshToken);
},
server => {
var request = server.ReadAuthorizationRequest();
IAccessTokenRequest accessTokenRequest = (EndUserAuthorizationImplicitRequest)request;
Assert.IsFalse(accessTokenRequest.ClientAuthenticated);
server.ApproveAuthorizationRequest(request, ResourceOwnerUsername);
});
coordinatorClient.ClientSecret = null; // implicit grant clients don't need a secret.
coordinator.Run();
}
示例9: Authorize
public void Authorize(ref IAuthorizationState authorization, string refreshToken)
{
if ((authorization == null))
{
authorization = new AuthorizationState
{
Callback = _redirectUri,
RefreshToken = refreshToken
};
}
bool refreshFailed = false;
if (AccessTokenHasToBeRefreshed(authorization))
{
try
{
refreshFailed = !RefreshAuthorization(authorization);
}
catch (ProtocolException)
{
//The refreshtoken is not valid anymore
}
}
if (authorization.AccessToken == null || refreshFailed)
{
using (var loginDialog = new LoginForm(_redirectUri))
{
loginDialog.AuthorizationUri = GetAuthorizationUri(authorization);
loginDialog.ShowDialog();
ProcessUserAuthorization(loginDialog.AuthorizationUri, authorization);
}
}
}
示例10: RequestUserAuthorization
/// <summary>
/// Generates a URL that the user's browser can be directed to in order to authorize
/// this client to access protected data at some resource server.
/// </summary>
/// <param name="scope">The scope of authorized access requested.</param>
/// <param name="state">The client state that should be returned with the authorization response.</param>
/// <param name="returnTo">The URL that the authorization response should be sent to via a user-agent redirect.</param>
/// <returns>
/// A fully-qualified URL suitable to initiate the authorization flow.
/// </returns>
public Uri RequestUserAuthorization(IEnumerable<string> scope = null, string state = null, Uri returnTo = null) {
var authorization = new AuthorizationState(scope) {
Callback = returnTo,
};
return this.RequestUserAuthorization(authorization);
}
示例11: ProcessUserAuthorization
/// <summary>
/// Scans the incoming request for an authorization response message.
/// </summary>
/// <param name="actualRedirectUrl">The actual URL of the incoming HTTP request.</param>
/// <param name="authorizationState">The authorization.</param>
/// <returns>The granted authorization, or <c>null</c> if the incoming HTTP request did not contain an authorization server response or authorization was rejected.</returns>
public IAuthorizationState ProcessUserAuthorization(Uri actualRedirectUrl, IAuthorizationState authorizationState = null) {
Contract.Requires<ArgumentNullException>(actualRedirectUrl != null);
if (authorizationState == null) {
authorizationState = new AuthorizationState();
}
var carrier = new HttpRequestInfo("GET", actualRedirectUrl, actualRedirectUrl.PathAndQuery, new System.Net.WebHeaderCollection(), null);
IDirectedProtocolMessage response = this.Channel.ReadFromRequest(carrier);
if (response == null) {
return null;
}
EndUserAuthorizationSuccessAccessTokenResponse accessTokenSuccess;
EndUserAuthorizationSuccessAuthCodeResponse authCodeSuccess;
EndUserAuthorizationFailedResponse failure;
if ((accessTokenSuccess = response as EndUserAuthorizationSuccessAccessTokenResponse) != null) {
UpdateAuthorizationWithResponse(authorizationState, accessTokenSuccess);
} else if ((authCodeSuccess = response as EndUserAuthorizationSuccessAuthCodeResponse) != null) {
this.UpdateAuthorizationWithResponse(authorizationState, authCodeSuccess);
} else if ((failure = response as EndUserAuthorizationFailedResponse) != null) {
authorizationState.Delete();
return null;
}
return authorizationState;
}
示例12: PrepareRequestUserAuthorization
/// <summary>
/// Prepares a request for user authorization from an authorization server.
/// </summary>
/// <param name="scopes">The scope of authorized access requested.</param>
/// <param name="state">The state of the client that should be sent back with the authorization response.</param>
/// <param name="returnTo">The URL the authorization server should redirect the browser (typically on this site) to when the authorization is completed. If null, the current request's URL will be used.</param>
/// <returns>The authorization request.</returns>
public OutgoingWebResponse PrepareRequestUserAuthorization(IEnumerable<string> scopes = null, string state = null, Uri returnTo = null)
{
var authorizationState = new AuthorizationState(scopes) {
Callback = returnTo,
};
return this.PrepareRequestUserAuthorization(authorizationState, state);
}
示例13: Create
/// <summary>
/// Create an HTTP Handler for client only auth.
/// </summary>
/// <param name="authBaseUri">The base auth URI e.g. https://auth.alitudeangel.com</param>
/// <param name="clientId">Your client ID</param>
/// <param name="clientSecret">Your client secret</param>
/// <param name="scopes">Requested scopes</param>
/// <param name="existingState">(optional) An existing state object from a previous session. May be null.</param>
public static ClientHandlerInfo Create(string authBaseUri,
string clientId,
string clientSecret,
IEnumerable<string> scopes,
AuthorizationState existingState = null
)
{
return Create(authBaseUri, clientId, clientSecret, scopes, existingState, false, null, null);
}
示例14: NamedAuthorizationState
public NamedAuthorizationState(Guid guid, string name, AuthorizationState authorizationState, bool shouldRefresh, Uri url)
{
Guid = guid;
Name = name;
AuthorizationState = authorizationState;
ShouldRefresh = shouldRefresh;
Url = url;
IsHistorical = true;
}
示例15: DelegateTest
public void DelegateTest()
{
var state = new AuthorizationState() { AccessToken = "Test" };
var client = new NativeApplicationClient(new Uri("http://example.com"));
var auth = new OAuth2Authenticator<NativeApplicationClient>(client, (clt) => state);
// Check that the state was set.
auth.LoadAccessToken();
Assert.AreEqual(state, auth.State);
}