设定的闲置时间后注销用户

时间:2018-07-11 12:52:20

标签: angular authentication .net-core jwt session-timeout

我正在处理的应用程序在后端使用.NET Core 2 Web API,在前端使用Angular。我们已将Active Directory与JWT结合使用,设置了身份验证。 当前流程:按下登录按钮后,将调用一个端点,以检索与当前用户相对应的令牌。如果令牌有效/已成功检索,则用户已登录。按下注销按钮时,令牌将被删除,并且用户将被重定向到登录页面。 只有几个人可以访问我们的应用程序。我们希望每个登录用户在一段时间(例如30分钟)不活动后自动退出。我们怎样才能做到这一点?将由后端还是前端处理?

3 个答案:

答案 0 :(得分:0)

30分钟后,使用javascript setTimeout()函数调用注销API。

答案 1 :(得分:0)

您可以从两个方面检查不活动状态。

在服务器端,尝试将Cookie置于启动状态

public void ConfigureAuth(IAppBuilder app)
    {
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            ExpireTimeSpan = System.TimeSpan.FromMinutes(30),
            LoginPath = new PathString("/Account/Login"),
            LogoutPath = new PathString("/Account/LogOff")
        });

In client side,通过检测光标ou键盘的移动

<script type="text/javascript">
var idleTime = 0;
$(document).ready(function () {
    //Increment the idle time counter every minute.
    var idleInterval = setInterval(timerIncrement, 60000); // 1 minute

    //Zero the idle timer on mouse movement.
    $(this).mousemove(function (e) {
        idleTime = 0;
    });
    $(this).keypress(function (e) {
        idleTime = 0;
    });
});

function timerIncrement() {
    idleTime = idleTime + 1;
    if (idleTime > 29) { // 30 minutes
        //send request to logout
    }
}
</script>   

答案 2 :(得分:0)

使用ng2-idle模块来实现注销功能。 以下是app.component.ts在一段时间后退出的代码段,

constructor(
    private router: Router,
    private idle: Idle,
    private keepalive: Keepalive,
) {
    idle.setIdle(1800); // for 30 minutes
    // sets a timeout period of 5 seconds. after 10 seconds of inactivity, the user will be considered timed out.
    idle.setTimeout(5);
    // sets the default interrupts, in this case, things like clicks, scrolls, touches to the document
    idle.setInterrupts(DEFAULT_INTERRUPTSOURCES);

    //idle.onIdleEnd.subscribe(() => (this.idleState = 'No longer idle.'));
    idle.onTimeout.subscribe(() => {
        this.idleState = 'Timed out!';
        this.timedOut = true;
    });
    idle.onIdleStart.subscribe(() => {
        this.idleState = "You've gone idle!";
        this.router.navigate(['/home']); // redirect to home if idle for 30 minutes
    });
}