Jump to content

rest authentication started failing with build 5886


TheShanMan

Recommended Posts

TheShanMan

I have some powershell scripts that do a library refresh and they have stopped working. I'm not sure why. Generally I just reuse an old token but the token started failing (with a 401) so I tried going back to authenticating from scratch and even that is failing (on the AuthenticateByName call, with a 400).

 

Here is how I'm performing the full authentication. What's wrong here?

$body = @{ username="Adults"; password="mysha1password" }
$authresponse = Invoke-RestMethod -uri http://myserver:8096/Users/AuthenticateByName?format=json -Method Post -Body $body
$headers = @{ "X-MediaBrowser-Token"=$authresponse.AccessToken }
Invoke-RestMethod -uri http://myserver:8096/Library/Refresh -Method Post -Headers $headers

Link to comment
Share on other sites

TheShanMan

Also failing with build 5887. I'm obviously doing something wrong because other clients like the web interface and android can log in fine. But from the authentication documentation it's not clear to me what's wrong.

 

This is in my server log:

2016-02-24 23:07:32.9724 Info HttpServer: HTTP POST http://myserver:8096/Users/AuthenticateByName?format=json. UserAgent: Mozilla/5.0 (Windows NT; Windows NT 6.1; en-US) WindowsPowerShell/3.0
2016-02-24 23:07:32.9724 Info UserManager: Authentication request for Adults has succeeded.
2016-02-24 23:07:32.9724 Info SessionManager: Reissuing access token: eca92e6e0c8d4ae79227b69d0bd3dc31
2016-02-24 23:07:32.9724 Error DtoUtils: ServiceBase<TRequest>::Service Exception
	*** Error Report ***
	Version: 3.0.5887.0
	Command line: C:\Users\Jeff\AppData\Roaming\MediaBrowser-Server\system\MediaBrowser.ServerApplication.exe
	Operating system: Microsoft Windows NT 6.1.7601 Service Pack 1
	Processor count: 4
	64-Bit OS: True
	64-Bit Process: True
	Program data path: C:\Users\Jeff\AppData\Roaming\MediaBrowser-Server
	Application Path: C:\Users\Jeff\AppData\Roaming\MediaBrowser-Server\system\MediaBrowser.ServerApplication.exe
	Value cannot be null.
	Parameter name: appName
	System.ArgumentNullException
	   at MediaBrowser.Server.Implementations.Session.SessionManager.<LogSessionActivity>d__9.MoveNext()
	--- End of stack trace from previous location where exception was thrown ---
	   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
	   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
	   at MediaBrowser.Server.Implementations.Session.SessionManager.<AuthenticateNewSessionInternal>d__ec.MoveNext()
	--- End of stack trace from previous location where exception was thrown ---
	   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
	   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
	   at MediaBrowser.Api.UserService.<Post>d__17.MoveNext()

So it's an appName parameter but I can't seem to get it to work by adding it, so I guess I'm doing it wrong but again, I don't know what.

Link to comment
Share on other sites

TheShanMan

I'm not sure I follow. The first call (which is failing) is supposed to give me a token, isn't it?

Link to comment
Share on other sites

TheShanMan

OK, I wasn't setting the headers it says are required for every request so I added them (minus the UserId of course). It still fails, and the server log still says appName can't be null. So in other words, adding those headers didn't seem to make any difference.  :huh:

Link to comment
Share on other sites

then I would just compare your requests to the web client using the chrome debugger to find out what is missing. I am sure you are missing something from that wiki article because others have used it to build full featured apps.

Link to comment
Share on other sites

  • 1 month later...
donut114

@@TheShanMan - what did you end up doing? I'm trying to use powershell to access the Emby API but I can't seem to authenticate. I've tried debugging with Chrome and all I keep getting is the same error message about the missing parameter "appName".

Link to comment
Share on other sites

donut114

@@Luke - Thank you for looking at this thread. I have scoured that page and I believe I am following it. I have also looked at the example API code in github. It's obvious to me that I'm missing something and the Emby Server log is indicating such. Here I have pasted my anonymized powershell code along with a snippet from the server log.

 

 

Powershell code:

$headers = @{ "Authorization"="MediaBrowser";  "UserId"="06de764b4e52c00a3133f4fc0be087b0"; "Client"="Powershell"; "Device"="Windows10"; "DeviceId"="123456789"; "Version"="1.0.0.0"; "Content-type"="application/json"}
$body = @{ Username="myusername"; password="66f89609852077e281b688df1efd0c4aa5289d79"; passwordMd5 = "1d8501fc3f3548f62680a7f2ff753c9f"} | convertto-json
$authresponse = Invoke-RestMethod -uri http://localhost:8096/Users/AuthenticateByName -Method Post -Body $body -Headers $headers
 

Server log after executing the above code.

2016-04-19 11:38:49.0625 Info HttpServer: HTTP POST http://localhost:8096/Users/AuthenticateByName. UserAgent: Mozilla/5.0 (Windows NT; Windows NT 10.0; en-US) WindowsPowerShell/5.0.10586.122
2016-04-19 11:38:49.1985 Info UserManager: Authentication request for myusername has succeeded.
2016-04-19 11:38:49.1985 Info SessionManager: Reissuing access token: de69bd70bb6dfa0d47550b733545e016
2016-04-19 11:38:49.2375 Error DtoUtils: ServiceBase<TRequest>::Service Exception
*** Error Report ***
Version: 3.0.5930.0
Command line: C:\Users\myusername\AppData\Roaming\Emby-Server\System\MediaBrowser.ServerApplication.exe
Operating system: Microsoft Windows NT 6.2.9200.0
Processor count: 8
64-Bit OS: True
64-Bit Process: True
Program data path: C:\Users\myusername\AppData\Roaming\Emby-Server
Application Path: C:\Users\myusername\AppData\Roaming\Emby-Server\System\MediaBrowser.ServerApplication.exe
Value cannot be null.
Parameter name: appName
System.ArgumentNullException
  at MediaBrowser.Server.Implementations.Session.SessionManager.<LogSessionActivity>d__9.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
  at MediaBrowser.Server.Implementations.Session.SessionManager.<AuthenticateNewSessionInternal>d__f2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
  at MediaBrowser.Api.UserService.<Post>d__17.MoveNext()


2016-04-19 11:38:49.2375 Error HttpServer: Error processing request for /Users/AuthenticateByName
*** Error Report ***
Version: 3.0.5930.0
Command line: C:\Users\myusername\AppData\Roaming\Emby-Server\System\MediaBrowser.ServerApplication.exe
Operating system: Microsoft Windows NT 6.2.9200.0
Processor count: 8
64-Bit OS: True
64-Bit Process: True
Program data path: C:\Users\myusername\AppData\Roaming\Emby-Server
Application Path: C:\Users\myusername\AppData\Roaming\Emby-Server\System\MediaBrowser.ServerApplication.exe
Value cannot be null.
Parameter name: appName
ServiceStack.HttpError
No Stack Trace Available


2016-04-19 11:38:49.2375 Info HttpServer: HTTP Response 400 to ::1. Time: 177ms. http://localhost:8096/Users/AuthenticateByName
2016-04-19 11:38:49.3095 Info HttpServer: HTTP GET http://localhost:8096/emby/System/ActivityLog/Entries?startIndex=0&limit=7&minDate=2016-04-18T18:38:49.236Z. UserAgent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Safari/537.36 Edge/13.10586
2016-04-19 11:38:49.3095 Info HttpServer: HTTP Response 200 to ::1. Time: 4ms. http://localhost:8096/emby/System/ActivityLog/Entries?startIndex=0&limit=7&minDate=2016-04-18T18:38:49.236Z
2016-04-19 11:38:49.3095 Info HttpServer: HTTP GET http://localhost:8096/emby/System/ActivityLog/Entries?startIndex=0&limit=7&minDate=2016-04-18T18:38:49.306Z. UserAgent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Safari/537.36 Edge/13.10586
2016-04-19 11:38:49.3175 Info HttpServer: HTTP Response 200 to ::1. Time: 3ms. http://localhost:8096/emby/System/ActivityLog/Entries?startIndex=0&limit=7&minDate=2016-04-18T18:38:49.306Z
2016-04-19 11:38:49.3555 Info HttpServer: HTTP GET http://localhost:8096/emby/Packages/Updates?PackageType=UserInstalled. UserAgent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Safari/537.36 Edge/13.10586
2016-04-19 11:38:49.4105 Info HttpServer: HTTP Response 200 to ::1. Time: 55ms. http://localhost:8096/emby/Packages/Updates?PackageType=UserInstalled

It looks like I am authenticating successfully and the server is issuing a valid access token, but that access token is never returned to the calling script and is only available in the server log file (instead I get an error code 400 response). I have tested that I can use the access token in subsequent requests with success.

 

I want to be clear that I have tried this outside of powershell and I get the same response using the Advanced REST client plugin for google chrome. I'm missing something from my headers or body. My question is what is appName?

 

Thank you for your time.

Edited by donut114
Link to comment
Share on other sites

You are missing appName in your header.

Value cannot be null.
Parameter name: appName
Link to comment
Share on other sites

donut114

 

You are missing appName in your header.

Value cannot be null.
Parameter name: appName

 

Still no dice. I get the error message in the server log if I add appName to my header. Does it need to be a specific name? One where I grant it an API-key through the server dashboard?

$headers = @{ "Authorization"="MediaBrowser";  "UserId"="06de764b4e52c00a3133f4fc0be087b0"; "Client"="Powershell"; "Device"="Windows10"; "DeviceId"="123456789"; "Version"="1.0.0.0"; "Content-type"="application/json"; "appName"="Powershell"}
$body = @{ Username="myusername"; password="66f89609852077e281b688df1efd0c4aa5289d79"; passwordMd5 = "1d8501fc3f3548f62680a7f2ff753c9f"; appName = "Powershell" } | convertto-json
$authresponse = Invoke-RestMethod -uri http://localhost:8096/Users/AuthenticateByName?format=json -Method Post -Body $body -Headers $headers -ContentType 'application/json'
Link to comment
Share on other sites

sytone

Having the same issue in my script. What code in github handles this authentication process so I can review it and not have to run around the repo looking for it if you or luke have it at hand. Also can authenticate be updated with the new appName paramter so t is correct.

Link to comment
Share on other sites

sytone

Got it solved. The headers are not really headers...

 

There is one header called Authorization, its content is the rest of the data and not separate entries as Emby splits it on the comma character internally. If you look at the my new entry for header it is only one entry inthe hash and its value is the comma delimited entries. Also appName == Client when submitting the data to the endpoint. 


Function Get-StringHash([String] $String,$HashName = "MD5") 
{ 
    $StringBuilder = New-Object System.Text.StringBuilder 
    [System.Security.Cryptography.HashAlgorithm]::Create($HashName).ComputeHash([System.Text.Encoding]::UTF8.GetBytes($String))|%{ 
        [Void]$StringBuilder.Append($_.ToString("x2")) 
    } 
    $StringBuilder.ToString() 
}
$embyServerUrl = "http://homecentral:8096"
$embyClientName = "PowerShellScript"
$embyDeviceName = "PowerShellScriptEpisodeFiller"
$embyDeviceId = "1"
$embyApplicationVersion = "1.0.0";
 
function Get-EmbyAccessToken {
    [CmdletBinding()]
    param ($Username, $Password)
    $authUrl = "{0}/Users/AuthenticateByName?format=json" -f $embyServerUrl
    $sha1Pass = Get-StringHash -String $password -HashName "SHA1"
    $md5Pass = Get-StringHash -String $password 
    $postParams = (@{Username="$username";password="$sha1Pass";passwordMd5="$md5Pass"} | ConvertTo-Json)


    $headers = @{"Authorization"="MediaBrowser Client=`"$embyClientName`", Device=`"$embyDeviceName`", DeviceId=`"$embyDeviceId`", Version=`"$embyApplicationVersion`""}


    Write-Verbose ("authUrl={0},Username={1},sha1Pass={2},md5Pass={3},params={4}" -f $authUrl, $Username,$sha1Pass,$md5Pass,$postParams)
    return (Invoke-WebRequest -Uri $authUrl -Method POST -Body $postParams -ContentType "application/json" -Headers $headers)
} 


$authResult = Get-EmbyAccessToken -Username homeuser -Password ""
$user = $authResult.Content | ConvertFrom-Json
$user.AccessToken
  • Like 3
Link to comment
Share on other sites

donut114

That worked for me. I also thought that the header listed in the API documentation had a typo and missing the comma. I didn't realize the whole thing was the header. Thank you for resolving this!

Link to comment
Share on other sites

  • 2 years later...

That header is a mess. I'm still getting that the appName is missing after following your instructions.

 

I even get the same error using the curl command that the swagger api generates for me. @@softworkz

 

Is that header some kind of a workaround? Why not add the entries as separate headers in the post?

Link to comment
Share on other sites

That's the api we've always had. 

 

The only recent change is that you can use 'Emby' for 'Authorization' and  'X-Emby-Token' now, while 'MediaBrowser' and 'X-MediaBrowser-Token' is still working as well. 

Link to comment
Share on other sites

As a system developer, I would like to go to the swagger API and follow the instructions to be able to login. That is not possible today.

Swagger tells me that my curl command for a user login should be:

 

curl -X POST "http://192.168.0.100:8096/emby/Users/AuthenticateByName"-H "accept: application/json" -H "Content-Type: application/json" -d "{\"Username\":\"jjj\",\"Password\":\"ttt\",\"Pw\":\"ttt\"}"

 

That gives me the error that the value cannot be null: appName

 

If you do not know about the special case on the wiki, you are lost.

 

It would be an investment to add working examples for the common languages on the wiki, so you can start building apps and addons for emby.

 

Using the EmbyApiClient works well and I have a .NET application that I develop as well, but you cannot use the embyapiclient in some scenarios, such as in a xamarin app as there are some unsupported methods.

 

However, I found a solution finally :-)

 

c# (works with xamarin as well)

public async void GetJSON2()
        {
            string requestUri = "http://192.168.0.100:8096/emby/Users/AuthenticateByName"; 
            dynamic dynamicJson = new ExpandoObject();
            dynamicJson.Username = "xxxx";
            dynamicJson.Password = "yyyy";
            dynamicJson.Pw = "yyyy";
                       
            var json = Newtonsoft.Json.JsonConvert.SerializeObject(dynamicJson);
            
            string applicationName = "appname";
            string deviceName = "devicename";
            string deviceId = "deviceId";
            string applicationVersion = "1.0.0";
            
            var httpClient = new System.Net.Http.HttpClient();
            httpClient.DefaultRequestHeaders.Add("Authorization", "Emby Client=\"" + applicationName + "\", Device=\"" + deviceName + "\", DeviceId=\"" + deviceId + "\", Version=\"" + applicationVersion + "\"");
            System.Net.Http.HttpResponseMessage respon = await httpClient.PostAsync(requestUri, new StringContent(json, System.Text.Encoding.UTF8, "application/json"));
            string responJsonText = await respon.Content.ReadAsStringAsync();
        }
Edited by joggs
Link to comment
Share on other sites

In the next version we will have some changes for this:

  • The documentation link for this will point to the user-authentication wiki page instead of the general one
  • For the "/Users/AuthenticateByName" API, it will display the required header
    • It's named "X-Emby-Authorization" (equivalent to "Authorization")
    • It has a description explaining the required content
    • The description also states that it's equivalent to "Authorization"
      ("Authorization" couldn't be used because the swagger-ui layer removes it)
  • The curl statement will work
  • The error responses will be displayed correctly now - for all API calls!
    (no more "fetch failed" messages)
  • Like 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...