spring security 配置多个AuthenticationProvider
前言
发现很少关于spring security的文章,基本都是入门级的,配个UserServiceDetails或者配个路由控制就完事了,而且很多还是xml配置,国内通病...so,本文里的配置都是java配置,不涉及xml配置,事实上我也不会xml配置
spring security的大体介绍
spring security本身如果只是说配置,还是很简单易懂的(我也不知道网上说spring security难,难在哪里),简单不需要特别的功能,一个WebSecurityConfigurerAdapter的实现,然后实现UserServiceDetails就是简单的数据库验证了,这个我就不说了。
spring security大体上是由一堆Filter(所以才能在spring mvc前拦截请求)实现的,Filter有几个,登出Filter(LogoutFilter),用户名密码验证Filter(UsernamePasswordAuthenticationFilter)之类的,Filter再交由其他组件完成细分的功能,例如最常用的UsernamePasswordAuthenticationFilter会持有一个AuthenticationManager引用,AuthenticationManager顾名思义,验证管理器,负责验证的,但AuthenticationManager本身并不做具体的验证工作,AuthenticationManager持有一个AuthenticationProvider集合,AuthenticationProvider才是做验证工作的组件,AuthenticationManager和AuthenticationProvider的工作机制可以大概看一下这两个的java doc,然后成功失败都有相对应该Handler 。大体的spring security的验证工作流程就是这样了。
开始配置多AuthenticationProvider
首先,写一个内存认证的AuthenticationProvider,这里我简单地写一个只有root帐号的AuthenticationProvider
package com.scau.equipment.config.common.security.provider; import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component; import java.util.Arrays;
import java.util.List; /**
* Created by Administrator on 2017-05-10.
*/
@Component
public class InMemoryAuthenticationProvider implements AuthenticationProvider {
private final String adminName = "root";
private final String adminPassword = "root"; //根用户拥有全部的权限
private final List<GrantedAuthority> authorities = Arrays.asList(new SimpleGrantedAuthority("CAN_SEARCH"),
new SimpleGrantedAuthority("CAN_SEARCH"),
new SimpleGrantedAuthority("CAN_EXPORT"),
new SimpleGrantedAuthority("CAN_IMPORT"),
new SimpleGrantedAuthority("CAN_BORROW"),
new SimpleGrantedAuthority("CAN_RETURN"),
new SimpleGrantedAuthority("CAN_REPAIR"),
new SimpleGrantedAuthority("CAN_DISCARD"),
new SimpleGrantedAuthority("CAN_EMPOWERMENT"),
new SimpleGrantedAuthority("CAN_BREED")); @Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
if(isMatch(authentication)){
User user = new User(authentication.getName(),authentication.getCredentials().toString(),authorities);
return new UsernamePasswordAuthenticationToken(user,authentication.getCredentials(),authorities);
}
return null;
} @Override
public boolean supports(Class<?> authentication) {
return true;
} private boolean isMatch(Authentication authentication){
if(authentication.getName().equals(adminName)&&authentication.getCredentials().equals(adminPassword))
return true;
else
return false;
}
}
InMemoryAuthenticationProvider
support方法检查authentication的类型是不是这个AuthenticationProvider支持的,这里我简单地返回true,就是所有都支持,这里所说的authentication为什么会有多个类型,是因为多个AuthenticationProvider可以返回不同的Authentication。
public Authentication authenticate(Authentication authentication) throws AuthenticationException 方法就是验证过程。
如果AuthenticationProvider返回了null,AuthenticationManager会交给下一个支持authentication类型的AuthenticationProvider处理。
另外需要一个数据库认证的AuthenticationProvider,我们可以直接用spring security提供的DaoAuthenticationProvider,设置一下UserServiceDetails和PasswordEncoder就可以了
@Bean
DaoAuthenticationProvider daoAuthenticationProvider(){
DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
daoAuthenticationProvider.setPasswordEncoder(new BCryptPasswordEncoder());
daoAuthenticationProvider.setUserDetailsService(userServiceDetails);
return daoAuthenticationProvider;
}
DaoAuthenticationProvider
最后在WebSecurityConfigurerAdapter里配置一个含有以上两个AuthenticationProvider的AuthenticationManager,依然重用spring security提供的ProviderManager
package com.scau.equipment.config.common.security; import com.scau.equipment.config.common.security.handler.AjaxLoginFailureHandler;
import com.scau.equipment.config.common.security.handler.AjaxLoginSuccessHandler;
import com.scau.equipment.config.common.security.provider.InMemoryAuthenticationProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.authentication.configurers.provisioning.InMemoryUserDetailsManagerConfigurer;
import org.springframework.security.config.annotation.authentication.configurers.provisioning.UserDetailsManagerConfigurer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import java.util.Arrays;
import java.util.List; /**
* Created by Administrator on 2017/2/17.
*/
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired
UserDetailsService userServiceDetails; @Autowired
InMemoryAuthenticationProvider inMemoryAuthenticationProvider; @Bean
DaoAuthenticationProvider daoAuthenticationProvider(){
DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
daoAuthenticationProvider.setPasswordEncoder(new BCryptPasswordEncoder());
daoAuthenticationProvider.setUserDetailsService(userServiceDetails);
return daoAuthenticationProvider;
} @Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.rememberMe().alwaysRemember(true).tokenValiditySeconds(86400).and()
.authorizeRequests()
.antMatchers("/","/*swagger*/**", "/v2/api-docs").permitAll()
.anyRequest().authenticated().and()
.formLogin()
.loginPage("/")
.loginProcessingUrl("/login")
.successHandler(new AjaxLoginSuccessHandler())
.failureHandler(new AjaxLoginFailureHandler()).and()
.logout().logoutUrl("/logout").logoutSuccessUrl("/");
} @Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/public/**", "/webjars/**", "/v2/**", "/swagger**");
} @Override
protected AuthenticationManager authenticationManager() throws Exception {
ProviderManager authenticationManager = new ProviderManager(Arrays.asList(inMemoryAuthenticationProvider,daoAuthenticationProvider()));
//不擦除认证密码,擦除会导致TokenBasedRememberMeServices因为找不到Credentials再调用UserDetailsService而抛出UsernameNotFoundException
authenticationManager.setEraseCredentialsAfterAuthentication(false);
return authenticationManager;
} /**
* 这里需要提供UserDetailsService的原因是RememberMeServices需要用到
* @return
*/
@Override
protected UserDetailsService userDetailsService() {
return userServiceDetails;
}
}
WebSecurityConfigurerAdapter
基本上都是重用了原有的类,很多都是默认使用的,只不过为了修改下行为而重新配置。其实如果偷懒,直接用一个UserDetailsService,在里面做各种认证也是可以的~不过这样就没意思了
spring security 配置多个AuthenticationProvider的更多相关文章
- spring boot 之 spring security 配置
Spring Security简介 之前项目都是用shiro,但是时过境迁,spring security变得越来越流行.spring security的前身是Acegi, acegi 我也玩过,那都 ...
- Spring Security(06)——AuthenticationProvider
目录 1.1 用户信息从数据库获取 1.1.1 使用jdbc-user-service获取 1.1.2 直接使用JdbcDaoImpl 1.2 PasswordEncode ...
- Spring Security 入门(1-4-2)Spring Security - 认证过程之AuthenticationProvider的扩展补充说明
1.用户信息从数据库获取 通常我们的用户信息都不会向第一节示例中那样简单的写在配置文件中,而是从其它存储位置获取,比如数据库.根据之前的介绍我们知道用户信息是通过 UserDetailsService ...
- Spring Security配置个过滤器也这么卷
以前胖哥带大家用Spring Security过滤器实现了验证码认证,今天我们来改良一下验证码认证的配置方式,更符合Spring Security的设计风格,也更加内卷. CaptchaAuthent ...
- Spring学习日志之Spring Security配置
依赖引入 <dependency> <groupId>org.springframework.security</groupId> <artifactId&g ...
- Spring Security配置
更加优雅地配置Spring Securiy(使用Java配置和注解):https://www.cnblogs.com/xxzhuang/p/5960001.html 采用注解方式实现security: ...
- spring mvc 和spring security配置 web.xml设置
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmln ...
- 通过 Spring Security配置 解决X-Frame-Options deny 造成的页面空白 iframe调用问题
spring Security下,X-Frame-Options默认为DENY,非Spring Security环境下,X-Frame-Options的默认大多也是DENY,这种情况下,浏览器拒绝当前 ...
- spring mvc 和spring security配置 spring-servlet.xml和spring-security.xml设置
spring-servlet.xml配置 <?xml version="1.0" encoding="UTF-8"?> <beans xmln ...
随机推荐
- (转)开源分布式搜索平台ELK(Elasticsearch+Logstash+Kibana)入门学习资源索引
Github, Soundcloud, FogCreek, Stackoverflow, Foursquare,等公司通过elasticsearch提供搜索或大规模日志分析可视化等服务.博主近4个月搜 ...
- 如何写一手漂亮的 Vue
前几日听到一句生猛与激励并存,可怕与尴尬同在,最无奈也无解的话:"90后,你的中年危机已经杀到".这令我很受触动.显然,这有些夸张了,但就目前这日复一日的庸碌下去,眨眼的功夫,那情 ...
- 【C++】浅谈三大特性之一继承(二)
三,继承方式&访问限定符 派生类可以继承基类中除了构造函数和析构函数之外的所有成员,但是这些成员的访问属性是由继承方式决定的. 不同的继承方式下基类成员在派生类中的访问属性: 举例说明: (1 ...
- 【Spring】BeanFactory解析bean详解
在该文中来讲讲Spring框架中BeanFactory解析bean的过程,该文之前在小编原文中有发表过,要看原文的可以直接点击原文查看,先来看一个在Spring中一个基本的bean定义与使用. pac ...
- 老李分享:https协议
老李分享:https协议 最近我们看到很多站点使用 HTTPS 协议提供网页服务.通常情况下我们都是在一些包含机密信息的站点像银行看到 HTTPS 协议. 如果你访问 google,查看一下地址栏 ...
- VC++6.0中不兼容问题
记得上次用VC++6.0已经是很长一段时间之前的事情了.这次由于需要学习计算机图形学,要开始学这写一些算法之类的,我又开始了VC++之旅. 重新安装一个vc++,我用的是Visual C++ 6.0( ...
- JS高级学习路线——面向对象进阶
构造函数进阶 使用构造函数创建对象 用于创建对象 其除了是一个函数之外,我们又称之为构造对象的函数 - 简称构造函数 function Product(name,description){ //属性 ...
- 基于Flink的windows--简介
新的一年,新的开始,新的习惯,现在开始. 1.简介 Flink是德国一家公司名为dataArtisans的产品,2016年正式被apache提升为顶级项目(地位同spark.storm等开源架构).并 ...
- php 启动过程 - reqeust RSHUTDOWN 过程
php 启动过程 - reqeust RSHUTDOWN 过程 概述 request RSHUTDOWN 过程在请求结束后调用 调用触发 同 request RINIT 过程一样, 先是用 apach ...
- JavaScript高级程序设计---学习笔记(五)
1.2D上下文 1)填充与描边 填充和描边的两个操作取决于两个属性:fillStyle和strokeStyle.两个属性的值可以是字符串.渐变对象或模式对象,默认值都是#000000 例: html: ...