This would be a good answer for me except that I cannot get header based auth to work so I am attempting to do it with forms and am also getting CSRF. Any solution? I am trying to create a new topic using the API.
We will need more information to be able to help. Can you share a code snippet showing how you are trying to use the header based authentication?
The problem I’ve been having stems mostly from whenever I try to make a call with header based auth, the accepted headers are always “User-Api-Key” and “User-Client-Id” instead of “Api-Key” and “Api-Username” so I get CORS errors. I do not believe I need user based keys. I am just trying to do a simple authenticated request to create a new topic. If I try to use the “User-Api-Key” I am getting a 403 errors.
This is sample code (Angular Typescript), but should be similar to other setups:
createNewTopic(postBody: any) {
let url = "myserver.com/posts.json";
let CATEGORY_ARTICLES = 6;
let topicContent = `
<p>Some content
</p>
<p>Did that work?</p>
`;
let post = {
"title": "Tdk Test 1",
"raw": topicContent,
"category": CATEGORY_ARTICLES,
"target_usernames": "tdekoekkoek",
"archetype": "",
"created_at": new Date()
}
let headers = new HttpHeaders()
.set("Accept", "application/json")
.set("User-Api-Key", DISCOURSE_API_KEY)
.set("User-Key", "system")
.set("Content-Type", "application/x-www-form-urlencoded")
let options = {headers: headers};
return this.http.post(url, post, options);
}
user-api-key and user-client-id are a completely different method of authentication. Regular API keys won’t work with those headers. What happens when you use the correct header names? (api-key and api-username)
I get a CORS error because the server is expecting User-Api-Key. I examine the expected headers in the OPTIONS response and that is what it says. There is a similar topic elsewhere on this forum where a user was experiencing this when calling from a javascript app.
Oh, so you are trying to make this request from a client-side javascript application? That is not permitted for numerous reasons. For example, if you include an admin API key in the source code of your javascript app, any user could gain full admin access to your forum. Here is a previous topic on the subject.
Yes that is what I am trying to do. That should be more clearly documented. That has been my whole strategy since getting started with Discourse. I appreciate your help. Been battling with this for days and reading the documentation. Will have to rethink my whole approach as I am currently building a serverless application though I do have access to a node.js server.
This isn’t a restriction specific to Discourse - in general it is a bad idea to include admin credentials in the source code of a website.
If you can make the Discourse API call from your node.js server, that would probably be the best solution. If you need your application to be purely client-side, then requesting user-specific api keys is an option, although their setup is a lot more complex: User API keys specification
Frankly accessing APIs from client applications with CORS enabled is extremely common and standard. I can’t believe there is not a more secure way of doing this. An entire industry revolves around hosted APIs that are accessed from different domains. As for accessing with user api, I’ve seen how to create those, but am unclear about what the actual credentials are. I am always getting 403 permission denied when using that method.
나도 비슷한 상황에 있는 것 같습니다.
사용 사례에 대해 간단히 설명하면:
저는 Discourse를 백엔드로 사용하고 VueJS로 프론트엔드를 구축하고 있습니다. REST API만 단독으로 사용할 예정입니다. 플랫폼의 각 사용자를 위해 사용자 API 키를 생성하고, 인증을 위해 두 개의 헤더(Api-Key 및 Api-Username)를 모두 사용하고 있습니다.
각 사용자는 우리 서버와 안전하게 인증을 거친 후 인증을 위한 Discourse 토큰을 받습니다. 그리고 우리는 이 토큰을 VueJS 프론트엔드에서 API 요청(토픽 게시, 포스트 작성, 수정 등)을 보내는 데 사용하고자 합니다.
무엇이든 하드코딩되어 있지 않으며, 모든 토큰은 적절한 인증 후에 발급됩니다.
문제점:
app.yml에서 CORS를 활성화하고 관리자 설정의 보안 섹션에서 설정해 두었음에도 불구하고 CORS 오류 메시지를 받고 있습니다.
오류 내용: Request header field api-key is not allowed by Access-Control-Allow-Headers
저도 같은 이유로 CORS 오류 메시지를 겪고 있는 걸까요? "Api-Key"와 “Api-Username” 헤더를 사용할 때 CORS 요청이 차단되는 이유는 무엇인가요? 이 헤더들의 사용 사례를 오해하고 있는 것 같습니다.
수정:
제 오해에 대한 가설이 하나 있습니다. REST API의 “Generate an api_key for a user” 엔드포인트에서 사용자 API 키를 생성할 때, 해당 키에는 관리자 권한이 부여되는 건가요? 이 키는 단순히 게시와 댓글 작성용 사용자 키가 아닌가요? 만약 그렇다면 해당 제한 사항을 이해할 수 있습니다.
필요하다면 제 오해를 수정해 주십시오.
@david Discourse가 서버에서 HMAC으로 세션 시크릿에 서명하고, 그 세션 시크릿을 다시 해당 세션 내에서 서명하는 데 사용할 수 있게 하면 안 될까요? 만약 시크릿이 탈취되더라도, 세션 쿠키나 CSRF 논스까지 함께 탈취되지는 않을 것입니다. 이는 인증서 체인과 유사합니다. 루트 키를 브라우저에 저장할 필요가 없듯이 말입니다.
이것은 관리자 API 전용입니다. 제 이해를 따르면, 자바스크립트 클라이언트의 경우 위에서 언급했듯이 User API keys specification 을 확인해야 합니다.