Hi everyone,
I am building a Swift mobile app. For the login and authentication I am using auth0. I’ve been able to configure this correctly. When logging in, I get forwarded back to the app and the idToken shows all the relevant user data.
The problem I can’t wrap my head around is that I am unable to call my backend. I keep getting 401 unauthorized from my dotnet 7 backend which I configured to have authentication via jwtbearer in my program.cs
I have both an API( for the backend) and an application (for the swift app) in my auth0 dashboard.
For some reason, if I copy paste the access token in jwt.io (the one I am getting back from auth0 in the swift app), it is also encrypted. I am a bit lost and not sure how to proceed. To summarize:
- I want to authenticate users in my swift app. (account login and creation)
- After authenticating, I want to use the access token I got back to make API calls to my backend
Why does the backend not see the received access token as valid?
All the examples I can find in the docs only handle login and logout in the swift app, not calling a backend.
I’ve been struggling with this for an entire day already. I really hope you can help.
Program.cs
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.Authority = "{my authority}";
options.Audience = "{my audience}";
});
Auth0.plist
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Audience</key>
<string>{my audience}</string>
<key>ClientId</key>
<string>{my client ID}</string>
<key>Domain</key>
<string>{my domain}</string>
</dict>
</plist>
Backend API call in my Swift app
func addHouse(address: CreateAddress) async throws {
var accessToken = ""
do {
let credentials = try await AuthManager.shared.credentialsManager.credentials()
accessToken = credentials.accessToken
print(accessToken)
} catch {
print("Failed with: \(error)")
}
guard let url = URL(string: "\(baseURL)") else {
print("Missing URL")
return
}
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = "POST"
urlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")
urlRequest.setValue("Bearer \(accessToken)", forHTTPHeaderField: "Authorization")
print(urlRequest)
let parameters: [String: Any] = [
"street": address.street,
"number": address.number,
"box": address.box,
"zipCode": address.zipCode,
"city": address.city,
"country": address.country,
]
let jsonData = try JSONSerialization.data(withJSONObject: parameters, options: [])
urlRequest.httpBody = jsonData
let (data, response) = try await URLSession.shared.data(for: urlRequest)
guard (response as? HTTPURLResponse)?.statusCode == 201 else {
return
}
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
DispatchQueue.main.async {
do {
self.house = try decoder.decode(House.self, from: data)
} catch {
print("error when decoding house")
}
}
}