在Spring Boot/Security + Google oAuth2中,如何确定用户是否已经通过身份验证?

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

In Spring Boot/Security + Google oAuth2, how do I determine if a user is already authenticated?

问题

背景:

我已成功将Google身份验证添加到我的网站。有一个工作的登录按钮(并将用户从数据库存储到会话中),以及一个注销按钮,用于从我的应用程序注销用户,但显然不能注销用户的Google登录。有一个菜单项,通过仅显示适当的登录或注销菜单项来反映身份验证,以及如果他们已经通过身份验证,还可以访问个人资料页面。在我的SecurityConfig.filterChain()方法中,我有

.antMatchers("/secure/**").authenticated()

以确保用户在未经身份验证的情况下无法进入站点的安全部分(例如:secure/xyz)。

问题:

然而,当用户返回我的网站(使用新会话)并仍然登录Google时,我的应用程序会认为用户已经经过身份验证,并允许通过浏览器地址栏(例如:secure/xyz)访问安全的URL,而无需重新登录。

我想知道当他们返回网站时,用户是否已通过身份验证,至少是为了UI目的(显示登录或注销)。将用户存储在会话中是不够的。我认为我需要一个SessionListener或HttpSessionIdListener来实现这一点,但我不确定应将什么代码放入sessionCreated()或sessionIdChanged()方法中以获取经过身份验证的用户的身份。我需要哪些代码?

英文:

Background:

I've successfully added Google authentication to my website. There's a Login button that works (and stores the user from the db into the session) as well as a Logout button that logs out the user from my application, but obviously not from Google also. There's a menu item that reflects that authentication by only displaying the appropriate Login or Logout menu item, plus access to a Profile page if they're authenticated. In my SecurityConfig.filterChain() method, I have

 .antMatchers("/secure/**").authenticated()

to ensure users can't get into the secure part of the site (ex: secure/xyz) without being authenticated.

Problem:

However, when a user returns to my website (with a new session) and is still logged into Google, my application thinks the user is authenticated and allows access to the secure URLs, via the browser address bar (ex: secure/xyz), without having to log in again.

I want to know if a user is authenticated when they return to the site, at the very least for UI purposes (displaying Login or Logout). Storing the User in the session is insufficient. I assume I need a SessionListener or a HttpSessionIdListener for this, but I'm not sure what code to put in the sessionCreated() or sessionIdChanged() method to get the identity of the authenticated user. What code do I need?

答案1

得分: 0

以下是翻译好的部分:

"实际解决方案表明我仍在学习。当用户返回到网站时,他们尚未通过身份验证。我之所以认为他们已经通过身份验证,是因为我在SecurityConfig.filterChain()中的顺序安排有误。一旦我将以下内容放在开头:

.antMatchers("/secure/**").authenticated()

一切开始按预期工作。"

英文:

Well, the actual solution show that I'm still learning. When the user returns back to the site, they are not already authenticated. I thought they were only because I had things in SecurityConfig.filterChain() in the wrong order. Once I put

.antMatchers("/secure/**").authenticated()

at the beginning, everything started working as expected.

huangapple
  • 本文由 发表于 2023年2月10日 05:48:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/75404760.html
匿名

发表评论

匿名网友

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

确定