首先,引入依赖:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>

引入此依赖之后,你的web程序将拥有以下功能:

  • 所有请求路径都需要认证
  • 不需要特定的角色和权限
  • 没有登录页面,使用HTTP基本身份认证
  • 只有一个用户,名称为user

配置SpringSecurity

springsecurity配置项,最好保存在一个单独的配置类中:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter { }

**配置用户认证方式**

首先,要解决的就是用户注册,保存用户的信息。springsecurity提供四种存储用户的方式:

  • 基于内存(生产肯定不使用)
  • 基于JDBC
  • 基于LDAP
  • 用户自定义(最常用)

使用其中任意一种方式,需要覆盖configure(AuthenticationManagerBuilder auth)方法:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
}
}

1.基于内存

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("zhangsan").password("123").authorities("ROLE_USER")
.and()
.withUser("lisi").password("456").authorities("ROLE_USER");
}

2.基于JDBC

@Autowired
DataSource dataSource; @Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication()
.dataSource(dataSource);
}

基于JDBC的方式,你必须有一些特定表表,而且字段满足其查询规则:

public static final String DEF_USERS_BY_USERNAME_QUERY =
"select username,password,enabled " +
"from users " +
"where username = ?";
public static final String DEF_AUTHORITIES_BY_USERNAME_QUERY =
"select username,authority " +
"from authorities " +
"where username = ?";
public static final String DEF_GROUP_AUTHORITIES_BY_USERNAME_QUERY =
"select g.id, g.group_name, ga.authority " +
"from groups g, group_members gm, group_authorities ga " +
"where gm.username = ? " +
"and g.id = ga.group_id " +
"and g.id = gm.group_id";

当然,你可以对这些语句进行一下修改:

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(dataSource)
.usersByUsernameQuery("select username, password, enabled from Users " +
"where username=?")
.authoritiesByUsernameQuery("select username, authority from UserAuthorities " +
"where username=?");

这有一个问题,你数据库中的密码可能是一种加密方式加密过的,而用户传递的是明文,比较的时候需要进行加密处理,springsecurity也提供了相应的功能:

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(dataSource)
.usersByUsernameQuery("select username, password, enabled from Users " +
"where username=?")
.authoritiesByUsernameQuery("select username, authority from UserAuthorities " +
"where username=?")
.passwordEncoder(new StandardPasswordEncoder("53cr3t");

passwordEncoder方法传递的是PasswordEncoder接口的实现,其默认提供了一些实现,如果都不满足,你可以实现这个接口:

  • BCryptPasswordEncoder

  • NoOpPasswordEncoder

  • Pbkdf2PasswordEncoder

  • SCryptPasswordEncoder

  • StandardPasswordEncoder(SHA-256)

3.基于LDAP

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.ldapAuthentication()
.userSearchBase("ou=people")
.userSearchFilter("(uid={0})")
.groupSearchBase("ou=groups")
.groupSearchFilter("member={0}")
.passwordCompare()
.passwordEncoder(new BCryptPasswordEncoder())
.passwordAttribute("passcode")
.contextSource()
.root("dc=tacocloud,dc=com")
.ldif("classpath:users.ldif");

4.用户自定义方式(最常用)

首先,你需要一个用户实体类,它实现UserDetails 接口,实现这个接口的目的是为框架提供更多的信息,你可以把它看作框架使用的实体类:

@Data
public class User implements UserDetails { private Long id;
private String username;
private String password;
private String fullname;
private String city;
private String phoneNumber; @Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return null;
} @Override
public boolean isAccountNonExpired() {
return false;
} @Override
public boolean isAccountNonLocked() {
return false;
} @Override
public boolean isCredentialsNonExpired() {
return false;
} @Override
public boolean isEnabled() {
return false;
}
}

有了实体类,你还需要Service逻辑层,springsecurity提供了UserDetailsService 接口,见名知意,你只要通过loadUserByUsername返回一个UserDetails对象就成,无论是基于文件、基于数据库、还是基于LDAP,剩下的对比判断交个框架完成:

@Service
public class UserService implements UserDetailsService { @Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
return null;
} }

最后,进行应用:

@Autowired
private UserDetailsService userDetailsService; @Bean
public PasswordEncoder encoder() {
return new StandardPasswordEncoder("53cr3t");
} @Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService)
.passwordEncoder(encoder());
}

**配置认证路径**

知道了如何认证,但现在有几个问题,比如,用户登录页面就不需要认证,可以用configure(HttpSecurity http)对认证路径进行配置:

@Override
protected void configure(HttpSecurity http) throws Exception {
}

你可以通过这个方法,实现以下功能:

  • 在提供接口服务前,判断请求必须满足某些条件
  • 配置登录页面
  • 允许用户注销登录
  • 跨站点伪造请求防护

1.保护请求

@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/design", "/orders").hasRole("ROLE_USER")
.antMatchers(“/”, "/**").permitAll();
}

要注意其顺序,除了hasRolepermitAll还有其它访问认证方法:

方法 作用
access(String) 如果给定的SpEL表达式的计算结果为true,则允许访问
anonymous() 允许访问匿名用户
authenticated() 允许访问经过身份验证的用户
denyAll() 无条件拒绝访问
fullyAuthenticated() 如果用户完全通过身份验证,则允许访问
hasAnyAuthority(String...) 如果用户具有任何给定权限,则允许访问
hasAnyRole(String...) 如果用户具有任何给定角色,则允许访问
hasAuthority(String) 如果用户具有给定权限,则允许访问
hasIpAddress(String) 如果请求来自给定的IP地址,则允许访问
hasRole(String) 如果用户具有给定角色,则允许访问
not() 否定任何其他访问方法的影响
permitAll() 允许无条件访问
rememberMe() 允许通过remember-me进行身份验证的用户访问

大部分方法是为特定方式准备的,但是access(String)可以使用SpEL进一些特殊的设置,但其中很大一部分也和上面的方法相同:

表达式 作用
authentication 用户的身份验证对象
denyAll 始终评估为false
hasAnyRole(list of roles) 如果用户具有任何给定角色,则为true
hasRole(role) 如果用户具有给定角色,则为true
hasIpAddress(IP address) 如果请求来自给定的IP地址,则为true
isAnonymous() 如果用户是匿名用户,则为true
isAuthenticated() 如果用户已通过身份验证,则为true
isFullyAuthenticated() 如果用户已完全通过身份验证,则为true(未通过remember-me进行身份验证)
isRememberMe() 如果用户通过remember-me进行身份验证,则为true
permitAll 始终评估为true
principal 用户的主要对象

示例:

@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/design", "/orders").access("hasRole('ROLE_USER')")
.antMatchers(“/”, "/**").access("permitAll");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/design", "/orders").access("hasRole('ROLE_USER') && " +
"T(java.util.Calendar).getInstance().get("+"T(java.util.Calendar).DAY_OF_WEEK) == " + "T(java.util.Calendar).TUESDAY")
.antMatchers(“/”, "/**").access("permitAll");
}

2.配置登录页面

@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/design", "/orders").access("hasRole('ROLE_USER')")
.antMatchers(“/”, "/**").access("permitAll")
.and()
.formLogin()
.loginPage("/login");
} // 增加视图处理器
@Overridepublic void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("home");
registry.addViewController("/login");
}

默认情况下,希望传递的是usernamepassword,当然你可以修改:

.and()
.formLogin()
.loginPage("/login")
.loginProcessingUrl("/authenticate")
.usernameParameter("user")
.passwordParameter("pwd")

也可修改默认登录成功的页面:

.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/design")

3.配置登出

.and()
.logout()
.logoutSuccessUrl("/")

4.csrf攻击

springsecurity默认开启了防止csrf攻击,你只需要在传递的时候加上:

<input type="hidden" name="_csrf" th:value="${_csrf.token}"/>

当然,你也可以关闭,但是不建议这样做:

.and()
.csrf()
.disable()

知道用户是谁

仅仅控制用户登录有时候是不够的,你可能还想在程序的其它地方获取已经登录的用户信息,有几种方式可以做到:

  • Principal对象注入控制器方法

  • Authentication对象注入控制器方法

  • 使用SecurityContextHolder获取安全上下文

  • 使用@AuthenticationPrincipal注解方法

1.将Principal对象注入控制器方法

@PostMappingpublic String processOrder(@Valid Order order, Errors errors,SessionStatus sessionStatus,Principal principal) {
...
User user = userRepository.findByUsername(principal.getName());
order.setUser(user);
...
}

2.将Authentication对象注入控制器方法

@PostMappingpublic String processOrder(@Valid Order order, Errors errors, SessionStatus sessionStatus, Authentication authentication) {
...
User user = (User) authentication.getPrincipal();
order.setUser(user);
...
}

3.使用SecurityContextHolder获取安全上下文

Authentication authentication =
SecurityContextHolder.getContext().getAuthentication();
User user = (User) authentication.getPrincipal();

4.使用@AuthenticationPrincipal注解方法

@PostMappingpublic String processOrder(@Valid Order order, Errors errors,SessionStatus sessionStatus, @AuthenticationPrincipal User user) {
if (errors.hasErrors()) {
return "orderForm";
}
order.setUser(user);
orderRepo.save(order);
sessionStatus.setComplete();
return "redirect:/";
}

使用SpringSecurity保护程序安全的更多相关文章

  1. 使用C#开发屏幕保护程序步骤

    本文介绍使用C#制作屏幕保护的方法,这个屏幕保护就是仿效视窗系统自带的字幕屏保. 屏幕保护程序的扩展名虽然是"scr",但其实是一个可执行的"exe"文件.但他 ...

  2. windows系统操作类和演示程序(关机,关闭显示器,打开屏幕保护程序,打开光驱等)

    /// <summary> /// 系统控制类,关机,关闭显示器,打开屏幕保存程序等 /// </summary> public class SystemPowerContro ...

  3. windows屏幕保护程序opengl模板

    Visual Studio 2013 屏幕保护程序opengl模板 ScreenSaver.cpp #define VC_EXTRALEAN #include <windows.h> #i ...

  4. SystemParametersInfo调置壁纸、屏幕保护程序

    应用SystemParametersInfo函数可以获取和设置数量众多的windows系统参数.这个小程序就是运用了SystemParametersInfo函数来设置桌面的墙纸,而且程序可以让我们选择 ...

  5. 使用 WPF 开发一个 Windows 屏幕保护程序

    最近有小伙伴问我如何可以让 Windows 静置一段时间不操作之后,显示一个特殊的界面.我想了想,屏幕保护程序可以做到这一点,而且,屏幕保护程序的开发也是非常简单的. 本文将介绍如何为 Windows ...

  6. Window权限维持(五):屏幕保护程序

    屏幕保护是Windows功能的一部分,使用户可以在一段时间不活动后放置屏幕消息或图形动画.众所周知,Windows的此功能被威胁参与者滥用为持久性方法.这是因为屏幕保护程序是具有.scr文件扩展名的可 ...

  7. 保护程序猿滴眼睛---修改VS 2012 编辑器颜色

    转载于http://blog.csdn.net/qing666888/article/details/8973216 字体,发现好多人选用 Consolas  ...确实挺好看的. 然后 修改背景色: ...

  8. c#制作一个屏幕保护程序

    代码已上传github 实现思路:纯黑窗体去边框,加入标签. 使用Timmer让windows 10标签运动.限制标签的行为. 代码: int deltX = 10;       int deltY ...

  9. 使用SpringSecurity保护你的Eureka.

    因为注册中心基本上都是自己的应用在使用,应用不是特别多,可以写死,如果应用很多,那么就写入数据库把 pom <dependency> <groupId>org.springfr ...

随机推荐

  1. WAMP运行原理

    Apache运行原理 Apache的诸多功能都是通过模块进行加载的,自己本身并不具备那么多功能. php文件动态网页请求原理 请求步骤: 1. 用户在浏览器中输入需要访问的网站的域名以及具体要请求的网 ...

  2. C# sql 批量插入数据库的语句

    //执行DataTable数据导入 public static int UpdateDt(string strConn, DataTable dt) { try { string tablaName ...

  3. 最近很火的MySQL:抛开复杂的架构设计,MySQL优化思想基本都在这

    优化一览图 优化 笔者将优化分为了两大类:软优化和硬优化.软优化一般是操作数据库即可:而硬优化则是操作服务器硬件及参数设置. 1.软优化 1)查询语句优化 首先我们可以用EXPLAIN或DESCRIB ...

  4. Linux升级GCC

    升级原因 测试需要使用DOClever,下载了最新的node8.11,运行node 时候报错 [root@app_test bin]# node www module.js:681 return pr ...

  5. 用泛型写Redis缓存与数据库操作工具类

    功能描述: 先从缓存获取数据,如果缓存没有,就从数据库获取数据,并设置到缓存中,返回数据. 如果数据库中没有数据,需要设置一个缓存标记flagKey,防止暴击访问数据库,用缓存保护数据库. 当删除缓存 ...

  6. Java性能权威指南读书笔记--之一

    JIT(即时编译) 解释型代码:程序可移植,相同的代码在任何有适当解释器的机器上,都能运行,但是速度慢. 编译型代码:速度快,电视不同CPU平台的代码无法兼容. java则是使用java的编译器先将其 ...

  7. 什么是https?http升级为https需要什么?

    一.什么是https? https是一种加密传输协议,网站使用https后可以避免敏感信息被第三方获取.https加密协议=SSL / TLS+http协议,也就是说,在传统的http协议上加上SSL ...

  8. 【原创】JAVA进程突然消失的原因?

    引言 值此七夕佳节,烟哥放弃了无数妹纸的邀约,坐在电脑面前码字,就是为了给读者带来新的知识,这是一件伟大的事业! 好吧,实际情况是没人约.为了化解尴尬,我决定卖力写文章,嗯,一定是我过于屌丝! 好了, ...

  9. 伪分布式Spark + Hive on Spark搭建

    Spark大数据平台有使用一段时间了,但大部分都是用于实验而搭建起来用的,搭建过Spark完全分布式,也搭建过用于测试的伪分布式.现在是写一遍随笔,记录一下曾经搭建过的环境,免得以后自己忘记了.也给和 ...

  10. Java基础的一些知识点(一):接口interface

    1.接口的含义 接口可以理解成统一的协议, 而接口中的属性也属于协议中的内容.但是接口的属性都是公共的,静态的,最终的. 接口的成员特点: 1.成员变量只能是常量,默认修饰符 public stati ...