英文:
Optional authentication using Keycloak
问题
目前,我拥有的大多数React SPA应用程序都要求在用户访问站点之前进行身份验证,这是在应用程序启动时在index.js
中完成的:
window.keycloak
.init({
onLoad: "login-required",
checkLoginIframe: false,
promiseType: "native",
})
.then((authenticated) => {
ReactDOM.render(<App />, document.getElementById("root"));
})
.catch(() => {
console.error("初始化失败");
});
然而,现在我需要允许用户以非经身份验证的方式浏览站点(基本上将身份验证变成可选)。只有当用户需要时,我才需要将她重定向到登录页面。
如何使用Keycloak实现这一点呢?
有一个类似的问题这里,但已经有5年了,而且似乎建议的某些库已经不推荐使用了。因此,我想知道是否有更好的方法。
英文:
Currently most of the React SPA applications I have, we require authentication before user can access the site, this is done using this inside the index.js
when the app starts:
window.keycloak
.init({
onLoad: "login-required",
checkLoginIframe: false,
promiseType: "native",
})
.then((authenticated) => {
ReactDOM.render(<App />, document.getElementById("root"));
})
.catch(() => {
console.error("failed to initialize");
});
However, now I need to allow the user to be able to browse the site also in an unauthenticated way (authentication becomes optional basically). And only when user desires, then I have to redirect her to login page.
How can I do this using keycloak?
There is a similar question here, but it is 5 years old and also the library which one of the answers seems to recommend seems to be deprecated. So I was wondering if there were better approaches.
答案1
得分: 1
将onLoad
选项更改为"check-sso"
,而不是"login-required"
。这将检查用户是否已经认证但不会强制登录。
onLoad: "check-sso",
在组件内部,使用Keycloak来检查用户是否已认证并重定向到登录页面。
import React from "react";
export default function ProtectedComponent(){
if(!window.keycloak.authenticated){
window.keycloak.login();
return null;
}
return <div>您不能通过</div>;
}
英文:
I had this issue a while ago.
Change the onLoad
option to "check-sso"
instead of "login-required"
. This checks if the user is authenticated but won't force to log in.
onLoad: "check-sso",
Inside components use Keycloak to check if the user is authenticated and redirect to the login page.
import React from "react";
export default function ProtectedComponent(){
if(!window.keycloak.authenticated){
window.keycloak.login();
return null;
}
return <div>U shall not pass</div>;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论