/// <summary> /// Initializes a new instance of the <see cref="AutomatedUserAuthorizationCheckResponse" /> class. /// </summary> /// <param name="accessRequest">The access token request.</param> /// <param name="approved">A value indicating whether the authorization should be approved.</param> /// <param name="canonicalUserName"> /// Canonical username of the authorizing user (resource owner), as the resource server would recognize it. /// Ignored if <paramref name="approved"/> is false. /// </param> public AutomatedUserAuthorizationCheckResponse(IAccessTokenRequest accessRequest, bool approved, string canonicalUserName) : base(accessRequest, approved) { if (approved) { Requires.NotNullOrEmpty(canonicalUserName, "canonicalUserName"); } this.CanonicalUserName = canonicalUserName; }
/// <summary> /// Obtains parameters to go into the formulation of an access token. /// </summary> /// <param name="accessTokenRequestMessage">Details regarding the resources that the access token will grant access to, and the identity of the client /// that will receive that access. /// Based on this information the receiving resource server can be determined and the lifetime of the access /// token can be set based on the sensitivity of the resources.</param> /// <returns> /// A non-null parameters instance that DotNetOpenAuth will dispose after it has been used. /// </returns> public AccessTokenParameters GetAccessTokenParameters(IAccessTokenRequest accessTokenRequestMessage) { return new AccessTokenParameters() { // For this sample, we assume just one resource server. // If this authorization server needs to mint access tokens for more than one resource server, // we'd look at the request message passed to us and decide which public key to return. ResourceServerEncryptionKey = OAuthResourceServer.CreateRSA(), }; }
/// <summary> /// Acquires the access token and related parameters that go into the formulation of the token endpoint's response to a client. /// </summary> /// <param name="accessTokenRequestMessage">Details regarding the resources that the access token will grant access to, and the identity of the client /// that will receive that access. /// Based on this information the receiving resource server can be determined and the lifetime of the access /// token can be set based on the sensitivity of the resources.</param> /// <returns> /// A non-null parameters instance that DotNetOpenAuth will dispose after it has been used. /// </returns> public AccessTokenResult CreateAccessToken(IAccessTokenRequest accessTokenRequestMessage) { var accessToken = new AuthorizationServerAccessToken(); accessToken.Lifetime = TimeSpan.FromHours(1); accessToken.ResourceServerEncryptionKey = EncryptionKeys.GetResourceServerEncryptionPublicKey(); accessToken.AccessTokenSigningKey = EncryptionKeys.GetAuthorizationServerSigningPrivateKey(); return new AccessTokenResult(accessToken); }
public AccessTokenResult CreateAccessToken(IAccessTokenRequest accessTokenRequestMessage) { var accessToken = new AuthorizationServerAccessToken { Lifetime = TimeSpan.FromDays(30), SymmetricKeyStore = this.CryptoKeyStore, ClientIdentifier = accessTokenRequestMessage.ClientIdentifier }; return new AccessTokenResult(accessToken); }
/// <summary> /// Obtains parameters to go into the formulation of an access token. /// </summary> /// <param name="accessTokenRequestMessage">Details regarding the resources that the access token will grant access to, and the identity of the client /// that will receive that access. /// Based on this information the receiving resource server can be determined and the lifetime of the access /// token can be set based on the sensitivity of the resources.</param> /// <returns> /// A non-null parameters instance that DotNetOpenAuth will dispose after it has been used. /// </returns> public AccessTokenResult CreateAccessToken(IAccessTokenRequest accessTokenRequestMessage) { var accessToken = new AuthorizationServerAccessToken() { // For this sample, we assume just one resource server. // If this authorization server needs to mint access tokens for more than one resource server, // we'd look at the request message passed to us and decide which public key to return. ResourceServerEncryptionKey = OAuthResourceServer.CreateRSA(), }; var result = new AccessTokenResult(accessToken); return result; }
// Generate an access token, given parameters in request that tell use what scopes to include, // and thus what resource's encryption key to use in addition to the authroization server key public AccessTokenResult CreateAccessToken(IAccessTokenRequest accessTokenRequestMessage) { var accessToken = new AuthorizationServerAccessToken {Lifetime = TimeSpan.FromMinutes(10)}; // could parameterize lifetime var targetResource = _resourceRepository.FindWithSupportedScopes(accessTokenRequestMessage.Scope); accessToken.ResourceServerEncryptionKey = targetResource.PublicTokenEncrypter; accessToken.AccessTokenSigningKey = _tokenSigner.GetSigner(); var result = new AccessTokenResult(accessToken); return result; }
public AutomatedAuthorizationCheckResponse CheckAuthorizeClientCredentialsGrant(IAccessTokenRequest accessRequest) { if (accessRequest.ClientAuthenticated) { throw new NotSupportedException(); } else { return new AutomatedAuthorizationCheckResponse(accessRequest, false); } }
/// <summary> /// Acquires the access token and related parameters that go into the formulation of the token endpoint's response to a client. /// </summary> /// <param name="accessTokenRequestMessage">Details regarding the resources that the access token will grant access to, and the identity of the client /// that will receive that access. /// Based on this information the receiving resource server can be determined and the lifetime of the access /// token can be set based on the sensitivity of the resources.</param> /// <returns> /// A non-null parameters instance that DotNetOpenAuth will dispose after it has been used. /// </returns> public AccessTokenResult CreateAccessToken(IAccessTokenRequest accessTokenRequestMessage) { // If your resource server and authorization server are different web apps, // consider using asymmetric keys instead of symmetric ones by setting different // properties on the access token below. var accessToken = new AuthorizationServerAccessToken { Lifetime = TimeSpan.FromHours(1), SymmetricKeyStore = this.CryptoKeyStore, }; var result = new AccessTokenResult(accessToken); return result; }
/// <summary> /// Applies the client identifier and (when applicable) the client authentication to an outbound message. /// </summary> /// <param name="clientIdentifier">The identifier by which the authorization server should recognize this client.</param> /// <param name="request">The outbound message to apply authentication information to.</param> public override void ApplyClientCredential(string clientIdentifier, IAccessTokenRequest request) { var authRequest = request as AuthenticatedClientRequestBase; if (authRequest != null) { // When using network credentials, the client authentication is not done as standard message parts. authRequest.ClientIdentifier = null; authRequest.ClientSecret = null; } }
/// <summary> /// Applies the client identifier and (when applicable) the client authentication to an outbound message. /// </summary> /// <param name="clientIdentifier">The identifier by which the authorization server should recognize this client.</param> /// <param name="request">The outbound message to apply authentication information to.</param> public override void ApplyClientCredential(string clientIdentifier, IAccessTokenRequest request) { var authRequest = request as AuthenticatedClientRequestBase; if (authRequest != null) { if (clientIdentifier != null) { authRequest.ClientSecret = this.secret; } } }
public AccessTokenResult CreateAccessToken(IAccessTokenRequest accessTokenRequestMessage) { var rsa = new RSACryptoServiceProvider(); rsa.ImportCspBlob(Convert.FromBase64String(ConfigurationManager.AppSettings["PrivateAsymmetricKey"])); var accessToken = new AuthorizationServerAccessToken() { AccessTokenSigningKey = rsa, ResourceServerEncryptionKey = rsa, }; var result = new AccessTokenResult(accessToken); result.AllowRefreshToken = false; return result; }
public AutomatedUserAuthorizationCheckResponse CheckAuthorizeResourceOwnerCredentialGrant(string userName, string password, IAccessTokenRequest accessRequest) { if (Membership.ValidateUser(userName, password)) { return new AutomatedUserAuthorizationCheckResponse(accessRequest, true, Membership.GetUser(userName).UserName); } else { return new AutomatedUserAuthorizationCheckResponse(accessRequest, false, null); } }
/// <summary> /// Acquires the access token and related parameters that go into the formulation of the token endpoint's response to a client. /// </summary> /// <param name="accessTokenRequestMessage">Details regarding the resources that the access token will grant access to, and the identity of the client that will receive that access. /// Based on this information the receiving resource server can be determined and the lifetime of the access token can be set based on the sensitivity of the resources. /// </param> /// <returns>A non-null parameters instance that DotNetOpenAuth will dispose after it has been used.</returns> public AccessTokenResult CreateAccessToken(IAccessTokenRequest accessTokenRequestMessage) { AuthorizationServerAccessToken accessToken = new AuthorizationServerAccessToken(); accessToken.Lifetime = TimeSpan.FromMinutes(5); accessToken.ExtraData.Add("userIdentity", "{ user: \"some identity\" }"); //accessToken.Lifetime = TimeSpan.FromSeconds(20); accessToken.ResourceServerEncryptionKey = CreateRsaCryptoServiceProvider(ResourceServerEncryptionPublicKey); accessToken.AccessTokenSigningKey = CreateRsaCryptoServiceProvider(AuthorizationServerSigningPrivateKey); return(new AccessTokenResult(accessToken)); }
/// <summary> /// Acquires the access token and related parameters that go into the formulation of the token endpoint's response to a client. /// </summary> /// <param name="accessTokenRequestMessage">Details regarding the resources that the access token will grant access to, and the identity of the client /// that will receive that access. /// Based on this information the receiving resource server can be determined and the lifetime of the access /// token can be set based on the sensitivity of the resources.</param> /// <returns> /// A non-null parameters instance that DotNetOpenAuth will dispose after it has been used. /// </returns> public AccessTokenResult CreateAccessToken(IAccessTokenRequest accessTokenRequestMessage) { // If your resource server and authorization server are different web apps, // consider using asymmetric keys instead of symmetric ones by setting different // properties on the access token below. var accessToken = new AuthorizationServerAccessToken { Lifetime = TimeSpan.FromHours(1), SymmetricKeyStore = this.CryptoKeyStore, }; var result = new AccessTokenResult(accessToken); return(result); }
/// <summary> /// Determines whether an access token request given a client credential grant should be authorized /// and if so records an authorization entry such that subsequent calls to <see cref="IsAuthorizationValid" /> would /// return <c>true</c>. /// </summary> /// <param name="accessRequest"> /// The access request the credentials came with. /// This may be useful if the authorization server wishes to apply some policy based on the client that is making the /// request. /// </param> /// <returns>A value that describes the result of the authorization check.</returns> /// <exception cref="NotSupportedException"> /// May be thrown if the authorization server does not support the client credential grant type. /// </exception> public AutomatedAuthorizationCheckResponse CheckAuthorizeClientCredentialsGrant( IAccessTokenRequest accessRequest) { Guard.NotNull(() => accessRequest, accessRequest); bool approved = IsClientExist(accessRequest.ClientIdentifier); var response = (new AutomatedAuthorizationCheckResponse(accessRequest, approved)); //TODO: Audit whether the authentication passed or failed return(response); }
/// <summary> /// Obtains parameters to go into the formulation of an access token. /// </summary> /// <param name="accessTokenRequestMessage">Details regarding the resources that the access token will grant access to, and the identity of the client /// that will receive that access. /// Based on this information the receiving resource server can be determined and the lifetime of the access /// token can be set based on the sensitivity of the resources.</param> /// <returns> /// A non-null parameters instance that DotNetOpenAuth will dispose after it has been used. /// </returns> public AccessTokenResult CreateAccessToken(IAccessTokenRequest accessTokenRequestMessage) { var accessToken = new AuthorizationServerAccessToken() { // For this sample, we assume just one resource server. // If this authorization server needs to mint access tokens for more than one resource server, // we'd look at the request message passed to us and decide which public key to return. ResourceServerEncryptionKey = OAuthResourceServer.CreateRSA(), }; var result = new AccessTokenResult(accessToken); return(result); }
/// <summary> /// Token创建 /// </summary> /// <param name="accessTokenRequestMessage"></param> /// <returns></returns> public AccessTokenResult CreateAccessToken(IAccessTokenRequest accessTokenRequestMessage) { var accessToken = new AuthorizationServerAccessToken(); accessToken.Lifetime = _configuration.TokenLifetime;//设置Token的有效时间 // 设置加密公钥 accessToken.ResourceServerEncryptionKey = (RSACryptoServiceProvider)_configuration.EncryptionCertificate.PublicKey.Key; // 设置签名私钥 accessToken.AccessTokenSigningKey = (RSACryptoServiceProvider)_configuration.SigningCertificate.PrivateKey; var result = new AccessTokenResult(accessToken); return result; }
// Generate an access token, given parameters in request that tell use what scopes to include, // and thus what resource's encryption key to use in addition to the authroization server key public AccessTokenResult CreateAccessToken(IAccessTokenRequest accessTokenRequestMessage) { var accessToken = new AuthorizationServerAccessToken { Lifetime = TimeSpan.FromMinutes(10) }; // could parameterize lifetime var targetResource = _resourceRepository.FindWithSupportedScopes(accessTokenRequestMessage.Scope); accessToken.ResourceServerEncryptionKey = targetResource.PublicTokenEncrypter; accessToken.AccessTokenSigningKey = _tokenSigner.GetSigner(); var result = new AccessTokenResult(accessToken); return(result); }
/// <summary> /// Token创建 /// </summary> /// <param name="accessTokenRequestMessage"></param> /// <returns></returns> public AccessTokenResult CreateAccessToken(IAccessTokenRequest accessTokenRequestMessage) { var accessToken = new AuthorizationServerAccessToken(); accessToken.Lifetime = _configuration.TokenLifetime;//设置Token的有效时间 // 设置加密公钥 accessToken.ResourceServerEncryptionKey = (RSACryptoServiceProvider)_configuration.EncryptionCertificate.PublicKey.Key; // 设置签名私钥 accessToken.AccessTokenSigningKey = (RSACryptoServiceProvider)_configuration.SigningCertificate.PrivateKey; var result = new AccessTokenResult(accessToken); return(result); }
public AutomatedAuthorizationCheckResponse CheckAuthorizeClientCredentialsGrant(IAccessTokenRequest accessRequest) { var client = ClientStore.SingleOrDefault(c => c.ClientIdentifier == accessRequest.ClientIdentifier) ?? new Client(); // Parse the scopes the client is authorized for var scopesClientIsAuthorizedFor = OAuthUtilities.SplitScopes(client.Scope); // Check if the scopes that are being requested are a subset of the scopes the user is authorized for. // If not, that means that the user has requested at least one scope it is not authorized for var clientIsAuthorizedForRequestedScopes = accessRequest.Scope.IsSubsetOf(scopesClientIsAuthorizedFor); // The token request is approved when the client is authorized for the requested scopes var isApproved = clientIsAuthorizedForRequestedScopes; return new AutomatedAuthorizationCheckResponse(accessRequest, isApproved); }
public AccessTokenResult CreateAccessToken(IAccessTokenRequest accessTokenRequestMessage) { var rsa = new RSACryptoServiceProvider(); rsa.ImportCspBlob(Convert.FromBase64String(ConfigurationManager.AppSettings["PrivateAsymmetricKey"])); var accessToken = new AuthorizationServerAccessToken() { AccessTokenSigningKey = rsa, ResourceServerEncryptionKey = rsa, }; var result = new AccessTokenResult(accessToken); result.AllowRefreshToken = false; return(result); }
// Used during client credentials flow. Before we get here, the client and secret will already have been verified // We're also ensuring the scopes requested are ok to give the client public AutomatedAuthorizationCheckResponse CheckAuthorizeClientCredentialsGrant(IAccessTokenRequest accessRequest) { // Find the client var client = _clientRepository.GetById(accessRequest.ClientIdentifier); // Determine the scopes the client is authorized for var scopesClientIsAuthorizedFor = client.SupportedScopes; // Check if the scopes that are being requested are a subset of the scopes the user is authorized for. // If not, that means that the user has requested at least one scope it is not authorized for var clientIsAuthorizedForRequestedScopes = accessRequest.Scope.IsSubsetOf(scopesClientIsAuthorizedFor); // The token request is approved when the client is authorized for the requested scopes var isApproved = clientIsAuthorizedForRequestedScopes; return new AutomatedAuthorizationCheckResponse(accessRequest, isApproved); }
public AccessTokenResult CreateAccessToken(IAccessTokenRequest accessTokenRequestMessage) { var accessToken = new AuthorizationServerAccessToken(); accessToken.Lifetime = TimeSpan.FromMinutes(2); // Using the certificate of our one and only resource server blindly accessToken.ResourceServerEncryptionKey = (RSACryptoServiceProvider)WebApiApplication.EncryptionCertificate.PublicKey.Key; accessToken.AccessTokenSigningKey = (RSACryptoServiceProvider)WebApiApplication.SigningCertificate.PrivateKey; var result = new AccessTokenResult(accessToken); return(result); }
/// <summary> /// Determines whether an access token request given a client credential grant should be authorized /// and if so records an authorization entry such that subsequent calls to <see cref="IsAuthorizationValid" /> would /// return <c>true</c>. /// </summary> /// <param name="accessRequest">The access request the credentials came with. /// This may be useful if the authorization server wishes to apply some policy based on the client that is making the request.</param> /// <returns> /// A value that describes the result of the authorization check. /// </returns> /// <exception cref="System.NotSupportedException"></exception> public AutomatedAuthorizationCheckResponse CheckAuthorizeClientCredentialsGrant(IAccessTokenRequest accessRequest) { // TODO: Consider implementing this if your application should support clients that access data that // doesn't belong to specific people, or clients that have elevated privileges and can access other // people's data. if (accessRequest.ClientAuthenticated) { // Before returning a positive response, be *very careful* to validate the requested access scope // to make sure it is appropriate for the requesting client. //throw new NotSupportedException(); return new AutomatedAuthorizationCheckResponse(accessRequest, true); } else { // Only authenticated clients should be given access. return new AutomatedAuthorizationCheckResponse(accessRequest, false); } }
public AccessTokenResult CreateAccessToken(IAccessTokenRequest accessTokenRequestMessage) { var accessToken = new AuthorizationServerAccessToken(); // TODO: work out and implement appropriate lifespan for access tokens based on your specific application requirements accessToken.Lifetime = TimeSpan.FromSeconds(15); // TODO: artificially shorten the access token's lifetime if the original authorization is due to expire sooner than the default lifespan. // (i.e. don't give out 7-day access tokens to somebody who has only granted your app access for 24 hours) // TODO: choose the appropriate signing keys for the specific resource server being used. // If you need to support multiple resource servers, there's two options. // 1) Use the same RSA key pair on every resource server. // 2) Select the appropriate key pair based on the requested scope (this assumes each scope maps to exactly one resource server) accessToken.ResourceServerEncryptionKey = dataServerKeys.PublicSigningKey; accessToken.AccessTokenSigningKey = authServerKeys.PrivateEncryptionKey; return (new AccessTokenResult(accessToken)); }
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); } }
public AccessTokenResult CreateAccessToken(IAccessTokenRequest accessTokenRequestMessage) { //Default to a lifespan of one hours for all tokens. var accessToken = new AuthorizationServerAccessToken { Lifetime = TimeSpan.FromHours(1), }; //Provide both signing and encryption keys for the token (the private/public relationships will be reversed //when the resource server digests the token accessToken.AccessTokenSigningKey = (RSACryptoServiceProvider)AuthorizationServerCertificate.PrivateKey; accessToken.ResourceServerEncryptionKey = (RSACryptoServiceProvider)ResourceServerCertificate.PublicKey.Key; //Return an access token result. var result = new AccessTokenResult(accessToken); return(result); }
public AccessTokenResult CreateAccessToken(IAccessTokenRequest accessTokenRequestMessage) { var accessToken = new AuthorizationServerAccessToken(); // TODO: work out and implement appropriate lifespan for access tokens based on your specific application requirements accessToken.Lifetime = TimeSpan.FromSeconds(_tokenLifetime); // TODO: artificially shorten the access token's lifetime if the original authorization is due to expire sooner than the default lifespan. // (i.e. don't give out 7-day access tokens to somebody who has only granted your app access for 24 hours) // TODO: choose the appropriate signing keys for the specific resource server being used. // If you need to support multiple resource servers, there's two options. // 1) Use the same RSA key pair on every resource server. // 2) Select the appropriate key pair based on the requested scope (this assumes each scope maps to exactly one resource server) accessToken.ResourceServerEncryptionKey = _dataServerKeys.PublicSigningKey; accessToken.AccessTokenSigningKey = _authServerKeys.PrivateEncryptionKey; return(new AccessTokenResult(accessToken)); }
public AccessTokenResult CreateAccessToken(IAccessTokenRequest accessTokenRequestMessage) { var accessToken = new MappingAccessToken(); int minutes; string setting = ConfigurationManager.AppSettings["AccessTokenLifeTime"]; if (!int.TryParse(setting, out minutes)) { minutes = 30; } accessToken.Lifetime = TimeSpan.FromMinutes(minutes); //accessToken.ResourceServerEncryptionKey = new RSACryptoServiceProvider(); //accessToken.ResourceServerEncryptionKey.ImportParameters(ResourceServerEncryptionPublicKey); //accessToken.AccessTokenSigningKey = CreateRSA(); var result = new AccessTokenResult(accessToken); return(result); }
public AccessTokenResult CreateAccessToken( IAccessTokenRequest accessTokenRequestMessage) { var token = new AuthorizationServerAccessToken(); token.Lifetime = TimeSpan.FromMinutes(10); var signCert = LoadCert(Config.STS_CERT); token.AccessTokenSigningKey = (RSACryptoServiceProvider)signCert.PrivateKey; var encryptCert = LoadCert(Config.SERVICE_CERT); token.ResourceServerEncryptionKey = (RSACryptoServiceProvider)encryptCert.PublicKey.Key; var result = new AccessTokenResult(token); return(result); }
public AccessTokenResult CreateAccessToken(IAccessTokenRequest accessTokenRequestMessage) { var accessToken = new AuthorizationServerAccessToken(); // Just for the sake of the sample, we use a short-lived token. This can be useful to mitigate the security risks // of access tokens that are used over standard HTTP. // But this is just the lifetime of the access token. The client can still renew it using their refresh token until // the authorization itself expires. accessToken.Lifetime = TimeSpan.FromMinutes(20); // Also take into account the remaining life of the authorization and artificially shorten the access token's lifetime // to account for that if necessary. //// TODO: code here PublicEncryptionKey = (RSACryptoServiceProvider)EncryptionCertificate.PublicKey.Key; accessToken.ResourceServerEncryptionKey = PublicEncryptionKey; PrivateSigningKey = (RSACryptoServiceProvider)SigningCertificate.PrivateKey; accessToken.AccessTokenSigningKey = PrivateSigningKey; return(new AccessTokenResult(accessToken)); }
public AccessTokenResult CreateAccessToken(IAccessTokenRequest accessTokenRequestMessage) { var accessToken = new AuthorizationServerAccessToken(); // Just for the sake of the sample, we use a short-lived token. This can be useful to mitigate the security risks // of access tokens that are used over standard HTTP. // But this is just the lifetime of the access token. The client can still renew it using their refresh token until // the authorization itself expires. accessToken.Lifetime = TimeSpan.FromMinutes(20); // Also take into account the remaining life of the authorization and artificially shorten the access token's lifetime // to account for that if necessary. //// TODO: code here _publicEncryptionKey = (RSACryptoServiceProvider)_encryptionCertificate.PublicKey.Key; accessToken.ResourceServerEncryptionKey = _publicEncryptionKey; _privateSigningKey = (RSACryptoServiceProvider)_signingCertificate.PrivateKey; accessToken.AccessTokenSigningKey = _privateSigningKey; return new AccessTokenResult(accessToken); }
/// <summary> /// Determines whether a given set of resource owner credentials is valid based on the authorization server's user database. /// </summary> /// <param name="userName">Username on the account.</param> /// <param name="password">The user's password.</param> /// <param name="accessRequest"> /// The access request the credentials came with. /// This may be useful if the authorization server wishes to apply some policy based on the client that is making the request. /// </param> /// <param name="canonicalUserName"> /// Receives the canonical username (normalized for the resource server) of the user, for valid credentials; /// Or <c>null</c> if the return value is false. /// </param> /// <returns> /// <c>true</c> if the given credentials are valid; otherwise, <c>false</c>. /// </returns> public bool IsResourceOwnerCredentialValid(string userName, string password, IAccessTokenRequest accessRequest, out string canonicalUserName) { canonicalUserName = null; // If the consumer exists. if (IsConsumer(accessRequest.ClientIdentifier)) { // Get the user for the consumer key var user = GetSpecificUser(userName, password); if (user != null) { canonicalUserName = userName; return(true); } else { return(false); } } else { throw new Exception("The client for consumer key : " + _clientIdentifier + " does not exist."); } }
public AccessTokenResult CreateAccessToken(IAccessTokenRequest accessTokenRequestMessage) { var accessToken = new AuthorizationServerAccessToken(); // Just for the sake of the sample, we use a short-lived token. This can be useful to mitigate the security risks // of access tokens that are used over standard HTTP. // But this is just the lifetime of the access token. The client can still renew it using their refresh token until // the authorization itself expires. accessToken.Lifetime = TimeSpan.FromMinutes(2); // Also take into account the remaining life of the authorization and artificially shorten the access token's lifetime // to account for that if necessary. //// TODO: code here // For this sample, we assume just one resource server. // If this authorization server needs to mint access tokens for more than one resource server, // we'd look at the request message passed to us and decide which public key to return. accessToken.ResourceServerEncryptionKey = new RSACryptoServiceProvider(); accessToken.ResourceServerEncryptionKey.ImportParameters(ResourceServerEncryptionPublicKey); accessToken.AccessTokenSigningKey = CreateRSA(); var result = new AccessTokenResult(accessToken); return result; }
/// <summary> /// Determines whether an access token request given a client credential grant should be authorized /// and if so records an authorization entry such that subsequent calls to <see cref="IsAuthorizationValid"/> would /// return <c>true</c>. /// </summary> /// <param name="accessRequest"> /// The access request the credentials came with. /// This may be useful if the authorization server wishes to apply some policy based on the client that is making the request. /// </param> /// <returns> /// <c>true</c> if the given credentials are valid and the authorization granted; otherwise, <c>false</c>. /// </returns> /// <exception cref="NotSupportedException"> /// May be thrown if the authorization server does not support the client credential grant type. /// </exception> public bool TryAuthorizeClientCredentialsGrant(IAccessTokenRequest accessRequest) { throw new NotImplementedException(); }
/// <summary> /// Determines whether a given set of resource owner credentials is valid based on the authorization server's user database /// and if so records an authorization entry such that subsequent calls to <see cref="IsAuthorizationValid"/> would /// return <c>true</c>. /// </summary> /// <param name="userName">Username on the account.</param> /// <param name="password">The user's password.</param> /// <param name="accessRequest"> /// The access request the credentials came with. /// This may be useful if the authorization server wishes to apply some policy based on the client that is making the request. /// </param> /// <param name="canonicalUserName"> /// Receives the canonical username (normalized for the resource server) of the user, for valid credentials; /// Or <c>null</c> if the return value is false. /// </param> /// <returns> /// <c>true</c> if the given credentials are valid and the authorization granted; otherwise, <c>false</c>. /// </returns> /// <exception cref="NotSupportedException"> /// May be thrown if the authorization server does not support the resource owner password credential grant type. /// </exception> public bool TryAuthorizeResourceOwnerCredentialGrant(string userName, string password, IAccessTokenRequest accessRequest, out string canonicalUserName) { // This web site delegates user authentication to OpenID Providers, and as such no users have local passwords with this server. throw new NotSupportedException(); }
/// <summary> /// Obtains parameters to go into the formulation of an access token. /// </summary> /// <param name="accessTokenRequestMessage">Details regarding the resources that the access token will grant access to, and the identity of the client /// that will receive that access. /// Based on this information the receiving resource server can be determined and the lifetime of the access /// token can be set based on the sensitivity of the resources.</param> /// <returns> /// A non-null parameters instance that DotNetOpenAuth will dispose after it has been used. /// </returns> AccessTokenParameters IAuthorizationServerHost.GetAccessTokenParameters(IAccessTokenRequest accessTokenRequestMessage) { Contract.Requires(accessTokenRequestMessage != null); Contract.Ensures(Contract.Result<AccessTokenParameters>() != null); throw new NotImplementedException(); }
public AutomatedAuthorizationCheckResponse CheckAuthorizeClientCredentialsGrant(IAccessTokenRequest accessRequest) { //TODO: if you're using web-based redirect login, this is where you verify the client's access token request is valid. return (new AutomatedAuthorizationCheckResponse(accessRequest, true)); }
public AutomatedAuthorizationCheckResponse(IAccessTokenRequest accessRequest, bool approved) { this.IsApproved = approved; this.ApprovedScope = new HashSet <string>(accessRequest.Scope); }
public AutomatedUserAuthorizationCheckResponse CheckAuthorizeResourceOwnerCredentialGrant(string userName, string password, IAccessTokenRequest accessRequest) { throw new NotImplementedException(); }
public AutomatedAuthorizationCheckResponse CheckAuthorizeClientCredentialsGrant(IAccessTokenRequest accessRequest) { throw new NotImplementedException(); }
/// <summary> /// Obtains the lifetime for a new access token. /// </summary> /// <param name="accessTokenRequestMessage">Details regarding the resources that the access token will grant access to, and the identity of the client /// that will receive that access. /// Based on this information the receiving resource server can be determined and the lifetime of the access /// token can be set based on the sensitivity of the resources.</param> /// <returns> /// Receives the lifetime for this access token. Note that within this lifetime, authorization <i>may</i> not be revokable. /// Short lifetimes are recommended (i.e. one hour), particularly when the client is not authenticated or /// the resources to which access is being granted are sensitive. /// </returns> TimeSpan IAuthorizationServer.GetAccessTokenLifetime(IAccessTokenRequest accessTokenRequestMessage) { Requires.NotNull(accessTokenRequestMessage, "accessTokenRequestMessage"); throw new NotImplementedException(); }
/// <summary> /// Obtains the encryption key for an access token being created. /// </summary> /// <param name="accessTokenRequestMessage">Details regarding the resources that the access token will grant access to, and the identity of the client /// that will receive that access. /// Based on this information the receiving resource server can be determined and the lifetime of the access /// token can be set based on the sensitivity of the resources.</param> /// <returns> /// The crypto service provider with the asymmetric public key to use for encrypting access tokens for a specific resource server. /// The caller is responsible to dispose of this value. /// </returns> RSACryptoServiceProvider IAuthorizationServer.GetResourceServerEncryptionKey(IAccessTokenRequest accessTokenRequestMessage) { Requires.NotNull(accessTokenRequestMessage, "accessTokenRequestMessage"); Contract.Ensures(Contract.Result<RSACryptoServiceProvider>() != null); throw new NotImplementedException(); }
public AutomatedAuthorizationCheckResponse CheckAuthorizeClientCredentialsGrant(IAccessTokenRequest accessRequest) { // This web site delegates user authentication to OpenID Providers, and as such no users have local passwords with this server. throw new NotImplementedException(); }
public AutomatedAuthorizationCheckResponse CheckAuthorizeClientCredentialsGrant(IAccessTokenRequest accessRequest) { if (accessRequest == null) { throw new ArgumentNullException(nameof(accessRequest)); } // Find the client var client = _lstClients.Single(consumerCandidate => consumerCandidate.ClientIdentifier == accessRequest.ClientIdentifier); // Parse the scopes the client is authorized for var scopesClientIsAuthorizedFor = OAuthUtilities.SplitScopes(client.Scope); // Check if the scopes that are being requested are a subset of the scopes the user is authorized for. // If not, that means that the user has requested at least one scope it is not authorized for var clientIsAuthorizedForRequestedScopes = accessRequest.Scope.IsSubsetOf(scopesClientIsAuthorizedFor); // The token request is approved when the client is authorized for the requested scopes var isApproved = clientIsAuthorizedForRequestedScopes; return(new AutomatedAuthorizationCheckResponse(accessRequest, isApproved)); }
/// <summary> /// Determines whether a given set of resource owner credentials is valid based on the authorization server's user database /// and if so records an authorization entry such that subsequent calls to <see cref="M:DotNetOpenAuth.OAuth2.IAuthorizationServerHost.IsAuthorizationValid(DotNetOpenAuth.OAuth2.ChannelElements.IAuthorizationDescription)" /> would /// return <c>true</c>. /// </summary> /// <param name="userName">Username on the account.</param> /// <param name="password">The user's password.</param> /// <param name="accessRequest">The access request the credentials came with. /// This may be useful if the authorization server wishes to apply some policy based on the client that is making the request.</param> /// <returns> /// A value that describes the result of the authorization check. /// </returns> public AutomatedUserAuthorizationCheckResponse CheckAuthorizeResourceOwnerCredentialGrant(string userName, string password, IAccessTokenRequest accessRequest) { IOAuth2AuthorizationStoreAgent agent = DependencyInjection.Get <IOAuth2AuthorizationStoreAgent>(); var user = agent.GetUser(userName, password); // We use a fixed username and password to determine if the username/password combination is correct. var userCredentialsAreCorrect = user != null; // Add the user's scopes. IList <OAuth2Scope> scopes = agent.GetUserScopes(userName); scopes.Select(x => x.Code).ToList().ForEach(x => { accessRequest.Scope.Add(x); }); OAuth2UserIdentity userIdentity = agent.GetUserIdentity(userName); var _userIdentity = userIdentity.ToDataTransferValue(); accessRequest.ExtraData.Add(new KeyValuePair <string, string>("userIdentity", JsonConvert.SerializeObject(_userIdentity))); // The token request is approved when the user credentials are correct and the user is authorized for the requested scopes var isApproved = userCredentialsAreCorrect && UserIsAuthorizedForRequestedScopes(userName, accessRequest.Scope); return(new AutomatedUserAuthorizationCheckResponse(accessRequest, isApproved, userName)); }
public AutomatedUserAuthorizationCheckResponse CheckAuthorizeResourceOwnerCredentialGrant(string userName, string password, IAccessTokenRequest accessRequest) { //We're not demonstrating a RO Credential grant in this exercise, so let's not allow it at all. return(new AutomatedUserAuthorizationCheckResponse(accessRequest, false, null)); }
public AutomatedUserAuthorizationCheckResponse CheckAuthorizeResourceOwnerCredentialGrant(string userName, string password, IAccessTokenRequest accessRequest) { // This web site delegates user authentication to OpenID Providers, and as such no users have local passwords with this server. throw new NotSupportedException(); }
public AutomatedAuthorizationCheckResponse CheckAuthorizeClientCredentialsGrant(IAccessTokenRequest accessRequest) { if (accessRequest.ClientAuthenticated) { //If the client request is properly authenticated (in this case, the client_secret properly matches the client secret //set up in GetClient()), then we can provide an access token. return(new AutomatedAuthorizationCheckResponse(accessRequest, true)); } else { // Only authenticated clients should be given access. return(new AutomatedAuthorizationCheckResponse(accessRequest, false)); } }
public bool TryAuthorizeResourceOwnerCredentialGrant(string userName, string password, IAccessTokenRequest accessRequest, out string canonicalUserName) { // This web site delegates user authentication to OpenID Providers, and as such no users have local passwords with this server. throw new NotSupportedException(); }
public AutomatedAuthorizationCheckResponse CheckAuthorizeClientCredentialsGrant(IAccessTokenRequest accessRequest) { AutomatedUserAuthorizationCheckResponse response = new AutomatedUserAuthorizationCheckResponse(accessRequest, true, "test"); return(response); }
public bool TryAuthorizeClientCredentialsGrant(IAccessTokenRequest accessRequest) { throw new NotImplementedException(); }
public AutomatedUserAuthorizationCheckResponse CheckAuthorizeResourceOwnerCredentialGrant(string userName, string password, IAccessTokenRequest accessRequest) { //TODO: this is where the OAuth2 server checks the client username/password are correct. Replace this with your own implementation. var user = userStore.GetUser(userName); var approved = (user != null && user.VerifyPassword(password)); return (new AutomatedUserAuthorizationCheckResponse(accessRequest, approved, userName)); }
public AutomatedUserAuthorizationCheckResponse CheckAuthorizeResourceOwnerCredentialGrant(string userName, string password, IAccessTokenRequest accessRequest) { // Not supporting this flow, as it's not normally a good idea to have user give their credentials directly to the client throw new NotImplementedException(); }
/// <summary> /// Determines whether a given set of resource owner credentials is valid based on the authorization server's user database /// and if so records an authorization entry such that subsequent calls to <see cref="IsAuthorizationValid" /> would /// return <c>true</c>. /// </summary> /// <param name="userName">Username on the account.</param> /// <param name="password">The user's password.</param> /// <param name="accessRequest">The access request the credentials came with. /// This may be useful if the authorization server wishes to apply some policy based on the client that is making the request.</param> /// <returns> /// A value that describes the result of the authorization check. /// </returns> public AutomatedUserAuthorizationCheckResponse CheckAuthorizeResourceOwnerCredentialGrant(string userName, string password, IAccessTokenRequest accessRequest) { // This web site delegates user authentication to OpenID Providers, and as such no users have local passwords with this server. throw new NotSupportedException(); }
/// <summary> /// Determines whether a given set of resource owner credentials is valid based on the authorization server's user database /// and if so records an authorization entry such that subsequent calls to <see cref="IsAuthorizationValid" /> would /// return <c>true</c>. /// </summary> /// <param name="userName">Username on the account.</param> /// <param name="password">The user's password.</param> /// <param name="accessRequest">The access request the credentials came with. /// This may be useful if the authorization server wishes to apply some policy based on the client that is making the request.</param> /// <returns> /// A value that describes the result of the authorization check. /// </returns> /// <exception cref="System.NotSupportedException"></exception> public AutomatedUserAuthorizationCheckResponse CheckAuthorizeResourceOwnerCredentialGrant(string userName, string password, IAccessTokenRequest accessRequest) { // TODO: Consider only accepting resource owner credential grants from specific clients // based on accessRequest.ClientIdentifier and accessRequest.ClientAuthenticated. //if (1 == 1)//(Membership.ValidateUser(userName, password)) //{ // Add an entry to your authorization table to record that access was granted so that // you can conditionally return true from IsAuthorizationValid when the row is discovered. //// TODO: code here // Inform DotNetOpenAuth that it may proceed to issue an access token. var user = RedisHelp.GetLoginUserCacheNotNull(int.Parse(userName)); if (user.TempSecret != password) { return new AutomatedUserAuthorizationCheckResponse(accessRequest, false, null); } return new AutomatedUserAuthorizationCheckResponse(accessRequest, true, userName);//Membership.GetUser(userName).UserName); //} //else //{ // return new AutomatedUserAuthorizationCheckResponse(accessRequest, false, null); //} }
/// <summary> /// Determines whether an access token request given a client credential grant should be authorized /// and if so records an authorization entry such that subsequent calls to <see cref="M:DotNetOpenAuth.OAuth2.IAuthorizationServerHost.IsAuthorizationValid(DotNetOpenAuth.OAuth2.ChannelElements.IAuthorizationDescription)" /> would /// return <c>true</c>. /// </summary> /// <param name="accessRequest">The access request the credentials came with. /// This may be useful if the authorization server wishes to apply some policy based on the client that is making the request.</param> /// <returns> /// A value that describes the result of the authorization check. /// </returns> public AutomatedAuthorizationCheckResponse CheckAuthorizeClientCredentialsGrant(IAccessTokenRequest accessRequest) { // We define the scopes the client is authorized for. Once again, you would expect these scopes to be retrieved from // a persistent store. Note: the scopes a client is authorized for can very well differ between clients HashSet <string> scopesClientIsAuthorizedFor = new HashSet <string>(OAuthUtilities.ScopeStringComparer); scopesClientIsAuthorizedFor.Add("demo-client-scope"); // Check if the scopes that are being requested are a subset of the scopes the user is authorized for. // If not, that means that the user has requested at least one scope it is not authorized for bool clientIsAuthorizedForRequestedScopes = accessRequest.Scope.IsSubsetOf(scopesClientIsAuthorizedFor); // The token request is approved when the client is authorized for the requested scopes bool isApproved = clientIsAuthorizedForRequestedScopes; return(new AutomatedAuthorizationCheckResponse(accessRequest, isApproved)); }
/// <summary> /// Determines whether an access token request given a client credential grant should be authorized /// and if so records an authorization entry such that subsequent calls to <see cref="IsAuthorizationValid" /> would /// return <c>true</c>. /// </summary> /// <param name="accessRequest">The access request the credentials came with. /// This may be useful if the authorization server wishes to apply some policy based on the client that is making the request.</param> /// <returns> /// A value that describes the result of the authorization check. /// </returns> public AutomatedAuthorizationCheckResponse CheckAuthorizeClientCredentialsGrant(IAccessTokenRequest accessRequest) { throw new NotImplementedException(); }