Spring Security 关于Web请求级别保护的配置说明

Java-教程王 SpringSecurity 发布时间:2021-08-05 23:19:49 阅读数:5762 1
spring security在web中主要通过url来限制用户的访问和验证用户的权限,下文将讲述spring mvc集成spring security的示例分享

使用Servlet过滤器

在java的servlet开发中,我们可以在web.xml中配置过滤器,对url请求进行检测操作,spring security就是借助过滤器的特性为url添加了一堆过滤器,
从而达到权限的认证和授权操作
spring mvc 集成spring security必须在web.xml中配置以下过滤器,如下所示:
<filter>
     <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>
        org.springframework.web.filter.DelegatingFilterProxy
    </filter-class>
</filter>
注意事项:
    1.filter-name的名字必须为 springSecurityFilterChain --这是一个约定,名称不能修改
    2.DelegatingFilterProxy是Servelt过滤器的代理,其功能为将工作委托给一个javax.servlet.Filter实现类
       此实现类已经注册至Spring bean的上下文中,bean的id则为springSecurityFilterChain

配置最小化web安全性和拦截请求

<http auto-config="true">
     <intercept-url pattern="/userInfo/**" access="ROLE_ADMIN" />
</http>
1. 当我们在spring的配置文件中,加入以上代码,则代表访问/userInfo下的所有url请求,必须为ROLE_ADMIN角色的用户,才可以访问
2. auto-config=true时,则会自动生成一个登录界面
auto-config=true,也可以采用以下配置实现其效果
 
<http>
    <form-login />
  <!--HTTP 基本认证 -->
    <http-basic/>
  <!-- 可以通过logout-url属性设置用户退出的url-->
    <logout />
    <intercept pattern="/**" access="ROLE_DEMO" />
</http>
注意事项:
    在Spring security 3.0及以后加入了堆SpEL支持,此时我们可以将 use-expressions 设置为true,
 使其支持SpEL
-------------------------------------------------------
<http auto-config="true" use-expressions="true">
   ..
    <intercept-url pattern="/userInfo/**" access="hasRole('ROLE_ADMIN')">
</http>
 Spring Security 支持的所有SpEL表达式如下:
安全表达式  计算结果
authentication   用户认证对象
denyAll   否定所有,直接返回false
hasAnyRole(list of roles)   当用户被授权指定的任意权限,结果为true
hasRole(role) 当用户被授予了指定的权限,结果 为true
hasIpAddress(IP Adress) 用户地址
isAnonymous()   是否为匿名用户
isAuthenticated()   不是匿名用户
isFullyAuthenticated   不是匿名也不是remember-me认证
isRemberMe()   remember-me认证
permitAll 始终true
principal 用户主要信息对象

用户自定义登录表单

当我们设置了auto-config="true"时,此时如果未认证,则自动跳转至Spring security生成一个登录界面,
我们也可以通过下面的配置,使其跳转到我们指定的登录界面上
如下所示:
<http auto-config="true">
    <!-- 设置登录页配置 login-page指定了登录界面的视图,authentication-failure-url则设置失败后的重定向到相同的登陆界面-->
    <from-login login-processing-url="/static/checkLoginInfo"
    login-page="/login" 
    authentication-failure-url="/login?login_error=t">
</http>

注意事项:
    1.将form表单的action页面指向 /static/checkLoginInfo  (checkLoginInfo可以为任意名称),无需编写相应的Controller ,由Spring Security自动实现
    2.表单中的用户名的 表单名称必须为 username,密码的表单名称必须为 password
    3.如果需设置记住密码操作,需在表单中加入以下元素 :记住我的有效期,记住我的复选框
     
     <remember-me key="spitterKey" token-validity-seconds="2419200"/>
     <input  name="_spring_security_rember_me" type="checkbox"/>
   

强制请求使用https

使用以下设置后,无论是否使用Http,都会将请求重定向至https请求,例:
 <intercept pattern="/userInfo/**" access="ROLE_DEMO" requires-channel="https" />

版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaFramework/SpringSecurity/202108/637.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者