Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9324893
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 19, 20262026-06-19T04:42:45+00:00 2026-06-19T04:42:45+00:00

I want to let users authenticate via SoundCloud for my ASP.NET MVC 4 project.

  • 0

I want to let users authenticate via SoundCloud for my ASP.NET MVC 4 project. Since there is no .NET SDK, I wrote a custom OAuth2Client to handle the authentication. After adding the client to my AuthConfig.cs, it appropriately showed up as an option to login. The problem is, when I click on the button to login, it always returns

Login Failure.

Unsuccessful login with service.

without even asking me to login in SoundCloud. What is the problem? I implemented a very similar client for GitHub and it worked with no problems.

Here is my client:

 public class SoundCloudOAuth2Client : OAuth2Client
 {
     private const string ENDUSERAUTHLINK = "https://soundcloud.com/connect";
     private const string TOKENLINK = "https://api.soundcloud.com/oauth2/token";
     private readonly string _clientID;
     private readonly string _clientSecret;

     public SoundCloudOAuth2Client(string clientID, string clientSecret) : base("SoundCloud")
     {
         if (string.IsNullOrWhiteSpace(clientID)) {
                throw new ArgumentNullException("clientID");
         }

         if (string.IsNullOrWhiteSpace(clientSecret)) {
                throw new ArgumentNullException("clientSecret");
         }

         _clientID = clientID;
         _clientSecret = clientSecret;
     }

     protected override Uri GetServiceLoginUrl(Uri returnUrl)
     {
         StringBuilder serviceUrl = new StringBuilder();
         serviceUrl.Append(ENDUSERAUTHLINK);
         serviceUrl.AppendFormat("?client_id={0}", _clientID);
         serviceUrl.AppendFormat("&response_type={0}", "code");
         serviceUrl.AppendFormat("&scope={0}", "non-expiring");
         serviceUrl.AppendFormat("&redirect_uri={0}", System.Uri.EscapeDataString(returnUrl.ToString()));

         return new Uri(serviceUrl.ToString());
     }

     public override void RequestAuthentication(HttpContextBase context, Uri returnUrl)
     {
         base.RequestAuthentication(context, returnUrl);
     }

     protected override IDictionary<string, string> GetUserData(string accessToken)
     {
         IDictionary<String, String> extraData = new Dictionary<String, String>();

         var webRequest = (HttpWebRequest)WebRequest.Create("https://api.soundcloud.com/me.json?oauth_token=" + accessToken);
         webRequest.Method = "GET";
         string response = "";
         using (HttpWebResponse webResponse = HttpWebResponse)webRequest.GetResponse())
         {
             using (StreamReader reader = new StreamReader(webResponse.GetResponseStream()))
             {
                 response = reader.ReadToEnd();
             }
         }

         var json = JObject.Parse(response);
         string id = (string)json["id"];
         string username = (string)json["username"];
         string permalinkUrl = (string)json["permalink_url"];

         extraData = new Dictionary<String, String>
         {
             {"SCAccessToken", accessToken},
             {"username", username}, 
             {"permalinkUrl", permalinkUrl}, 
             {"id", id}                                           
         };

         return extraData;
     }

     protected override string QueryAccessToken(Uri returnUrl, string authorizationCode)
     {
         StringBuilder postData = new StringBuilder();
         postData.AppendFormat("client_id={0}", this._clientID);
         postData.AppendFormat("&redirect_uri={0}", HttpUtility.UrlEncode(returnUrl.ToString()));
         postData.AppendFormat("&client_secret={0}", this._clientSecret);
         postData.AppendFormat("&grant_type={0}", "authorization_code");
         postData.AppendFormat("&code={0}", authorizationCode);

         string response = "";
         string accessToken = "";

         var webRequest = (HttpWebRequest)WebRequest.Create(TOKENLINK);    
         webRequest.Method = "POST";
         webRequest.ContentType = "application/x-www-form-urlencoded";

         using (Stream s = webRequest.GetRequestStream())
         {
             using (StreamWriter sw = new StreamWriter(s))
                    sw.Write(postData.ToString());
         }

         using (WebResponse webResponse = webRequest.GetResponse())
         {
             using (StreamReader reader = new StreamReader(webResponse.GetResponseStream()))
             {
                 response = reader.ReadToEnd();
             }
         }

         var json = JObject.Parse(response);
         accessToken = (string)json["access_token"];

         return accessToken;
     }

     public override AuthenticationResult VerifyAuthentication(HttpContextBase context, Uri returnPageUrl)
     {    
         string code = context.Request.QueryString["code"];  
         string u = context.Request.Url.ToString();

         if (string.IsNullOrEmpty(code))
         {
             return AuthenticationResult.Failed;
         }

         string accessToken = this.QueryAccessToken(returnPageUrl, code);
         if (accessToken == null)
         {
             return AuthenticationResult.Failed;
         }

         IDictionary<string, string> userData = this.GetUserData(accessToken);
         if (userData == null)
         {
             return AuthenticationResult.Failed;
         }

         string id = userData["id"];
         string name;

         if (!userData.TryGetValue("username", out name) && !userData.TryGetValue("name", out name))
         {
             name = id;
         }

         return new AuthenticationResult(
             isSuccessful: true, provider: "SoundCloud", providerUserId: id, userName: name, extraData: userData);
     }
 }

and the AuthConfig.cs:

 public static void RegisterAuth()
 {
     OAuthWebSecurity.RegisterClient(new SoundCloudOAuth2Client(
         clientID: MyValues.MyClientID,
         clientSecret: MyValues.MyClientSECRET), 
         displayName: "SoundCloud",
         extraData: null);

     OAuthWebSecurity.RegisterClient(new GitHubOAuth2Client(
         appId: MyValues.GITHUBAPPID,
         appSecret: MyValues.GITHUBAPPSECRET), "GitHub", null);

     OAuthWebSecurity.RegisterGoogleClient();
     OAuthWebSecurity.RegisterYahooClient();
 }
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-19T04:42:47+00:00Added an answer on June 19, 2026 at 4:42 am

    There are multiple issues to address, starting with the first function that runs: GetServiceLoginUrl(Uri returnUrl)

    The returnUrl, which is automatically created, contains ampersands, which SoundCloud does not like. You need to strip out the ampersands and ensure the “Redirect URI for Authentication” in your SoundCloud account exactly matches what is being sent (querystring and all). Here is an example of what was being sent as the returnURL by default:

    https://localhost:44301/Account/ExternalLoginCallback?__provider__=SoundCloud&__sid__=blahblahyoursid
    

    First step was to remove the &__sid__ value. You can strip out sid value and pass it as the state parameter, just in case you ever need it. The new function looks like this:

    protected override Uri GetServiceLoginUrl(Uri returnUrl)
    {
        StringBuilder serviceUrl = new StringBuilder();
        string sid = String.Empty;
        if (returnUrl.ToString().Contains("__sid__"))
        {
            int index = returnUrl.ToString().IndexOf("__sid__") + 8;
            int len = returnUrl.ToString().Length;
            sid = returnUrl.ToString().Substring(index, len - index-1);
        }
    
        string redirectUri = returnUrl.ToString().Contains('&') ? 
        returnUrl.ToString().Substring(0,returnUrl.ToString().IndexOf("&")) : 
        returnUrl.ToString();
        serviceUrl.Append(ENDUSERAUTHLINK);
        serviceUrl.AppendFormat("?client_id={0}", _clientID);
        serviceUrl.AppendFormat("&response_type={0}", "code");
        serviceUrl.AppendFormat("&scope={0}", "non-expiring");
        serviceUrl.AppendFormat("&state={0}", sid);
        serviceUrl.AppendFormat("&redirect_uri={0}", System.Uri.EscapeDataString(redirectUri));
    
        return new Uri(serviceUrl.ToString());
    }
    

    That solves part of the problem. The redirect URI in SoundlCoud now is simply https://localhost:44301/Account/ExternalLoginCallback?__provider__=SoundCloud). But trying to authenticate will still return false. The next issue to address is in AccountController.cs, specifically:

    [AllowAnonymous]
    public ActionResult ExternalLoginCallback(string returnUrl)
    

    because in the first line, it tries to return:

    AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication(Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));
    

    and this doesn’t run for my custom OAuth2Client, since VerifyAuthentication takes different parameters. Fix it by detecting if it is the SoundCloud client and then use the custom VerifyAuthentication:

    [AllowAnonymous]
    public ActionResult ExternalLoginCallback(string returnUrl)
    {
        AuthenticationResult result;
        var context = this.HttpContext;
        string p = Tools.GetProviderNameFromQueryString(context.Request.QueryString);
    
        if (!String.IsNullOrEmpty(p) && p.ToLower() == "soundcloud")
        {
            result = new SoundCloudOAuth2Client(
                    clientID: MyValues.SCCLIENTID,
                    clientSecret: MyValues.SCCLIENTSECRET).VerifyAuthentication(this.HttpContext, new Uri(String.Format("{0}/Account/ExternalLoginCallback?__provider__=SoundCloud", context.Request.Url.GetLeftPart(UriPartial.Authority).ToString())));
        }
        else
        {
            result = OAuthWebSecurity.VerifyAuthentication(Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));
        }
    

    where

    public static string GetProviderNameFromQueryString(NameValueCollection queryString)
    {
        var result = queryString["__provider__"];
        ///commented out stuff
        return result;
    }
    

    After that, everything works fine and you can successfully authenticate. You can configure GetUserData to get whatever SoundCloud data you want to save and then save it off to your UserProfile or related table. The key part is that SCAccessToken because that is what you will need in the future to upload to their account.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I want to let users record video via webcam and then upload the recorded
We want to let users click a thumbs up or thumbs down button from
I want to let users upload Images. The file gets re-named (by adding the
In my open source app, I want to let users insert a picture/video/sound/etc .
I'm using CodeIgniter + Zend libraries. I want to let users upload videos to
Let's say I have thousands of users and I want to make the passwords
I want to build a flash app to let me and my users snap
I want to implement functionality which let user share posts by other users similar
Let's say, I want the users to be able to customize the layout/format of
I am working on an ASP.NET website which uses forms authentication with a custom

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.