Reputation: 1313
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:
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?
Upvotes: 2
Views: 4204
Reputation: 1313
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 :)
Upvotes: 0
Reputation: 1395
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
Upvotes: 4