可选的身份验证使用Keycloak

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

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: &quot;login-required&quot;,
    checkLoginIframe: false,
    promiseType: &quot;native&quot;,
  })
  .then((authenticated) =&gt; {
    ReactDOM.render(&lt;App /&gt;, document.getElementById(&quot;root&quot;));
  })
  .catch(() =&gt; {
    console.error(&quot;failed to initialize&quot;);
  });

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 &quot;check-sso&quot; instead of &quot;login-required&quot;. This checks if the user is authenticated but won't force to log in.

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

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

import React from &quot;react&quot;;

export default function ProtectedComponent(){
  if(!window.keycloak.authenticated){
    window.keycloak.login();
    return null;
  }
  return &lt;div&gt;U shall not pass&lt;/div&gt;;
}

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:

确定