Spring Security - check if web url is secure / protected

烂漫一生 提交于 2020-01-03 08:37:14

问题


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!


回答1:


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);
}



回答2:


I think you can use your own implementation for AccessDecisionVoter then just simply override Vote method and compare intercept url using filterInvocation.getRequestUrl(); method.

@Override
public int vote(Authentication authentication, FilterInvocation filterInvocation,
    Collection<ConfigAttribute> attributes) {
  String requestUrl = filterInvocation.getRequestUrl();
  ....
}



回答3:


We can mark it is as secure channel so converted to https:// url.

    <intercept-url pattern="/**" access="IS_AUTHENTICATED_FULLY" requires-channel="https" />

We can then use request.getScheme() to identify it. I used org.springframework.security.version 3.1.4.RELEASE



来源:https://stackoverflow.com/questions/12236448/spring-security-check-if-web-url-is-secure-protected

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