How to check if a user is logged in with spring-security?

吃可爱长大的小学妹 提交于 2019-12-25 06:58:44

问题


I've implemented ajax login/logout in my client code against a backend running spring-security.

What I need to know is how to tell whether or not the user is logged in.

For instance:

  • User logs in. This returns a 200 from the POST to /login. I could set some variable to track state on the client side.
  • User refreshes browser. Now the state is lost.

So, I want to know if there's some way from the client to check whether or not the user is authenticated and logged in purely from the client.

Is there such a way?


回答1:


In JSP, you can access request user prinicial (or) use spring security taglib to get authenticated user roles

Example: Access request user principal in JSP

<c:if test="${pageContext.request.userPrincipal.name != null}">
    <label>
     Hi ${pageContext.request.userPrincipal.name} ! Welcome to our site
    </label>
</c:if>

Example: A variable isAuthenticated depending on granted roles for user logged in.

<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

    <sec:authorize access="hasAnyAuthority('ROLE_ADMIN', 'ROLE_USER')" var="isAuthenticated">
    </sec:authorize>

    <c:out value="${isAuthenticated}"/>

Even you can enable/disable some html using the same tag

<sec:authorize access="hasAnyRole('ROLE_ADMIN')">
    <a href="delete/${file.id}">Delete</a>
</sec:authorize>

If you want to get from javascript, then you need to expose a backend method returning request.userPrincipal




回答2:


What I actually did was add an endpoint to respond to GET /login. It returns a 200 with the username in the response body when the user is logged in with a valid session. When the user is not logged in or has an invalid session the response returns a 401 (and no response body).

I then have handlers in the javascript code that bring up a login modal when it receives the 401 and does nothing when it receives the 200.

Works beautifully :)



来源:https://stackoverflow.com/questions/32448749/how-to-check-if-a-user-is-logged-in-with-spring-security

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!