Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Security - check if web url is secure / protected

Is there a way to "ask" spring security if the current request is secure? Because even if I am authenticated I want to detect if I am in a secure protected URL or in a anonymous / public page

Thanks in advance!

like image 710
user1641877 Avatar asked Sep 02 '12 13:09

user1641877


1 Answers

Spring Security provides JSP tag support for this. For example:

<sec:authorize url="/admin">

This content will only be visible to users who are authorized to access the "/admin" URL.

</sec:authorize>

Thymeleaf provides a Spring Security Dialect that has direct support for checking URL authorization with Spring Security. For example:

<div sec:authorize-url="/admin">
    This will only be displayed if authenticated user can call the "/admin" URL.
</div>

If your technology does not support performing the check directly, you can easily use the WebInvocationPrivilegeEvaluator (this is the object that the JSP taglib and Thymeleaf use). For example, you can @Autowire an instance of WebInvocationPrivilegeEvaluator and use it directly. Obviously the syntax will vary depending on where you use it (i.e. GSP, Freemarker, etc), but here is an example in straight Java code.

@Autowired
WebInvocationPrivilegeEvaluator webPrivs;

public void useIt() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

    boolean hasAdminAccess = webPrivs.isAllowed("/admin", authentication);

    boolean hasAdminPostAccess = webPrivs.isAllowed(null, "/admin", "POST", authentication);
}
like image 163
Rob Winch Avatar answered Sep 28 '22 06:09

Rob Winch