首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用react应用程序的OIDC客户端JS认证授权

使用react应用程序的OIDC客户端JS认证授权
EN

Stack Overflow用户
提问于 2020-07-04 16:57:16
回答 1查看 3.9K关注 0票数 0

我正在使用OIDC客户端使用react应用程序执行身份验证和授权。我能够成功登录后登录,我有一个导航菜单显示,如果用户是认证与否。

代码语言:javascript
复制
export default function NavMenu() {
    const authService = new AuthService();
    useSelector((state: ApplicationState) => state.oidcUser);
    const dispatch = useDispatch();
    const [state, setState] = useState({
        isLogedIn: false
    });
    const [open, setOpen] = React.useState(false);
    const close = () => {
        setOpen(false);
    };
    const menuClick =() => {
        setOpen(!open);
    };

    useEffect(() => {
        authService.getUser().then((user: any) => {
            if (user != null)
                setState({ isLogedIn: true });
            else
                setState({ isLogedIn: false })
        });

    });

    const login = () => {
        authService.startAuthentication(window.location.pathname);
    };
    const logout = () => {
        authService.logout();
    };

    const menuOptions = [
        'Save',
        'Edit',
        'Cut',
        'Copy',
        'Paste',
    ];

    return (<div>
        <TopAppBar>
            <TopAppBarRow>
                <TopAppBarSection align='start'>
                    <TopAppBarTitle>Falcon</TopAppBarTitle>
                </TopAppBarSection>
                <TopAppBarSection align='end' role='toolbar'>
                    <div>
                        {(() => {
                            if (!state.isLogedIn) {
                                return (
                                    <Button raised type="button" onClick={login}>Portal</Button>
                                )
                            } else {
                                return (
                                    <div>
                                        <Menu
                                            open={open}
                                            onClose={close}
                                            onSelected={(index, item) => console.log(index, item)}>
                                            <MenuList>
                                                {menuOptions.map((option, index) => (
                                                    <MenuListItem key={index}>
                                                        <MenuListItemText primaryText={option} />
                                                        {/* You can also use other components from list, which are documented below */}
                                                    </MenuListItem>
                                                ))}
                                            </MenuList>
                                        </Menu>
                                        <Fab onClick={menuClick} icon={<MaterialIcon icon="account_circle" />} />
                                    </div>
                                )
                            }
                        })()}
                    </div>
                </TopAppBarSection>
            </TopAppBarRow>
        </TopAppBar>
    </div>);
}

如果我用这个方法

代码语言:javascript
复制
useEffect(() => {
            authService.getUser().then((user: any) => {
                if (user != null)
                    setState({ isLogedIn: true });
                else
                    setState({ isLogedIn: false })
            });
        });

我从identity服务器获得连接/校验会话API上的无限循环。如果删除该方法,则显示菜单的If条件(state.isLogedIn)不能工作。

如何正确地处理用户。什么是进行OIDC客户端认证和授权的最佳方法?

Auth service

代码语言:javascript
复制
export class AuthService {
    public userManager: UserManager;
    private user: any = null;

    constructor() {
        const settings = this.getClientSettings();
        this.userManager = new UserManager(settings);
    }


    public isLoggedIn(): boolean {
        return this.user != null && this.user.access_token && !this.user.expired;
    }

    public getUser(): Promise<User | null> {
        return this.userManager.getUser().then((user) => this.user = user);
    }

    public login(): Promise<void> {
        return this.userManager.signinRedirect();
    }
    public logout(): Promise<void> {
        return this.userManager.signoutRedirect(this.getClientSettings().post_logout_redirect_uri);
    }

    public startAuthentication(returnUrl: string) {
        Log.info("[AuthService] startAuthentication", returnUrl);
        this.userManager.clearStaleState();
        this.userManager.signinRedirect({ data: { returnUrl: returnUrl } }).then(user => this.user = user).catch(err => {
            this.handleError(err);
            return err;
        });
    }

    private getClientSettings(): any {
        return {
            authority: "https://localhost:5001",
            client_id: "Local",
            redirect_uri: "https://localhost:5001/auth-callback",
            post_logout_redirect_uri: "https://localhost:5001",
            response_type: "code",
            automaticSilentRenew: true,
            scope: "profile openid email IdentityPortal.API offline_access",
            //filterProtocolClaims: environment.openID.filterProtocolClaims,
            loadUserInfo: true,
            monitorSession: true,
            silent_redirect_uri: "https://localhost:5001/silent-reniew.html",
            accessTokenExpiringNotificationTime: 20, //default 60
            //checkSessionInterval: 86400, //default 2000
            //silentRequestTimeout: 2000,
        };
    }

    handleError(error: any) {
        Log.error(error)
    }
}
EN

回答 1

Stack Overflow用户

发布于 2020-07-06 18:25:04

如果你想要比较一下,不妨看看我的反应样本:

我相当于你的AuthService是我的验证器。如果您得到一个重定向循环,那么可能是因为您没有调用OIDC的signInRedirectCallback()方法来处理登录响应。在您的代码中,我看不到对该调用的引用。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62731946

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档