可选的身份验证使用Keycloak

huangapple go评论146阅读模式
英文:

Optional authentication using Keycloak

问题

目前,我拥有的大多数React SPA应用程序都要求在用户访问站点之前进行身份验证,这是在应用程序启动时在index.js中完成的:

  1. window.keycloak
  2. .init({
  3. onLoad: "login-required",
  4. checkLoginIframe: false,
  5. promiseType: "native",
  6. })
  7. .then((authenticated) => {
  8. ReactDOM.render(<App />, document.getElementById("root"));
  9. })
  10. .catch(() => {
  11. console.error("初始化失败");
  12. });

然而,现在我需要允许用户以非经身份验证的方式浏览站点(基本上将身份验证变成可选)。只有当用户需要时,我才需要将她重定向到登录页面。

如何使用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:

  1. window.keycloak
  2. .init({
  3. onLoad: &quot;login-required&quot;,
  4. checkLoginIframe: false,
  5. promiseType: &quot;native&quot;,
  6. })
  7. .then((authenticated) =&gt; {
  8. ReactDOM.render(&lt;App /&gt;, document.getElementById(&quot;root&quot;));
  9. })
  10. .catch(() =&gt; {
  11. console.error(&quot;failed to initialize&quot;);
  12. });

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"。这将检查用户是否已经认证但不会强制登录。

  1. onLoad: "check-sso",

在组件内部,使用Keycloak来检查用户是否已认证并重定向到登录页面。

  1. import React from "react";
  2. export default function ProtectedComponent(){
  3. if(!window.keycloak.authenticated){
  4. window.keycloak.login();
  5. return null;
  6. }
  7. return <div>您不能通过</div>;
  8. }
英文:

I had this issue a while ago.

Change the onLoad option to &quot;check-sso&quot; instead of &quot;login-required&quot;. This checks if the user is authenticated but won't force to log in.

  1. onLoad: &quot;check-sso&quot;,

Inside components use Keycloak to check if the user is authenticated and redirect to the login page.

  1. import React from &quot;react&quot;;
  2. export default function ProtectedComponent(){
  3. if(!window.keycloak.authenticated){
  4. window.keycloak.login();
  5. return null;
  6. }
  7. return &lt;div&gt;U shall not pass&lt;/div&gt;;
  8. }

huangapple
  • 本文由 发表于 2023年8月10日 20:12:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/76875636.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定