更加优雅地配置Spring Securiy(使用Java配置和注解)
Spring Security 借助一系列Servlet Filter 来提供安全性功能,但是借助Spring的小技巧,我们只需要配置一个Filer就可以了,DelegatingFilterProxy是一个特殊的Servlet Filter,它本身所做的工作并不多,只是将工作委托给一个javax.servlet.Filter 的实现类,这个实现类作为一个bean注册再Spring应用的上下文中。
如果了解过用xml配置spring security的朋友就知道,用基于xml配置Spring Security过程繁琐,而且不容易学习和入门,但是基于javaConfig和注解则大大简化了这一配置,下面我们来看看是如何用java的方式配置Spring Security
首先我们需要配置DelegatingFilterProxy,我们只需要拓展一个新类,该类实现了WebApplicationInitializer,因此Spring会发现它并用他在Web容器中注册DelegatingFilterProxy。
public class SecurityWebInitializer extends AbstractSecurityWebApplicationInitializer {
}
接下来我们需要启用Web安全性功能,也是只需要拓展一个类,Spring Security 必须配置在一个实现了WebSecurityConfigurer 的bean中,或者拓展WebSecurityConfigurerAdapter 。在Spring 应用上下文中,任何实现了WebSecurityConfigurerAdapter 的bean都可以用来配置Spring Security。常用的配置已贴上,也全都写上了对应的注释。
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailServiceImpl userDetailService;
//对每个请求进行细粒度安全性控制的关键在于重载一下方法
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()//该方法所返回的对象的方法来配置请求级别的安全细节
.antMatchers("/login")
.permitAll()//对于登录路径不进行拦截
.antMatchers("/show").authenticated()//authenticated()表示允许过的用户访问
.and()
.formLogin()//配置登录页面
.loginPage("/login")//登录页面的访问路径
.loginProcessingUrl("/check")//登录页面下表单提交的路径
.failureUrl("/login")//登录失败后跳转的路径
.defaultSuccessUrl("/show")//登录成功后默认跳转的路径
.and()
.csrf()//启用防跨站伪请求攻击,默认启用
.and()
.logout()//用户退出操作
.logoutUrl("/logout")//用户退出所访问的路径,需要使用Post方式
.permitAll()
.logoutSuccessUrl("/login?logout=true")
.and()
.authorizeRequests()
// //定义路径保护的配置方法
// .antMatchers(HttpMethod.GET,"/admin")
// .authenticated()
.antMatchers(HttpMethod.GET,"/message/**","/object/**").hasRole("USER")
.anyRequest().permitAll()
.and()
.rememberMe()//启用记住我功能
.tokenValiditySeconds(2419200)
;
}
//配置Spring Security的Filter链
@Override
public void configure(WebSecurity web) throws Exception {
super.configure(web);
}
//配置user-detail服务
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailService)
.passwordEncoder(new StandardPasswordEncoder("53cr3t"))//密码加密方式 ;
// auth.inMemoryAuthentication() //内置用户
// .withUser("user").password("user").roles("USER");
}
}
需要注意的有几点,如果是用xml配置的springmvc环境下,基于javaConfig和注解配置Spring Security同样适用,只需要确保Spring的上下文能够扫描到上述的两个类即可。
如果在JSP页面下使用Spring的表单标签,该标签默认会自动添加隐藏的CSRF token标签,即防跨站伪请求攻击,如果没有使用Spring的表单标签,则需要手动添加以下标签,尤其是进行logout登出时表单提交,在Form标签内必须保护以下内容。
<input type="hiden"
name="${_csrf.parameterName}"
value="${_csrf.token}"}
下面是登录页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="sf" uri="http://www.springframework.org/tags/form" %>
<html>
<head>
<title>login</title>
</head>
<body>
<sf:form action="check" method="post" commandName="user" >
用户名:<sf:input path="username"></sf:input>
password:<sf:password path="password"></sf:password>
<input id="remember_me" name="remember-me" type="checkbox">
<label for="remember_me" class="inline">Remember me</label> <input type="submit" value="提交" > </sf:form>
</body>
</html>
登出页面
<%@ page language="java" contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="sf" uri="http://www.springframework.org/tags/form" %>
<html>
<head>
<title>User Manager</title>
</head>
<body> <sf:form id="logoutForm" action="${ctx}/logout" method="post">
<a href="#" onclick="document.getElementById('logoutForm').submit();">注销</a>
</sf:form>
</body>
</html>
如果我们想要配置自定义认证和授权服务,则需要实现UserDetailsService
public class UserDetailServiceImpl implements UserDetailsService {
private static Logger logger=Logger.getLogger(UserDetailServiceImpl.class);
@Autowired
private IUserService userService;
@Autowired
private IRoleService roleService;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
logger.info("===========授权============"); User user= null;
List<Role> role=null;
try {
user = userService.findUserByUsername(username);
role=roleService.listRoleByUserId(user.getId());
logger.info("用户角色为:"+role);
} catch (BaseException e) {
e.printStackTrace();
}
List<GrantedAuthority> list= new ArrayList<GrantedAuthority>();
list.add(new SimpleGrantedAuthority("ROLE_"+role));
org.springframework.security.core.userdetails.User authUser = new
org.springframework.security.core.userdetails.User
(user.getUsername(),user.getPassword(),list); return authUser;
}
}
该配置将安全级别细分到角色。重写的方法传来的参数为登录的username,再通过该参数从数据库中获取用户,以及相对应的权限,最终通过 将用户、密码、权限传入并实例化org.springframework.security.core.userdetails.User ,从而授权结束。配置安全路径或者方法中的权限依据上述方法中获取并绑定的权限。至此我们就可以对路径进行安全权限保护了。
转载请注明出处:http://www.cnblogs.com/xxzhuang/p/5960001.html 多谢合作。
更加优雅地配置Spring Securiy(使用Java配置和注解)的更多相关文章
- Spring完全基于Java配置和集成Junit单元测试
要点: 配置继承WebApplicationInitializer的类作为启动类,相当于配置web.xml文件 使用@Configuration注解一个类,在类中的方式使用@Bean注解,则表名该方法 ...
- Spring Security基于Java配置
Maven依赖 <dependencies> <!-- ... other dependency elements ... --> <dependency> < ...
- spring-security-4 (2)spring security 基于Java配置的搭建
一.spring security的模块 搭建spring security首先我们要导入必须的jar,即maven的依赖.spring security按模块划分,一个模块对应一个jar. spri ...
- eclipse里面配置spring,提示java.lang.ClassNotFoundException:org.springframework.web.servlet.Dispatcher错误
在eclipse里面创建了一个Dynamic 项目,用到spring,一直提示java.lang.ClassNotFoundException: org.springframework.web.ser ...
- Spring中通过java的@Valid注解和@ControllerAdvice实现全局异常处理。
通过java原生的@Valid注解和spring的@ControllerAdvice和@ExceptionHandler实现全局异常处理的方法: controller中加入@Valid注解: @Req ...
- 【原创】Spring MVC项目搭建(使用Java配置)
一.使用Intellij idea,新建maven项目,选择maven-archetype-webapp. 二.在src/main下新建文件夹,命名为java,并标注为source folder. 三 ...
- Spring MVC + Security 4 初体验(Java配置版)
spring Version = 4.3.6.RELEASE springSecurityVersion = 4.2.1.RELEASE Gradle 3.0 + Eclipse Neno(4.6) ...
- Spring的Java配置方式—@Configuration和@Bean实现Java配置
Java配置是Spring4.x推荐的配置方式,可以完全替代xml配置. 1.@Configuration 和 @BeanSpring的Java配置方式是通过 @Configuration 和 @Be ...
- Spring Boot 2.0 配置图文教程
摘要: 原创出处 https://www.bysocket.com 「公众号:泥瓦匠BYSocket 」欢迎关注和转载,保留摘要,谢谢! 本章内容 自定义属性快速入门 外化配置 自动配置 自定义创建 ...
随机推荐
- 分享一本Swift好书
http://yuedu.baidu.com/ebook/6f6c3b1ef01dc281e43af000?pn=1&rf=http%3A%2F%2Fyuedu.baidu.com%2Febo ...
- 【linux】修改文件所属用户和组
使用chown命令可以修改文件或目录所属的用户: 命令:chown 用户 目录或文件名 例如:chown qq /home/qq (把home目录下的qq目录的拥有者改为qq用户) 使用chgrp命 ...
- 40页PPT勾画“互联网颠覆性思维”----诠释互联网思维
本文PPT内容涉及移动互联网的三个分支——移动电商.在线教育和新媒体. 不同领域一直是可以相互借鉴.相互渗透.相互学习的,在盈利模式和思维方式上有很多是共通的.
- MSSql使用SQL语句快速查看表对的就说明,及表字段描述及字段类型
--表描述 SELECT tbs.name 表名,ds.value 描述 FROM sys.extended_properties ds LEFT JOIN sysobjects tbs ON ds. ...
- 【python】日志模块
# -*- coding: utf-8 -*- """ Created on Thu Jul 09 09:36:59 2015 @author: dapenghuang ...
- 调用 google speech api (使用Google语音识别引擎)
完全参考自: http://mikepultz.com/2011/03/accessing-google-speech-api-chrome-11/ http://aiku.me/bar/104480 ...
- SQL Server 数据库操作类
/// <summary> /// SQLServerHelper的摘要说明. /// </summary> public class SQLServerHelper { pu ...
- cocos2d ios 环境搭建
一.下载cocos2d-x http://cocos2d-x.org/projects/cocos2d-x/wiki/Download cocos2d-x-2.1.4.zip @ June.18, 2 ...
- Axapta 3 COM Connector
Axapta 3 COM Connector Copy from blog Having fun setting up the COM+ connector for Enterprise Port ...
- drupal7 form模板复写方法
给form制作一个template 从官方的drupal api document中可得到form有#theme这个参数,它可以指定form使用一个模板来用于form的基本布局,#theme的值必须是 ...