Ejemplo n.º 1
0
        /// <summary>
        /// Creates a security principal that may be used.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns>The <see cref="IPrincipal"/> instance that can be used for access control of resources.</returns>
        public IPrincipal CreatePrincipal(AccessProtectedResourceRequest request)
        {
            Requires.NotNull(request, "request");

            IServiceProviderAccessToken accessToken = this.TokenManager.GetAccessToken(request.AccessToken);

            return(OAuthPrincipal.CreatePrincipal(accessToken.Username, accessToken.Roles));
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Discovers what access the client should have considering the access token in the current request.
        /// </summary>
        /// <param name="httpRequestInfo">The HTTP request info.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <param name="requiredScopes">The set of scopes required to approve this request.</param>
        /// <returns>
        /// The principal that contains the user and roles that the access token is authorized for.  Never <c>null</c>.
        /// </returns>
        /// <exception cref="ProtocolFaultResponseException">Thrown when the client is not authorized.  This exception should be caught and the
        /// <see cref="ProtocolFaultResponseException.ErrorResponseMessage" /> message should be returned to the client.</exception>
        public virtual async Task <IPrincipal> GetPrincipalAsync(HttpRequestBase httpRequestInfo = null, CancellationToken cancellationToken = default(CancellationToken), params string[] requiredScopes)
        {
            AccessToken accessToken = await this.GetAccessTokenAsync(httpRequestInfo, cancellationToken, requiredScopes);

            // Mitigates attacks on this approach of differentiating clients from resource owners
            // by checking that a username doesn't look suspiciously engineered to appear like the other type.
            ErrorUtilities.VerifyProtocol(accessToken.User == null || string.IsNullOrEmpty(this.ClientPrincipalPrefix) || !accessToken.User.StartsWith(this.ClientPrincipalPrefix, StringComparison.OrdinalIgnoreCase), ResourceServerStrings.ResourceOwnerNameLooksLikeClientIdentifier);
            ErrorUtilities.VerifyProtocol(accessToken.ClientIdentifier == null || string.IsNullOrEmpty(this.ResourceOwnerPrincipalPrefix) || !accessToken.ClientIdentifier.StartsWith(this.ResourceOwnerPrincipalPrefix, StringComparison.OrdinalIgnoreCase), ResourceServerStrings.ClientIdentifierLooksLikeResourceOwnerName);

            string principalUserName = !string.IsNullOrEmpty(accessToken.User)
                                ? this.ResourceOwnerPrincipalPrefix + accessToken.User
                                : this.ClientPrincipalPrefix + accessToken.ClientIdentifier;

            return(OAuthPrincipal.CreatePrincipal(principalUserName, accessToken.Scope));
        }
        protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            try
            {
                var headers = request.Headers;
                if (headers.Authorization != null)
                {
                    if (headers.Authorization.Scheme.Equals("Bearer"))
                    {
                        string accessToken = request.Headers.Authorization.Parameter;

                        ResourceServer server = new ResourceServer(
                            new StandardAccessTokenAnalyzer(
                                (RSACryptoServiceProvider)WebApiApplication.SigningCertificate.PublicKey.Key,
                                (RSACryptoServiceProvider)WebApiApplication.EncryptionCertificate.PrivateKey
                                )
                            );

                        OAuthPrincipal principal = server.GetPrincipal() as OAuthPrincipal;
                        if (principal != null && principal.Identity != null && principal.Identity.IsAuthenticated)
                        {
                            var claims = new List <Claim>();

                            foreach (string scope in principal.Roles)
                            {
                                claims.Add(new Claim("http://www.my-contacts.com/contacts/OAuth20/claims/scope", scope));
                            }

                            claims.Add(new Claim(ClaimTypes.Name, principal.Identity.Name));

                            var identity     = new ClaimsIdentity(claims, "Bearer");
                            var newPrincipal = new ClaimsPrincipal(identity);

                            Thread.CurrentPrincipal = newPrincipal;

                            if (HttpContext.Current != null)
                            {
                                HttpContext.Current.User = newPrincipal;
                            }
                        }
                    }
                }

                var response = await base.SendAsync(request, cancellationToken);

                if (response.StatusCode == HttpStatusCode.Unauthorized)
                {
                    response.Headers.WwwAuthenticate.Add(
                        new AuthenticationHeaderValue("Bearer",
                                                      "error=\"invalid_token\""));
                }

                return(response);
            }
            catch (Exception)
            {
                var response = request.CreateResponse(HttpStatusCode.Unauthorized);

                response.Headers.WwwAuthenticate.Add(
                    new AuthenticationHeaderValue("Bearer", "error=\"invalid_token\""));

                return(response);
            }
        }